code
stringlengths
4
1.01M
AT.prototype.atSepHelpers = { sepText: function(){ return T9n.get(AccountsTemplates.texts.sep, markIfMissing=false); }, };
/* * Date Format 1.2.3 * (c) 2007-2009 Steven Levithan <stevenlevithan.com> * MIT license * * Includes enhancements by Scott Trenda <scott.trenda.net> * and Kris Kowal <cixar.com/~kris.kowal/> * * Accepts a date, a mask, or a date and a mask. * Returns a formatted version of the given date. * The date defaults to the current date/time. * The mask defaults to dateFormat.masks.default. */ var dateFormat = function () { var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function (val, len) { val = String(val); len = len || 2; while (val.length < len) val = "0" + val; return val; }; // Regexes and supporting functions are cached through closure return function (date, mask, utc) { var dF = dateFormat; // You can't provide utc if you skip other args (use the "UTC:" mask prefix) if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) { mask = date; date = undefined; } // Passing date through Date applies Date.parse, if necessary date = date ? new Date(date) : new Date; if (isNaN(date)) throw SyntaxError("invalid date"); mask = String(dF.masks[mask] || mask || dF.masks["default"]); // Allow setting the utc argument via the mask if (mask.slice(0, 4) == "UTC:") { mask = mask.slice(4); utc = true; } var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = { d: d, dd: pad(d), ddd: dF.i18n.dayNames[D], dddd: dF.i18n.dayNames[D + 7], m: m + 1, mm: pad(m + 1), mmm: dF.i18n.monthNames[m], mmmm: dF.i18n.monthNames[m + 12], yy: String(y).slice(2), yyyy: y, h: H % 12 || 12, hh: pad(H % 12 || 12), H: H, HH: pad(H), M: M, MM: pad(M), s: s, ss: pad(s), l: pad(L, 3), L: pad(L > 99 ? Math.round(L / 10) : L), t: H < 12 ? "a" : "p", tt: H < 12 ? "am" : "pm", T: H < 12 ? "A" : "P", TT: H < 12 ? "AM" : "PM", Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""), o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }; return mask.replace(token, function ($0) { return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1); }); }; }(); // Some common format strings dateFormat.masks = { "default": "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:ss", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'" }; // Internationalization strings dateFormat.i18n = { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ] }; // For convenience... Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };
#ifndef _ALLOCA_H #define _ALLOCA_H #ifdef __cplusplus extern "C" { #endif #define __NEED_size_t #include <bits/alltypes.h> void *alloca(size_t); #ifdef __GNUC__ #define alloca __builtin_alloca #endif #ifdef __cplusplus } #endif #endif
app.controller("LayersLayergroupSimpleController", [ "$scope", function($scope) { angular.extend($scope, { center: { lat: 39, lng: -100, zoom: 3 }, layers: { baselayers: { xyz: { name: 'OpenStreetMap (XYZ)', url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', type: 'xyz' } }, overlays: {} } }); var tileLayer = { name: 'Countries', type: 'xyz', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.png', visible: true, layerOptions: { attribution: 'Map data &copy; 2013 Natural Earth | Data &copy; 2013 <a href="http://www.reporter-ohne-grenzen.de/ranglisten/rangliste-2013/">ROG/RSF</a>', maxZoom: 5 } }; var utfGrid = { name: 'UtfGrid', type: 'utfGrid', url: 'http://{s}.tiles.mapbox.com/v3/milkator.press_freedom/{z}/{x}/{y}.grid.json?callback={cb}', visible: true, pluginOptions: { maxZoom: 5, resolution: 4 } }; var group = { name: 'Group Layer', type: 'group', visible: true, layerOptions: { layers: [ tileLayer, utfGrid], maxZoom: 5 } }; $scope.layers['overlays']['Group Layer'] = group; $scope.$on('leafletDirectiveMap.utfgridMouseover', function(event, leafletEvent) { $scope.country = leafletEvent.data.name; }); }]);
/* * Copyright (C) 2010 The Android Open Source Project * 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. * * 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. */ #ifndef CPU_FEATURES_H #define CPU_FEATURES_H #include <sys/cdefs.h> #include <stdint.h> __BEGIN_DECLS /* A list of valid values returned by android_getCpuFamily(). * They describe the CPU Architecture of the current process. */ typedef enum { ANDROID_CPU_FAMILY_UNKNOWN = 0, ANDROID_CPU_FAMILY_ARM, ANDROID_CPU_FAMILY_X86, ANDROID_CPU_FAMILY_MIPS, ANDROID_CPU_FAMILY_ARM64, ANDROID_CPU_FAMILY_X86_64, ANDROID_CPU_FAMILY_MIPS64, ANDROID_CPU_FAMILY_MAX /* do not remove */ } AndroidCpuFamily; /* Return the CPU family of the current process. * * Note that this matches the bitness of the current process. I.e. when * running a 32-bit binary on a 64-bit capable CPU, this will return the * 32-bit CPU family value. */ extern AndroidCpuFamily android_getCpuFamily(void); /* Return a bitmap describing a set of optional CPU features that are * supported by the current device's CPU. The exact bit-flags returned * depend on the value returned by android_getCpuFamily(). See the * documentation for the ANDROID_CPU_*_FEATURE_* flags below for details. */ extern uint64_t android_getCpuFeatures(void); /* The list of feature flags for ANDROID_CPU_FAMILY_ARM that can be * recognized by the library (see note below for 64-bit ARM). Value details * are: * * VFPv2: * CPU supports the VFPv2 instruction set. Many, but not all, ARMv6 CPUs * support these instructions. VFPv2 is a subset of VFPv3 so this will * be set whenever VFPv3 is set too. * * ARMv7: * CPU supports the ARMv7-A basic instruction set. * This feature is mandated by the 'armeabi-v7a' ABI. * * VFPv3: * CPU supports the VFPv3-D16 instruction set, providing hardware FPU * support for single and double precision floating point registers. * Note that only 16 FPU registers are available by default, unless * the D32 bit is set too. This feature is also mandated by the * 'armeabi-v7a' ABI. * * VFP_D32: * CPU VFP optional extension that provides 32 FPU registers, * instead of 16. Note that ARM mandates this feature is the 'NEON' * feature is implemented by the CPU. * * NEON: * CPU FPU supports "ARM Advanced SIMD" instructions, also known as * NEON. Note that this mandates the VFP_D32 feature as well, per the * ARM Architecture specification. * * VFP_FP16: * Half-width floating precision VFP extension. If set, the CPU * supports instructions to perform floating-point operations on * 16-bit registers. This is part of the VFPv4 specification, but * not mandated by any Android ABI. * * VFP_FMA: * Fused multiply-accumulate VFP instructions extension. Also part of * the VFPv4 specification, but not mandated by any Android ABI. * * NEON_FMA: * Fused multiply-accumulate NEON instructions extension. Optional * extension from the VFPv4 specification, but not mandated by any * Android ABI. * * IDIV_ARM: * Integer division available in ARM mode. Only available * on recent CPUs (e.g. Cortex-A15). * * IDIV_THUMB2: * Integer division available in Thumb-2 mode. Only available * on recent CPUs (e.g. Cortex-A15). * * iWMMXt: * Optional extension that adds MMX registers and operations to an * ARM CPU. This is only available on a few XScale-based CPU designs * sold by Marvell. Pretty rare in practice. * * AES: * CPU supports AES instructions. These instructions are only * available for 32-bit applications running on ARMv8 CPU. * * CRC32: * CPU supports CRC32 instructions. These instructions are only * available for 32-bit applications running on ARMv8 CPU. * * SHA2: * CPU supports SHA2 instructions. These instructions are only * available for 32-bit applications running on ARMv8 CPU. * * SHA1: * CPU supports SHA1 instructions. These instructions are only * available for 32-bit applications running on ARMv8 CPU. * * PMULL: * CPU supports 64-bit PMULL and PMULL2 instructions. These * instructions are only available for 32-bit applications * running on ARMv8 CPU. * * If you want to tell the compiler to generate code that targets one of * the feature set above, you should probably use one of the following * flags (for more details, see technical note at the end of this file): * * -mfpu=vfp * -mfpu=vfpv2 * These are equivalent and tell GCC to use VFPv2 instructions for * floating-point operations. Use this if you want your code to * run on *some* ARMv6 devices, and any ARMv7-A device supported * by Android. * * Generated code requires VFPv2 feature. * * -mfpu=vfpv3-d16 * Tell GCC to use VFPv3 instructions (using only 16 FPU registers). * This should be generic code that runs on any CPU that supports the * 'armeabi-v7a' Android ABI. Note that no ARMv6 CPU supports this. * * Generated code requires VFPv3 feature. * * -mfpu=vfpv3 * Tell GCC to use VFPv3 instructions with 32 FPU registers. * Generated code requires VFPv3|VFP_D32 features. * * -mfpu=neon * Tell GCC to use VFPv3 instructions with 32 FPU registers, and * also support NEON intrinsics (see <arm_neon.h>). * Generated code requires VFPv3|VFP_D32|NEON features. * * -mfpu=vfpv4-d16 * Generated code requires VFPv3|VFP_FP16|VFP_FMA features. * * -mfpu=vfpv4 * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32 features. * * -mfpu=neon-vfpv4 * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32|NEON|NEON_FMA * features. * * -mcpu=cortex-a7 * -mcpu=cortex-a15 * Generated code requires VFPv3|VFP_FP16|VFP_FMA|VFP_D32| * NEON|NEON_FMA|IDIV_ARM|IDIV_THUMB2 * This flag implies -mfpu=neon-vfpv4. * * -mcpu=iwmmxt * Allows the use of iWMMXt instrinsics with GCC. * * IMPORTANT NOTE: These flags should only be tested when * android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM, i.e. this is a * 32-bit process. * * When running a 64-bit ARM process on an ARMv8 CPU, * android_getCpuFeatures() will return a different set of bitflags */ enum { ANDROID_CPU_ARM_FEATURE_ARMv7 = (1 << 0), ANDROID_CPU_ARM_FEATURE_VFPv3 = (1 << 1), ANDROID_CPU_ARM_FEATURE_NEON = (1 << 2), ANDROID_CPU_ARM_FEATURE_LDREX_STREX = (1 << 3), ANDROID_CPU_ARM_FEATURE_VFPv2 = (1 << 4), ANDROID_CPU_ARM_FEATURE_VFP_D32 = (1 << 5), ANDROID_CPU_ARM_FEATURE_VFP_FP16 = (1 << 6), ANDROID_CPU_ARM_FEATURE_VFP_FMA = (1 << 7), ANDROID_CPU_ARM_FEATURE_NEON_FMA = (1 << 8), ANDROID_CPU_ARM_FEATURE_IDIV_ARM = (1 << 9), ANDROID_CPU_ARM_FEATURE_IDIV_THUMB2 = (1 << 10), ANDROID_CPU_ARM_FEATURE_iWMMXt = (1 << 11), ANDROID_CPU_ARM_FEATURE_AES = (1 << 12), ANDROID_CPU_ARM_FEATURE_PMULL = (1 << 13), ANDROID_CPU_ARM_FEATURE_SHA1 = (1 << 14), ANDROID_CPU_ARM_FEATURE_SHA2 = (1 << 15), ANDROID_CPU_ARM_FEATURE_CRC32 = (1 << 16), }; /* The bit flags corresponding to the output of android_getCpuFeatures() * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_ARM64. Value details * are: * * FP: * CPU has Floating-point unit. * * ASIMD: * CPU has Advanced SIMD unit. * * AES: * CPU supports AES instructions. * * CRC32: * CPU supports CRC32 instructions. * * SHA2: * CPU supports SHA2 instructions. * * SHA1: * CPU supports SHA1 instructions. * * PMULL: * CPU supports 64-bit PMULL and PMULL2 instructions. */ enum { ANDROID_CPU_ARM64_FEATURE_FP = (1 << 0), ANDROID_CPU_ARM64_FEATURE_ASIMD = (1 << 1), ANDROID_CPU_ARM64_FEATURE_AES = (1 << 2), ANDROID_CPU_ARM64_FEATURE_PMULL = (1 << 3), ANDROID_CPU_ARM64_FEATURE_SHA1 = (1 << 4), ANDROID_CPU_ARM64_FEATURE_SHA2 = (1 << 5), ANDROID_CPU_ARM64_FEATURE_CRC32 = (1 << 6), }; /* The bit flags corresponding to the output of android_getCpuFeatures() * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_X86 or * ANDROID_CPU_FAMILY_X86_64. */ enum { ANDROID_CPU_X86_FEATURE_SSSE3 = (1 << 0), ANDROID_CPU_X86_FEATURE_POPCNT = (1 << 1), ANDROID_CPU_X86_FEATURE_MOVBE = (1 << 2), ANDROID_CPU_X86_FEATURE_SSE4_1 = (1 << 3), ANDROID_CPU_X86_FEATURE_SSE4_2 = (1 << 4), ANDROID_CPU_X86_FEATURE_AES_NI = (1 << 5), ANDROID_CPU_X86_FEATURE_AVX = (1 << 6), ANDROID_CPU_X86_FEATURE_RDRAND = (1 << 7), ANDROID_CPU_X86_FEATURE_AVX2 = (1 << 8), ANDROID_CPU_X86_FEATURE_SHA_NI = (1 << 9), }; /* The bit flags corresponding to the output of android_getCpuFeatures() * when android_getCpuFamily() returns ANDROID_CPU_FAMILY_MIPS * or ANDROID_CPU_FAMILY_MIPS64. Values are: * * R6: * CPU executes MIPS Release 6 instructions natively, and * supports obsoleted R1..R5 instructions only via kernel traps. * * MSA: * CPU supports Mips SIMD Architecture instructions. */ enum { ANDROID_CPU_MIPS_FEATURE_R6 = (1 << 0), ANDROID_CPU_MIPS_FEATURE_MSA = (1 << 1), }; /* Return the number of CPU cores detected on this device. */ extern int android_getCpuCount(void); /* The following is used to force the CPU count and features * mask in sandboxed processes. Under 4.1 and higher, these processes * cannot access /proc, which is the only way to get information from * the kernel about the current hardware (at least on ARM). * * It _must_ be called only once, and before any android_getCpuXXX * function, any other case will fail. * * This function return 1 on success, and 0 on failure. */ extern int android_setCpu(int cpu_count, uint64_t cpu_features); #ifdef __arm__ /* Retrieve the ARM 32-bit CPUID value from the kernel. * Note that this cannot work on sandboxed processes under 4.1 and * higher, unless you called android_setCpuArm() before. */ extern uint32_t android_getCpuIdArm(void); /* An ARM-specific variant of android_setCpu() that also allows you * to set the ARM CPUID field. */ extern int android_setCpuArm(int cpu_count, uint64_t cpu_features, uint32_t cpu_id); #endif __END_DECLS #endif /* CPU_FEATURES_H */
#!/usr/bin/python # Copyright (C) International Business Machines Corp., 2005 # Author: Woody Marvel <marvel@us.ibm.com> # Li Ge <lge@us.ibm.com> # Positive Test: # Test Description: # 1. Create a domain # 2. Destroy the domain by id import sys import re import time from XmTestLib import * # Create a domain (default XmTestDomain, with our ramdisk) domain = XmTestDomain() # Start it try: domain.start(noConsole=True) except DomainError, e: if verbose: print "Failed to create test domain because:" print e.extra FAIL(str(e)) # destroy domain - positive test status, output = traceCommand("xm destroy %s" % domain.getId()) if status != 0: FAIL("xm destroy returned invalid %i != 0" % status)
#!/bin/sh /usr/bin/lynx -source http://example.com/cron.php > /dev/null 2>&1
-- UPDATE `creature_template` SET `flags_extra`=`flags_extra`|2 WHERE `entry` IN (22678,31989,22741,32012);
/* * Copyright (C) 2000-2006 Erik Andersen <andersen@uclibc.org> * * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball. */ #include <errno.h> /* This routine is jumped to by all the syscall handlers, to stash an error number into errno. */ int attribute_hidden __syscall_error (void) { register int err_no __asm__("$0"); __set_errno (err_no); return -1; }
// 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. #ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_WEB_UI_H_ #define CHROME_BROWSER_EXTENSIONS_EXTENSION_WEB_UI_H_ #include <string> #include "base/memory/scoped_ptr.h" #include "chrome/common/extensions/manifest_url_handler.h" #include "components/favicon_base/favicon_callback.h" #include "content/public/browser/web_ui_controller.h" class Profile; namespace content { class BrowserContext; class WebContents; } namespace extensions { class BookmarkManagerPrivateDragEventRouter; } namespace user_prefs { class PrefRegistrySyncable; } // This class implements WebUI for extensions and allows extensions to put UI in // the main tab contents area. For example, each extension can specify an // "options_page", and that page is displayed in the tab contents area and is // hosted by this class. class ExtensionWebUI : public content::WebUIController { public: static const char kExtensionURLOverrides[]; ExtensionWebUI(content::WebUI* web_ui, const GURL& url); virtual ~ExtensionWebUI(); virtual extensions::BookmarkManagerPrivateDragEventRouter* bookmark_manager_private_drag_event_router(); // BrowserURLHandler static bool HandleChromeURLOverride(GURL* url, content::BrowserContext* browser_context); static bool HandleChromeURLOverrideReverse( GURL* url, content::BrowserContext* browser_context); // Register and unregister a dictionary of one or more overrides. // Page names are the keys, and chrome-extension: URLs are the values. // (e.g. { "newtab": "chrome-extension://<id>/my_new_tab.html" } static void RegisterChromeURLOverrides(Profile* profile, const extensions::URLOverrides::URLOverrideMap& overrides); static void UnregisterChromeURLOverrides(Profile* profile, const extensions::URLOverrides::URLOverrideMap& overrides); static void UnregisterChromeURLOverride(const std::string& page, Profile* profile, const base::Value* override); // Called from BrowserPrefs static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); // Get the favicon for the extension by getting an icon from the manifest. // Note. |callback| is always run asynchronously. static void GetFaviconForURL( Profile* profile, const GURL& page_url, const favicon_base::FaviconResultsCallback& callback); private: // Unregister the specified override, and if it's the currently active one, // ensure that something takes its place. static void UnregisterAndReplaceOverride(const std::string& page, Profile* profile, base::ListValue* list, const base::Value* override); // TODO(aa): This seems out of place. Why is it not with the event routers for // the other extension APIs? scoped_ptr<extensions::BookmarkManagerPrivateDragEventRouter> bookmark_manager_private_drag_event_router_; // The URL this WebUI was created for. GURL url_; }; #endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_WEB_UI_H_
/************************************************************************ filename: CEGUIRenderCache.h created: Fri Jun 17 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #ifndef _CEGUIRenderCache_h_ #define _CEGUIRenderCache_h_ #include "CEGUIVector.h" #include "CEGUIRect.h" #include "CEGUIImage.h" #include "CEGUIFont.h" #include <vector> #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4251) #endif // Start of CEGUI namespace section namespace CEGUI { /*! \brief Class that acts as a cache for images that need to be rendered. This is in many ways an optimisation cache, it allows a full image redraw to occur while limiting the amount of information that needs to be re-calculated. \par Basically, unless the actual images (or their size) change, or the colours (or alpha) change then imagery cached in here will suffice for a full redraw. The reasoning behind this is that when some window underneath window 'X' changes, a full image redraw is required by the renderer, however, since window 'X' is unchanged, performing a total recalculation of all imagery is very wasteful, and so we use this cache to limit such waste. \par As another example, when a window is simply moved, there is no need to perform a total imagery recalculation; we can still use the imagery cached here since it is position independant. */ class CEGUIEXPORT RenderCache { public: /*! \brief Constructor */ RenderCache(); /*! \brief Destructor */ ~RenderCache(); /*! \brief Return whether the cache contains anything to draw. \return - true if the cache contains information about images to be drawn. - false if the cache is empty. */ bool hasCachedImagery() const; /*! \brief Send the contents of the cache to the Renderer. \param basePos Point that describes a screen offset that cached imagery will be rendered relative to. \param baseZ Z value that cached imagery will use as a base figure when calculating final z values. \param clipper Rect object describing a rect to which imagery will be clipped. \return Nothing */ void render(const Point& basePos, float baseZ, const Rect& clipper) const; /*! \brief Erase any stored image information. */ void clearCachedImagery(); /*! \brief Add an image to the cache. \param image Image object to be cached. \param destArea Destination area over which the Image object will be rendered. This area should be position independant; so position (0,0) will be to top-left corner of whatever it is you're rendering (like a Window for example). \param zOffset Zero based z offset for this image. Allows imagery to be layered. \param cols ColourRect object describing the colours to be applied when rendering this image. \return Nothing */ void cacheImage(const Image& image, const Rect& destArea, float zOffset, const ColourRect& cols, const Rect* clipper = 0, bool clipToDisplay = false); /*! \brief Add a text to the cache. \param text String object to be cached. \param font Font to be used when rendering. \param format TextFormatting value specifying the formatting to use when rendering. \param destArea Destination area over which the Image object will be rendered. This area should be position independant; so position (0,0) will be to top-left corner of whatever it is you're rendering (like a Window for example). \param zOffset Zero based z offset for this image. Allows imagery to be layered. \param cols ColourRect object describing the colours to be applied when rendering this image. \return Nothing */ void cacheText(const String& text, const Font* font, TextFormatting format, const Rect& destArea, float zOffset, const ColourRect& cols, const Rect* clipper = 0, bool clipToDisplay = false); private: /*! \brief internal struct that holds info about a single image to be drawn. */ struct ImageInfo { const Image* source_image; Rect target_area; float z_offset; ColourRect colours; Rect customClipper; bool usingCustomClipper; bool clipToDisplay; }; /*! \brief internal struct that holds info about text to be drawn. */ struct TextInfo { String text; const Font* source_font; TextFormatting formatting; Rect target_area; float z_offset; ColourRect colours; Rect customClipper; bool usingCustomClipper; bool clipToDisplay; }; typedef std::vector<ImageInfo> ImageryList; typedef std::vector<TextInfo> TextList; ImageryList d_cachedImages; //!< Collection of ImageInfo structs. TextList d_cachedTexts; //!< Collection of TextInfo structs. }; } // End of CEGUI namespace section #if defined(_MSC_VER) # pragma warning(pop) #endif #endif // end of guard _CEGUIRenderCache_h_
// 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. #ifndef IPC_IPC_CHANNEL_READER_H_ #define IPC_IPC_CHANNEL_READER_H_ #include "base/basictypes.h" #include "ipc/ipc_channel.h" namespace IPC { namespace internal { // This class provides common pipe reading functionality for the // platform-specific IPC channel implementations. // // It does the common input buffer management and message dispatch, while the // platform-specific parts provide the pipe management through a virtual // interface implemented on a per-platform basis. // // Note that there is no "writer" corresponding to this because the code for // writing to the channel is much simpler and has very little common // functionality that would benefit from being factored out. If we add // something like that in the future, it would be more appropriate to add it // here (and rename appropriately) rather than writing a different class. class ChannelReader { public: explicit ChannelReader(Listener* listener); virtual ~ChannelReader(); void set_listener(Listener* listener) { listener_ = listener; } // Call to process messages received from the IPC connection and dispatch // them. Returns false on channel error. True indicates that everything // succeeded, although there may not have been any messages processed. bool ProcessIncomingMessages(); // Handles asynchronously read data. // // Optionally call this after returning READ_PENDING from ReadData to // indicate that buffer was filled with the given number of bytes of // data. See ReadData for more. bool AsyncReadComplete(int bytes_read); // Returns true if the given message is the "hello" message sent on channel // set-up. bool IsHelloMessage(const Message& m) const; protected: enum ReadState { READ_SUCCEEDED, READ_FAILED, READ_PENDING }; Listener* listener() const { return listener_; } // Populates the given buffer with data from the pipe. // // Returns the state of the read. On READ_SUCCESS, the number of bytes // read will be placed into |*bytes_read| (which can be less than the // buffer size). On READ_FAILED, the channel will be closed. // // If the return value is READ_PENDING, it means that there was no data // ready for reading. The implementation is then responsible for either // calling AsyncReadComplete with the number of bytes read into the // buffer, or ProcessIncomingMessages to try the read again (depending // on whether the platform's async I/O is "try again" or "write // asynchronously into your buffer"). virtual ReadState ReadData(char* buffer, int buffer_len, int* bytes_read) = 0; // Loads the required file desciptors into the given message. Returns true // on success. False means a fatal channel error. // // This will read from the input_fds_ and read more handles from the FD // pipe if necessary. virtual bool WillDispatchInputMessage(Message* msg) = 0; // Performs post-dispatch checks. Called when all input buffers are empty, // though there could be more data ready to be read from the OS. virtual bool DidEmptyInputBuffers() = 0; // Handles the first message sent over the pipe which contains setup info. virtual void HandleHelloMessage(const Message& msg) = 0; private: // Takes the given data received from the IPC channel and dispatches any // fully completed messages. // // Returns true on success. False means channel error. bool DispatchInputData(const char* input_data, int input_data_len); Listener* listener_; // We read from the pipe into this buffer. Managed by DispatchInputData, do // not access directly outside that function. char input_buf_[Channel::kReadBufferSize]; // Large messages that span multiple pipe buffers, get built-up using // this buffer. std::string input_overflow_buf_; DISALLOW_COPY_AND_ASSIGN(ChannelReader); }; } // namespace internal } // namespace IPC #endif // IPC_IPC_CHANNEL_READER_H_
import React from 'react/addons'; import ContainerListItem from './ContainerListItem.react'; var ContainerList = React.createClass({ componentWillMount: function () { this.start = Date.now(); }, render: function () { var containers = this.props.containers.map(container => { return ( <ContainerListItem key={container.Id} container={container} start={this.start} /> ); }); return ( <ul> {containers} </ul> ); } }); module.exports = ContainerList;
/* * Copyright 2000-2009 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.ui.plaf.beg; import com.intellij.util.ui.UIUtil; import javax.swing.*; import javax.swing.border.AbstractBorder; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.UIResource; import javax.swing.plaf.basic.BasicBorders; import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.text.JTextComponent; import java.awt.*; /** * @author Eugene Belyaev */ public class BegBorders { private static Border ourButtonBorder; private static Border ourTextFieldBorder; private static Border ourScrollPaneBorder; public static Border getButtonBorder() { if (ourButtonBorder == null) { ourButtonBorder = new BorderUIResource.CompoundBorderUIResource( new ButtonBorder(), new BasicBorders.MarginBorder()); } return ourButtonBorder; } public static Border getTextFieldBorder() { if (ourTextFieldBorder == null) { ourTextFieldBorder = new BorderUIResource.CompoundBorderUIResource( new TextFieldBorder(), //new FlatLineBorder(), BorderFactory.createEmptyBorder(2, 2, 2, 2)); } return ourTextFieldBorder; } public static Border getScrollPaneBorder() { if (ourScrollPaneBorder == null) { ourScrollPaneBorder = new BorderUIResource.LineBorderUIResource(MetalLookAndFeel.getControlDarkShadow()); //ourScrollPaneBorder = new FlatLineBorder(); } return ourScrollPaneBorder; } public static class FlatLineBorder extends LineBorder implements UIResource { public FlatLineBorder() { super(new Color(127, 157, 185), 1, true); } } public static class ButtonBorder extends AbstractBorder implements UIResource { protected static Insets borderInsets = new Insets(3, 3, 3, 3); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { AbstractButton button = (AbstractButton) c; ButtonModel model = button.getModel(); if (model.isEnabled()) { boolean isPressed = model.isPressed() && model.isArmed(); boolean isDefault = (button instanceof JButton && ((JButton) button).isDefaultButton()); if (isPressed && isDefault) { drawDefaultButtonPressedBorder(g, x, y, w, h); } else if (isPressed) { drawPressed3DBorder(g, x, y, w, h); } else if (isDefault) { drawDefaultButtonBorder(g, x, y, w, h, false); } else { drawButtonBorder(g, x, y, w, h, false); } } else { // disabled state drawDisabledBorder(g, x, y, w - 1, h - 1); } } public Insets getBorderInsets(Component c) { return (Insets)borderInsets.clone(); } public Insets getBorderInsets(Component c, Insets newInsets) { newInsets.top = borderInsets.top; newInsets.left = borderInsets.left; newInsets.bottom = borderInsets.bottom; newInsets.right = borderInsets.right; return newInsets; } } public static class ScrollPaneBorder extends AbstractBorder implements UIResource { private static final Insets insets = new Insets(1, 1, 2, 2); public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { JScrollPane scroll = (JScrollPane) c; JComponent colHeader = scroll.getColumnHeader(); int colHeaderHeight = 0; if (colHeader != null) colHeaderHeight = colHeader.getHeight(); JComponent rowHeader = scroll.getRowHeader(); int rowHeaderWidth = 0; if (rowHeader != null) rowHeaderWidth = rowHeader.getWidth(); /* g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawLine(w - 1, 1, w - 1, h - 1); g.drawLine(1, h - 1, w - 1, h - 1); g.setColor(MetalLookAndFeel.getControl()); if (colHeaderHeight > 0) { g.drawLine(w - 2, 2 + colHeaderHeight, w - 2, 2 + colHeaderHeight); } if (rowHeaderWidth > 0) { g.drawLine(1 + rowHeaderWidth, h - 2, 1 + rowHeaderWidth, h - 2); } g.translate(-x, -y); */ drawLineBorder(g, x, y, w, h); } public Insets getBorderInsets(Component c) { return (Insets)insets.clone(); } } public static class TextFieldBorder /*extends MetalBorders.Flush3DBorder*/ extends LineBorder implements UIResource { public TextFieldBorder() { super(null, 1); } public boolean isBorderOpaque() { return false; } public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { if (!(c instanceof JTextComponent)) { // special case for non-text components (bug ID 4144840) if (c.isEnabled()) { drawFlush3DBorder(g, x, y, w, h); } else { drawDisabledBorder(g, x, y, w, h); } return; } if (c.isEnabled() && ((JTextComponent) c).isEditable()) { drawLineBorder(g, x, y, w, h); /* g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawLine(1, 0, w - 2, 0); g.drawLine(0, 1, 0, h - 2); g.drawLine(w - 1, 1, w - 1, h - 2); g.drawLine(1, h - 1, w - 2, h - 1); g.translate(-x, -y); */ } else { drawDisabledBorder(g, x, y, w, h); } } } static void drawLineBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 1, h - 1); g.translate(-x, -y); } static void drawFlush3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawRect(1, 1, w - 2, h - 2); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 2, h - 2); g.translate(-x, -y); } static void drawDisabledBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(MetalLookAndFeel.getControlShadow()); g.drawRect(0, 0, w - 1, h - 1); g.translate(-x, -y); } static void drawDefaultButtonPressedBorder(Graphics g, int x, int y, int w, int h) { drawPressed3DBorder(g, x + 1, y + 1, w - 1, h - 1); g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 3, h - 3); UIUtil.drawLine(g, w - 2, 0, w - 2, 0); UIUtil.drawLine(g, 0, h - 2, 0, h - 2); g.translate(-x, -y); } static void drawPressed3DBorder(Graphics g, int x, int y, int w, int h) { g.translate(x, y); drawFlush3DBorder(g, 0, 0, w, h); g.setColor(MetalLookAndFeel.getControlShadow()); UIUtil.drawLine(g, 1, 1, 1, h - 1); UIUtil.drawLine(g, 1, 1, w - 1, 1); g.translate(-x, -y); } static void drawDefaultButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { drawButtonBorder(g, x + 1, y + 1, w - 1, h - 1, active); g.translate(x, y); g.setColor(MetalLookAndFeel.getControlDarkShadow()); g.drawRect(0, 0, w - 3, h - 3); UIUtil.drawLine(g, w - 2, 0, w - 2, 0); UIUtil.drawLine(g, 0, h - 2, 0, h - 2); g.translate(-x, -y); } static void drawButtonBorder(Graphics g, int x, int y, int w, int h, boolean active) { if (active) { drawActiveButtonBorder(g, x, y, w, h); } else { drawFlush3DBorder(g, x, y, w, h); /* drawLineBorder(g, x, y, w - 1, h - 1); g.setColor(MetalLookAndFeel.getControlHighlight()); g.drawLine(x + 1, y + h - 1, x + w - 1, y + h - 1); g.drawLine(x + w - 1, y + 1, x + w - 1, y + h - 1); */ } } static void drawActiveButtonBorder(Graphics g, int x, int y, int w, int h) { drawFlush3DBorder(g, x, y, w, h); g.setColor(MetalLookAndFeel.getPrimaryControl()); UIUtil.drawLine(g, x + 1, y + 1, x + 1, h - 3); UIUtil.drawLine(g, x + 1, y + 1, w - 3, x + 1); g.setColor(MetalLookAndFeel.getPrimaryControlDarkShadow()); UIUtil.drawLine(g, x + 2, h - 2, w - 2, h - 2); UIUtil.drawLine(g, w - 2, y + 2, w - 2, h - 2); } }
/* * Copyright (c) 1997-2000 LAN Media Corporation (LMC) * All rights reserved. www.lanmedia.com * * This code is written by: * Andrew Stanley-Jones (asj@cban.com) * Rob Braun (bbraun@vix.com), * Michael Graff (explorer@vix.com) and * Matt Thomas (matt@3am-software.com). * * With Help By: * David Boggs * Ron Crane * Allan Cox * * This software may be used and distributed according to the terms * of the GNU General Public License version 2, incorporated herein by reference. * * Driver for the LanMedia LMC5200, LMC5245, LMC1000, LMC1200 cards. */ #include <linux/kernel.h> #include <linux/string.h> #include <linux/timer.h> #include <linux/ptrace.h> #include <linux/errno.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/in.h> #include <linux/if_arp.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/inet.h> #include <linux/workqueue.h> #include <linux/proc_fs.h> #include <linux/bitops.h> #include <net/syncppp.h> #include <asm/processor.h> /* Processor type for cache alignment. */ #include <asm/io.h> #include <asm/dma.h> #include <linux/smp.h> #include "lmc.h" #include "lmc_var.h" #include "lmc_debug.h" #include "lmc_ioctl.h" #include "lmc_proto.h" /* * The compile-time variable SPPPSTUP causes the module to be * compiled without referencing any of the sync ppp routines. */ #ifdef SPPPSTUB #define SPPP_detach(d) (void)0 #define SPPP_open(d) 0 #define SPPP_reopen(d) (void)0 #define SPPP_close(d) (void)0 #define SPPP_attach(d) (void)0 #define SPPP_do_ioctl(d,i,c) -EOPNOTSUPP #else #define SPPP_attach(x) sppp_attach((x)->pd) #define SPPP_detach(x) sppp_detach((x)->pd->dev) #define SPPP_open(x) sppp_open((x)->pd->dev) #define SPPP_reopen(x) sppp_reopen((x)->pd->dev) #define SPPP_close(x) sppp_close((x)->pd->dev) #define SPPP_do_ioctl(x, y, z) sppp_do_ioctl((x)->pd->dev, (y), (z)) #endif // init void lmc_proto_init(lmc_softc_t *sc) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_init in"); switch(sc->if_type){ case LMC_PPP: sc->pd = kmalloc(sizeof(struct ppp_device), GFP_KERNEL); if (!sc->pd) { printk("lmc_proto_init(): kmalloc failure!\n"); return; } sc->pd->dev = sc->lmc_device; sc->if_ptr = sc->pd; break; case LMC_RAW: break; default: break; } lmc_trace(sc->lmc_device, "lmc_proto_init out"); } // attach void lmc_proto_attach(lmc_softc_t *sc) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_attach in"); switch(sc->if_type){ case LMC_PPP: { struct net_device *dev = sc->lmc_device; SPPP_attach(sc); dev->do_ioctl = lmc_ioctl; } break; case LMC_NET: { struct net_device *dev = sc->lmc_device; /* * They set a few basics because they don't use sync_ppp */ dev->flags |= IFF_POINTOPOINT; dev->hard_header = NULL; dev->hard_header_len = 0; dev->addr_len = 0; } case LMC_RAW: /* Setup the task queue, maybe we should notify someone? */ { } default: break; } lmc_trace(sc->lmc_device, "lmc_proto_attach out"); } // detach void lmc_proto_detach(lmc_softc_t *sc) /*FOLD00*/ { switch(sc->if_type){ case LMC_PPP: SPPP_detach(sc); break; case LMC_RAW: /* Tell someone we're detaching? */ break; default: break; } } // reopen void lmc_proto_reopen(lmc_softc_t *sc) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_reopen in"); switch(sc->if_type){ case LMC_PPP: SPPP_reopen(sc); break; case LMC_RAW: /* Reset the interface after being down, prerape to receive packets again */ break; default: break; } lmc_trace(sc->lmc_device, "lmc_proto_reopen out"); } // ioctl int lmc_proto_ioctl(lmc_softc_t *sc, struct ifreq *ifr, int cmd) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_ioctl out"); switch(sc->if_type){ case LMC_PPP: return SPPP_do_ioctl (sc, ifr, cmd); break; default: return -EOPNOTSUPP; break; } lmc_trace(sc->lmc_device, "lmc_proto_ioctl out"); } // open void lmc_proto_open(lmc_softc_t *sc) /*FOLD00*/ { int ret; lmc_trace(sc->lmc_device, "lmc_proto_open in"); switch(sc->if_type){ case LMC_PPP: ret = SPPP_open(sc); if(ret < 0) printk("%s: syncPPP open failed: %d\n", sc->name, ret); break; case LMC_RAW: /* We're about to start getting packets! */ break; default: break; } lmc_trace(sc->lmc_device, "lmc_proto_open out"); } // close void lmc_proto_close(lmc_softc_t *sc) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_close in"); switch(sc->if_type){ case LMC_PPP: SPPP_close(sc); break; case LMC_RAW: /* Interface going down */ break; default: break; } lmc_trace(sc->lmc_device, "lmc_proto_close out"); } unsigned short lmc_proto_type(lmc_softc_t *sc, struct sk_buff *skb) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_type in"); switch(sc->if_type){ case LMC_PPP: return htons(ETH_P_WAN_PPP); break; case LMC_NET: return htons(ETH_P_802_2); break; case LMC_RAW: /* Packet type for skbuff kind of useless */ return htons(ETH_P_802_2); break; default: printk(KERN_WARNING "%s: No protocol set for this interface, assuming 802.2 (which is wrong!!)\n", sc->name); return htons(ETH_P_802_2); break; } lmc_trace(sc->lmc_device, "lmc_proto_tye out"); } void lmc_proto_netif(lmc_softc_t *sc, struct sk_buff *skb) /*FOLD00*/ { lmc_trace(sc->lmc_device, "lmc_proto_netif in"); switch(sc->if_type){ case LMC_PPP: case LMC_NET: default: skb->dev->last_rx = jiffies; netif_rx(skb); break; case LMC_RAW: break; } lmc_trace(sc->lmc_device, "lmc_proto_netif out"); }
// Copyright (C) 2004, 2009 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 <string> #include <testsuite_performance.h> void test_pair(const std::string& s, const std::string& f, int n) { std::string::size_type sz = 0; for (int i = 0; i < n; ++i) sz = s.find(f); } int main() { using namespace std; using namespace __gnu_test; time_counter time; resource_counter resource; const unsigned int iterations = 2000000; string s, f; s = "aabbaabbaaxd adbffdadgaxaabbbddhatyaaaabbbaabbaabbcsy"; f = "aabbaabbc"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "1", time, resource); clear_counters(time, resource); f = "aabbb"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "2", time, resource); clear_counters(time, resource); f = "xd"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "3", time, resource); clear_counters(time, resource); s = "dhruv is a very very good boy ;-)"; f = "very"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "4", time, resource); clear_counters(time, resource); f = "bad"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "5", time, resource); clear_counters(time, resource); f = "extra irritating"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "6", time, resource); clear_counters(time, resource); s = "this is a very this is a very this is a verty this is a very " "this is a very long sentence"; f = "this is a very long sentence"; start_counters(time, resource); test_pair(s, f, iterations); stop_counters(time, resource); report_performance(__FILE__, "7", time, resource); clear_counters(time, resource); return 0; }
/*! jQuery UI - v1.8.24 - 2012-09-28 * https://github.com/jquery/jquery-ui * Includes: jquery.ui.datepicker-ka.js * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ jQuery(function(a){a.datepicker.regional.ka={closeText:"დახურვა",prevText:"&#x3c; წინა",nextText:"შემდეგი &#x3e;",currentText:"დღეს",monthNames:["იანვარი","თებერვალი","მარტი","აპრილი","მაისი","ივნისი","ივლისი","აგვისტო","სექტემბერი","ოქტომბერი","ნოემბერი","დეკემბერი"],monthNamesShort:["იან","თებ","მარ","აპრ","მაი","ივნ","ივლ","აგვ","სექ","ოქტ","ნოე","დეკ"],dayNames:["კვირა","ორშაბათი","სამშაბათი","ოთხშაბათი","ხუთშაბათი","პარასკევი","შაბათი"],dayNamesShort:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],dayNamesMin:["კვ","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"],weekHeader:"კვირა",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},a.datepicker.setDefaults(a.datepicker.regional.ka)});
// 2001-06-14 Benjamin Kosnik <bkoz@redhat.com> // Copyright (C) 2001, 2002, 2004, 2005, 2009 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/>. // 20.4.1.1 allocator members #include <memory> #include <stdexcept> #include <cstdlib> #include <testsuite_hooks.h> struct gnu { }; bool check_new = false; bool check_delete = false; void* operator new(std::size_t n) throw(std::bad_alloc) { check_new = true; return std::malloc(n); } void operator delete(void *v) throw() { check_delete = true; return std::free(v); } void test01() { bool test __attribute__((unused)) = true; std::allocator<gnu> obj; // NB: These should work for various size allocation and // deallocations. Currently, they only work as expected for sizes > // _MAX_BYTES as defined in stl_alloc.h, which happes to be 128. gnu* pobj = obj.allocate(256); VERIFY( check_new ); obj.deallocate(pobj, 256); VERIFY( check_delete ); } int main() { test01(); return 0; }
import os import re import subprocess import sys import urlparse from wptrunner.update.sync import LoadManifest from wptrunner.update.tree import get_unique_name from wptrunner.update.base import Step, StepRunner, exit_clean, exit_unclean from .tree import Commit, GitTree, Patch import github from .github import GitHub def rewrite_patch(patch, strip_dir): """Take a Patch and convert to a different repository by stripping a prefix from the file paths. Also rewrite the message to remove the bug number and reviewer, but add a bugzilla link in the summary. :param patch: the Patch to convert :param strip_dir: the path prefix to remove """ if not strip_dir.startswith("/"): strip_dir = "/%s"% strip_dir new_diff = [] line_starts = ["diff ", "+++ ", "--- "] for line in patch.diff.split("\n"): for start in line_starts: if line.startswith(start): new_diff.append(line.replace(strip_dir, "").encode("utf8")) break else: new_diff.append(line) new_diff = "\n".join(new_diff) assert new_diff != patch return Patch(patch.author, patch.email, rewrite_message(patch), new_diff) def rewrite_message(patch): rest = patch.message.body if patch.message.bug is not None: return "\n".join([patch.message.summary, patch.message.body, "", "Upstreamed from https://bugzilla.mozilla.org/show_bug.cgi?id=%s" % patch.message.bug]) return "\n".join([patch.message.full_summary, rest]) class SyncToUpstream(Step): """Sync local changes to upstream""" def create(self, state): if not state.kwargs["upstream"]: return if not isinstance(state.local_tree, GitTree): self.logger.error("Cannot sync with upstream from a non-Git checkout.") return exit_clean try: import requests except ImportError: self.logger.error("Upstream sync requires the requests module to be installed") return exit_clean if not state.sync_tree: os.makedirs(state.sync["path"]) state.sync_tree = GitTree(root=state.sync["path"]) kwargs = state.kwargs with state.push(["local_tree", "sync_tree", "tests_path", "metadata_path", "sync"]): state.token = kwargs["token"] runner = SyncToUpstreamRunner(self.logger, state) runner.run() class CheckoutBranch(Step): """Create a branch in the sync tree pointing at the last upstream sync commit and check it out""" provides = ["branch"] def create(self, state): self.logger.info("Updating sync tree from %s" % state.sync["remote_url"]) state.branch = state.sync_tree.unique_branch_name( "outbound_update_%s" % state.test_manifest.rev) state.sync_tree.update(state.sync["remote_url"], state.sync["branch"], state.branch) state.sync_tree.checkout(state.test_manifest.rev, state.branch, force=True) class GetLastSyncCommit(Step): """Find the gecko commit at which we last performed a sync with upstream.""" provides = ["last_sync_path", "last_sync_commit"] def create(self, state): self.logger.info("Looking for last sync commit") state.last_sync_path = os.path.join(state.metadata_path, "mozilla-sync") with open(state.last_sync_path) as f: last_sync_sha1 = f.read().strip() state.last_sync_commit = Commit(state.local_tree, last_sync_sha1) if not state.local_tree.contains_commit(state.last_sync_commit): self.logger.error("Could not find last sync commit %s" % last_sync_sha1) return exit_clean self.logger.info("Last sync to web-platform-tests happened in %s" % state.last_sync_commit.sha1) class GetBaseCommit(Step): """Find the latest upstream commit on the branch that we are syncing with""" provides = ["base_commit"] def create(self, state): state.base_commit = state.sync_tree.get_remote_sha1(state.sync["remote_url"], state.sync["branch"]) self.logger.debug("New base commit is %s" % state.base_commit.sha1) class LoadCommits(Step): """Get a list of commits in the gecko tree that need to be upstreamed""" provides = ["source_commits"] def create(self, state): state.source_commits = state.local_tree.log(state.last_sync_commit, state.tests_path) update_regexp = re.compile("Bug \d+ - Update web-platform-tests to revision [0-9a-f]{40}") for i, commit in enumerate(state.source_commits[:]): if update_regexp.match(commit.message.text): # This is a previous update commit so ignore it state.source_commits.remove(commit) continue if commit.message.backouts: #TODO: Add support for collapsing backouts raise NotImplementedError("Need to get the Git->Hg commits for backouts and remove the backed out patch") if not commit.message.bug: self.logger.error("Commit %i (%s) doesn't have an associated bug number." % (i + 1, commit.sha1)) return exit_unclean self.logger.debug("Source commits: %s" % state.source_commits) class SelectCommits(Step): """Provide a UI to select which commits to upstream""" def create(self, state): if not state.source_commits: return while True: commits = state.source_commits[:] for i, commit in enumerate(commits): print "%i:\t%s" % (i, commit.message.summary) remove = raw_input("Provide a space-separated list of any commits numbers to remove from the list to upstream:\n").strip() remove_idx = set() invalid = False for item in remove.split(" "): try: item = int(item) except: invalid = True break if item < 0 or item >= len(commits): invalid = True break remove_idx.add(item) if invalid: continue keep_commits = [(i,cmt) for i,cmt in enumerate(commits) if i not in remove_idx] #TODO: consider printed removed commits print "Selected the following commits to keep:" for i, commit in keep_commits: print "%i:\t%s" % (i, commit.message.summary) confirm = raw_input("Keep the above commits? y/n\n").strip().lower() if confirm == "y": state.source_commits = [item[1] for item in keep_commits] break class MovePatches(Step): """Convert gecko commits into patches against upstream and commit these to the sync tree.""" provides = ["commits_loaded"] def create(self, state): state.commits_loaded = 0 strip_path = os.path.relpath(state.tests_path, state.local_tree.root) self.logger.debug("Stripping patch %s" % strip_path) for commit in state.source_commits[state.commits_loaded:]: i = state.commits_loaded + 1 self.logger.info("Moving commit %i: %s" % (i, commit.message.full_summary)) patch = commit.export_patch(state.tests_path) stripped_patch = rewrite_patch(patch, strip_path) try: state.sync_tree.import_patch(stripped_patch) except: print patch.diff raise state.commits_loaded = i class RebaseCommits(Step): """Rebase commits from the current branch on top of the upstream destination branch. This step is particularly likely to fail if the rebase generates merge conflicts. In that case the conflicts can be fixed up locally and the sync process restarted with --continue. """ provides = ["rebased_commits"] def create(self, state): self.logger.info("Rebasing local commits") continue_rebase = False # Check if there's a rebase in progress if (os.path.exists(os.path.join(state.sync_tree.root, ".git", "rebase-merge")) or os.path.exists(os.path.join(state.sync_tree.root, ".git", "rebase-apply"))): continue_rebase = True try: state.sync_tree.rebase(state.base_commit, continue_rebase=continue_rebase) except subprocess.CalledProcessError: self.logger.info("Rebase failed, fix merge and run %s again with --continue" % sys.argv[0]) raise state.rebased_commits = state.sync_tree.log(state.base_commit) self.logger.info("Rebase successful") class CheckRebase(Step): """Check if there are any commits remaining after rebase""" def create(self, state): if not state.rebased_commits: self.logger.info("Nothing to upstream, exiting") return exit_clean class MergeUpstream(Step): """Run steps to push local commits as seperate PRs and merge upstream.""" provides = ["merge_index", "gh_repo"] def create(self, state): gh = GitHub(state.token) if "merge_index" not in state: state.merge_index = 0 org, name = urlparse.urlsplit(state.sync["remote_url"]).path[1:].split("/") if name.endswith(".git"): name = name[:-4] state.gh_repo = gh.repo(org, name) for commit in state.rebased_commits[state.merge_index:]: with state.push(["gh_repo", "sync_tree"]): state.commit = commit pr_merger = PRMergeRunner(self.logger, state) rv = pr_merger.run() if rv is not None: return rv state.merge_index += 1 class UpdateLastSyncCommit(Step): """Update the gecko commit at which we last performed a sync with upstream.""" provides = [] def create(self, state): self.logger.info("Updating last sync commit") with open(state.last_sync_path, "w") as f: f.write(state.local_tree.rev) # This gets added to the patch later on class MergeLocalBranch(Step): """Create a local branch pointing at the commit to upstream""" provides = ["local_branch"] def create(self, state): branch_prefix = "sync_%s" % state.commit.sha1 local_branch = state.sync_tree.unique_branch_name(branch_prefix) state.sync_tree.create_branch(local_branch, state.commit) state.local_branch = local_branch class MergeRemoteBranch(Step): """Get an unused remote branch name to use for the PR""" provides = ["remote_branch"] def create(self, state): remote_branch = "sync_%s" % state.commit.sha1 branches = [ref[len("refs/heads/"):] for sha1, ref in state.sync_tree.list_remote(state.gh_repo.url) if ref.startswith("refs/heads")] state.remote_branch = get_unique_name(branches, remote_branch) class PushUpstream(Step): """Push local branch to remote""" def create(self, state): self.logger.info("Pushing commit upstream") state.sync_tree.push(state.gh_repo.url, state.local_branch, state.remote_branch) class CreatePR(Step): """Create a PR for the remote branch""" provides = ["pr"] def create(self, state): self.logger.info("Creating a PR") commit = state.commit state.pr = state.gh_repo.create_pr(commit.message.full_summary, state.remote_branch, "master", commit.message.body if commit.message.body else "") class PRAddComment(Step): """Add an issue comment indicating that the code has been reviewed already""" def create(self, state): state.pr.issue.add_comment("Code reviewed upstream.") class MergePR(Step): """Merge the PR""" def create(self, state): self.logger.info("Merging PR") state.pr.merge() class PRDeleteBranch(Step): """Delete the remote branch""" def create(self, state): self.logger.info("Deleting remote branch") state.sync_tree.push(state.gh_repo.url, "", state.remote_branch) class SyncToUpstreamRunner(StepRunner): """Runner for syncing local changes to upstream""" steps = [LoadManifest, CheckoutBranch, GetLastSyncCommit, GetBaseCommit, LoadCommits, SelectCommits, MovePatches, RebaseCommits, CheckRebase, MergeUpstream, UpdateLastSyncCommit] class PRMergeRunner(StepRunner): """(Sub)Runner for creating and merging a PR""" steps = [ MergeLocalBranch, MergeRemoteBranch, PushUpstream, CreatePR, PRAddComment, MergePR, PRDeleteBranch, ]
/* * * 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. * */ /* Test of gpr synchronization support. */ #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> #include <grpc/support/thd.h> #include <grpc/support/time.h> #include <stdio.h> #include <stdlib.h> #include "test/core/util/test_config.h" /* ==================Example use of interface=================== A producer-consumer queue of up to N integers, illustrating the use of the calls in this interface. */ #define N 4 typedef struct queue { gpr_cv non_empty; /* Signalled when length becomes non-zero. */ gpr_cv non_full; /* Signalled when length becomes non-N. */ gpr_mu mu; /* Protects all fields below. (That is, except during initialization or destruction, the fields below should be accessed only by a thread that holds mu.) */ int head; /* Index of head of queue 0..N-1. */ int length; /* Number of valid elements in queue 0..N. */ int elem[N]; /* elem[head .. head+length-1] are queue elements. */ } queue; /* Initialize *q. */ void queue_init(queue *q) { gpr_mu_init(&q->mu); gpr_cv_init(&q->non_empty); gpr_cv_init(&q->non_full); q->head = 0; q->length = 0; } /* Free storage associated with *q. */ void queue_destroy(queue *q) { gpr_mu_destroy(&q->mu); gpr_cv_destroy(&q->non_empty); gpr_cv_destroy(&q->non_full); } /* Wait until there is room in *q, then append x to *q. */ void queue_append(queue *q, int x) { gpr_mu_lock(&q->mu); /* To wait for a predicate without a deadline, loop on the negation of the predicate, and use gpr_cv_wait(..., gpr_inf_future(GPR_CLOCK_REALTIME)) inside the loop to release the lock, wait, and reacquire on each iteration. Code that makes the condition true should use gpr_cv_broadcast() on the corresponding condition variable. The predicate must be on state protected by the lock. */ while (q->length == N) { gpr_cv_wait(&q->non_full, &q->mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } if (q->length == 0) { /* Wake threads blocked in queue_remove(). */ /* It's normal to use gpr_cv_broadcast() or gpr_signal() while holding the lock. */ gpr_cv_broadcast(&q->non_empty); } q->elem[(q->head + q->length) % N] = x; q->length++; gpr_mu_unlock(&q->mu); } /* If it can be done without blocking, append x to *q and return non-zero. Otherwise return 0. */ int queue_try_append(queue *q, int x) { int result = 0; if (gpr_mu_trylock(&q->mu)) { if (q->length != N) { if (q->length == 0) { /* Wake threads blocked in queue_remove(). */ gpr_cv_broadcast(&q->non_empty); } q->elem[(q->head + q->length) % N] = x; q->length++; result = 1; } gpr_mu_unlock(&q->mu); } return result; } /* Wait until the *q is non-empty or deadline abs_deadline passes. If the queue is non-empty, remove its head entry, place it in *head, and return non-zero. Otherwise return 0. */ int queue_remove(queue *q, int *head, gpr_timespec abs_deadline) { int result = 0; gpr_mu_lock(&q->mu); /* To wait for a predicate with a deadline, loop on the negation of the predicate or until gpr_cv_wait() returns true. Code that makes the condition true should use gpr_cv_broadcast() on the corresponding condition variable. The predicate must be on state protected by the lock. */ while (q->length == 0 && !gpr_cv_wait(&q->non_empty, &q->mu, abs_deadline)) { } if (q->length != 0) { /* Queue is non-empty. */ result = 1; if (q->length == N) { /* Wake threads blocked in queue_append(). */ gpr_cv_broadcast(&q->non_full); } *head = q->elem[q->head]; q->head = (q->head + 1) % N; q->length--; } /* else deadline exceeded */ gpr_mu_unlock(&q->mu); return result; } /* ------------------------------------------------- */ /* Tests for gpr_mu and gpr_cv, and the queue example. */ struct test { int threads; /* number of threads */ int64_t iterations; /* number of iterations per thread */ int64_t counter; int thread_count; /* used to allocate thread ids */ int done; /* threads not yet completed */ int incr_step; /* how much to increment/decrement refcount each time */ gpr_mu mu; /* protects iterations, counter, thread_count, done */ gpr_cv cv; /* signalling depends on test */ gpr_cv done_cv; /* signalled when done == 0 */ queue q; gpr_stats_counter stats_counter; gpr_refcount refcount; gpr_refcount thread_refcount; gpr_event event; }; /* Return pointer to a new struct test. */ static struct test *test_new(int threads, int64_t iterations, int incr_step) { struct test *m = gpr_malloc(sizeof(*m)); m->threads = threads; m->iterations = iterations; m->counter = 0; m->thread_count = 0; m->done = threads; m->incr_step = incr_step; gpr_mu_init(&m->mu); gpr_cv_init(&m->cv); gpr_cv_init(&m->done_cv); queue_init(&m->q); gpr_stats_init(&m->stats_counter, 0); gpr_ref_init(&m->refcount, 0); gpr_ref_init(&m->thread_refcount, threads); gpr_event_init(&m->event); return m; } /* Return pointer to a new struct test. */ static void test_destroy(struct test *m) { gpr_mu_destroy(&m->mu); gpr_cv_destroy(&m->cv); gpr_cv_destroy(&m->done_cv); queue_destroy(&m->q); gpr_free(m); } /* Create m->threads threads, each running (*body)(m) */ static void test_create_threads(struct test *m, void (*body)(void *arg)) { gpr_thd_id id; int i; for (i = 0; i != m->threads; i++) { GPR_ASSERT(gpr_thd_new(&id, body, m, NULL)); } } /* Wait until all threads report done. */ static void test_wait(struct test *m) { gpr_mu_lock(&m->mu); while (m->done != 0) { gpr_cv_wait(&m->done_cv, &m->mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_unlock(&m->mu); } /* Get an integer thread id in the raneg 0..threads-1 */ static int thread_id(struct test *m) { int id; gpr_mu_lock(&m->mu); id = m->thread_count++; gpr_mu_unlock(&m->mu); return id; } /* Indicate that a thread is done, by decrementing m->done and signalling done_cv if m->done==0. */ static void mark_thread_done(struct test *m) { gpr_mu_lock(&m->mu); GPR_ASSERT(m->done != 0); m->done--; if (m->done == 0) { gpr_cv_signal(&m->done_cv); } gpr_mu_unlock(&m->mu); } /* Test several threads running (*body)(struct test *m) for increasing settings of m->iterations, until about timeout_s to 2*timeout_s seconds have elapsed. If extra!=NULL, run (*extra)(m) in an additional thread. incr_step controls by how much m->refcount should be incremented/decremented (if at all) each time in the tests. */ static void test(const char *name, void (*body)(void *m), void (*extra)(void *m), int timeout_s, int incr_step) { int64_t iterations = 1024; struct test *m; gpr_timespec start = gpr_now(GPR_CLOCK_REALTIME); gpr_timespec time_taken; gpr_timespec deadline = gpr_time_add( start, gpr_time_from_micros((int64_t)timeout_s * 1000000, GPR_TIMESPAN)); fprintf(stderr, "%s:", name); while (gpr_time_cmp(gpr_now(GPR_CLOCK_REALTIME), deadline) < 0) { iterations <<= 1; fprintf(stderr, " %ld", (long)iterations); m = test_new(10, iterations, incr_step); if (extra != NULL) { gpr_thd_id id; GPR_ASSERT(gpr_thd_new(&id, extra, m, NULL)); m->done++; /* one more thread to wait for */ } test_create_threads(m, body); test_wait(m); if (m->counter != m->threads * m->iterations * m->incr_step) { fprintf(stderr, "counter %ld threads %d iterations %ld\n", (long)m->counter, m->threads, (long)m->iterations); GPR_ASSERT(0); } test_destroy(m); } time_taken = gpr_time_sub(gpr_now(GPR_CLOCK_REALTIME), start); fprintf(stderr, " done %lld.%09d s\n", (long long)time_taken.tv_sec, (int)time_taken.tv_nsec); } /* Increment m->counter on each iteration; then mark thread as done. */ static void inc(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations; i++) { gpr_mu_lock(&m->mu); m->counter++; gpr_mu_unlock(&m->mu); } mark_thread_done(m); } /* Increment m->counter under lock acquired with trylock, m->iterations times; then mark thread as done. */ static void inctry(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations;) { if (gpr_mu_trylock(&m->mu)) { m->counter++; gpr_mu_unlock(&m->mu); i++; } } mark_thread_done(m); } /* Increment counter only when (m->counter%m->threads)==m->thread_id; then mark thread as done. */ static void inc_by_turns(void *v /*=m*/) { struct test *m = v; int64_t i; int id = thread_id(m); for (i = 0; i != m->iterations; i++) { gpr_mu_lock(&m->mu); while ((m->counter % m->threads) != id) { gpr_cv_wait(&m->cv, &m->mu, gpr_inf_future(GPR_CLOCK_REALTIME)); } m->counter++; gpr_cv_broadcast(&m->cv); gpr_mu_unlock(&m->mu); } mark_thread_done(m); } /* Wait a millisecond and increment counter on each iteration; then mark thread as done. */ static void inc_with_1ms_delay(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations; i++) { gpr_timespec deadline; gpr_mu_lock(&m->mu); deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_micros(1000, GPR_TIMESPAN)); while (!gpr_cv_wait(&m->cv, &m->mu, deadline)) { } m->counter++; gpr_mu_unlock(&m->mu); } mark_thread_done(m); } /* Wait a millisecond and increment counter on each iteration, using an event for timing; then mark thread as done. */ static void inc_with_1ms_delay_event(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations; i++) { gpr_timespec deadline; deadline = gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_micros(1000, GPR_TIMESPAN)); GPR_ASSERT(gpr_event_wait(&m->event, deadline) == NULL); gpr_mu_lock(&m->mu); m->counter++; gpr_mu_unlock(&m->mu); } mark_thread_done(m); } /* Produce m->iterations elements on queue m->q, then mark thread as done. Even threads use queue_append(), and odd threads use queue_try_append() until it succeeds. */ static void many_producers(void *v /*=m*/) { struct test *m = v; int64_t i; int x = thread_id(m); if ((x & 1) == 0) { for (i = 0; i != m->iterations; i++) { queue_append(&m->q, 1); } } else { for (i = 0; i != m->iterations; i++) { while (!queue_try_append(&m->q, 1)) { } } } mark_thread_done(m); } /* Consume elements from m->q until m->threads*m->iterations are seen, wait an extra second to confirm that no more elements are arriving, then mark thread as done. */ static void consumer(void *v /*=m*/) { struct test *m = v; int64_t n = m->iterations * m->threads; int64_t i; int value; for (i = 0; i != n; i++) { queue_remove(&m->q, &value, gpr_inf_future(GPR_CLOCK_REALTIME)); } gpr_mu_lock(&m->mu); m->counter = n; gpr_mu_unlock(&m->mu); GPR_ASSERT( !queue_remove(&m->q, &value, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_micros(1000000, GPR_TIMESPAN)))); mark_thread_done(m); } /* Increment m->stats_counter m->iterations times, transfer counter value to m->counter, then mark thread as done. */ static void statsinc(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations; i++) { gpr_stats_inc(&m->stats_counter, 1); } gpr_mu_lock(&m->mu); m->counter = gpr_stats_read(&m->stats_counter); gpr_mu_unlock(&m->mu); mark_thread_done(m); } /* Increment m->refcount by m->incr_step for m->iterations times. Decrement m->thread_refcount once, and if it reaches zero, set m->event to (void*)1; then mark thread as done. */ static void refinc(void *v /*=m*/) { struct test *m = v; int64_t i; for (i = 0; i != m->iterations; i++) { if (m->incr_step == 1) { gpr_ref(&m->refcount); } else { gpr_refn(&m->refcount, m->incr_step); } } if (gpr_unref(&m->thread_refcount)) { gpr_event_set(&m->event, (void *)1); } mark_thread_done(m); } /* Wait until m->event is set to (void *)1, then decrement m->refcount by 1 (m->threads * m->iterations * m->incr_step) times, and ensure that the last decrement caused the counter to reach zero, then mark thread as done. */ static void refcheck(void *v /*=m*/) { struct test *m = v; int64_t n = m->iterations * m->threads * m->incr_step; int64_t i; GPR_ASSERT(gpr_event_wait(&m->event, gpr_inf_future(GPR_CLOCK_REALTIME)) == (void *)1); GPR_ASSERT(gpr_event_get(&m->event) == (void *)1); for (i = 1; i != n; i++) { GPR_ASSERT(!gpr_unref(&m->refcount)); m->counter++; } GPR_ASSERT(gpr_unref(&m->refcount)); m->counter++; mark_thread_done(m); } /* ------------------------------------------------- */ int main(int argc, char *argv[]) { grpc_test_init(argc, argv); test("mutex", &inc, NULL, 1, 1); test("mutex try", &inctry, NULL, 1, 1); test("cv", &inc_by_turns, NULL, 1, 1); test("timedcv", &inc_with_1ms_delay, NULL, 1, 1); test("queue", &many_producers, &consumer, 10, 1); test("stats_counter", &statsinc, NULL, 1, 1); test("refcount by 1", &refinc, &refcheck, 1, 1); test("refcount by 3", &refinc, &refcheck, 1, 3); /* incr_step of 3 is an arbitrary choice. Any number > 1 is okay here */ test("timedevent", &inc_with_1ms_delay_event, NULL, 1, 1); return 0; }
/* * Copyright 2001-2011 Stephen Colebourne * * 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 org.joda.time; /** * Defines a partial time that does not support every datetime field, and is * thus a local time. * <p> * A {@code ReadablePartial} supports a subset of those fields on the chronology. * It cannot be compared to a {@code ReadableInstant}, as it does not fully * specify an instant in time. The time it does specify is a local time, and does * not include a time zone. * <p> * A {@code ReadablePartial} can be converted to a {@code ReadableInstant} * using the {@code toDateTime} method. This works by providing a full base * instant that can be used to 'fill in the gaps' and specify a time zone. * <p> * {@code ReadablePartial} is {@code Comparable} from v2.0. * The comparison is based on the fields, compared in order, from largest to smallest. * The first field that is non-equal is used to determine the result. * * @author Stephen Colebourne * @since 1.0 */ public interface ReadablePartial extends Comparable<ReadablePartial> { /** * Gets the number of fields that this partial supports. * * @return the number of fields supported */ int size(); /** * Gets the field type at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeFieldType getFieldType(int index); /** * Gets the field at the specified index. * * @param index the index to retrieve * @return the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ DateTimeField getField(int index); /** * Gets the value at the specified index. * * @param index the index to retrieve * @return the value of the field at the specified index * @throws IndexOutOfBoundsException if the index is invalid */ int getValue(int index); /** * Gets the chronology of the partial which is never null. * <p> * The {@link Chronology} is the calculation engine behind the partial and * provides conversion and validation of the fields in a particular calendar system. * * @return the chronology, never null */ Chronology getChronology(); /** * Gets the value of one of the fields. * <p> * The field type specified must be one of those that is supported by the partial. * * @param field a DateTimeFieldType instance that is supported by this partial * @return the value of that field * @throws IllegalArgumentException if the field is null or not supported */ int get(DateTimeFieldType field); /** * Checks whether the field type specified is supported by this partial. * * @param field the field to check, may be null which returns false * @return true if the field is supported */ boolean isSupported(DateTimeFieldType field); /** * Converts this partial to a full datetime by resolving it against another * datetime. * <p> * This method takes the specified datetime and sets the fields from this * instant on top. The chronology from the base instant is used. * <p> * For example, if this partial represents a time, then the result of this * method will be the datetime from the specified base instant plus the * time from this partial. * * @param baseInstant the instant that provides the missing fields, null means now * @return the combined datetime */ DateTime toDateTime(ReadableInstant baseInstant); //----------------------------------------------------------------------- /** * Compares this partial with the specified object for equality based * on the supported fields, chronology and values. * <p> * Two instances of ReadablePartial are equal if they have the same * chronology, same field types (in same order) and same values. * * @param partial the object to compare to * @return true if equal */ boolean equals(Object partial); /** * Gets a hash code for the partial that is compatible with the * equals method. * <p> * The formula used must be: * <pre> * int total = 157; * for (int i = 0; i < fields.length; i++) { * total = 23 * total + values[i]; * total = 23 * total + fieldTypes[i].hashCode(); * } * total += chronology.hashCode(); * return total; * </pre> * * @return a suitable hash code */ int hashCode(); //----------------------------------------------------------------------- // This is commented out to improve backwards compatibility // /** // * Compares this partial with another returning an integer // * indicating the order. // * <p> // * The fields are compared in order, from largest to smallest. // * The first field that is non-equal is used to determine the result. // * Thus a year-hour partial will first be compared on the year, and then // * on the hour. // * <p> // * The specified object must be a partial instance whose field types // * match those of this partial. If the partial instance has different // * fields then a {@code ClassCastException} is thrown. // * // * @param partial an object to check against // * @return negative if this is less, zero if equal, positive if greater // * @throws ClassCastException if the partial is the wrong class // * or if it has field types that don't match // * @throws NullPointerException if the partial is null // * @since 2.0, previously on {@code AbstractPartial} // */ // int compareTo(ReadablePartial partial); //----------------------------------------------------------------------- /** * Get the value as a String in a recognisable ISO8601 format, only * displaying supported fields. * <p> * The string output is in ISO8601 format to enable the String * constructor to correctly parse it. * * @return the value as an ISO8601 string */ String toString(); }
/* Copyright 2016 The Kubernetes 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. */ // Code generated by protoc-gen-gogo. // source: k8s.io/kubernetes/pkg/util/intstr/generated.proto // DO NOT EDIT! /* Package intstr is a generated protocol buffer package. It is generated from these files: k8s.io/kubernetes/pkg/util/intstr/generated.proto It has these top-level messages: IntOrString */ package intstr import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import io "io" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. const _ = proto.GoGoProtoPackageIsVersion1 func (m *IntOrString) Reset() { *m = IntOrString{} } func (*IntOrString) ProtoMessage() {} func (*IntOrString) Descriptor() ([]byte, []int) { return fileDescriptorGenerated, []int{0} } func init() { proto.RegisterType((*IntOrString)(nil), "k8s.io.client-go.1.5.pkg.util.intstr.IntOrString") } func (m *IntOrString) Marshal() (data []byte, err error) { size := m.Size() data = make([]byte, size) n, err := m.MarshalTo(data) if err != nil { return nil, err } return data[:n], nil } func (m *IntOrString) MarshalTo(data []byte) (int, error) { var i int _ = i var l int _ = l data[i] = 0x8 i++ i = encodeVarintGenerated(data, i, uint64(m.Type)) data[i] = 0x10 i++ i = encodeVarintGenerated(data, i, uint64(m.IntVal)) data[i] = 0x1a i++ i = encodeVarintGenerated(data, i, uint64(len(m.StrVal))) i += copy(data[i:], m.StrVal) return i, nil } func encodeFixed64Generated(data []byte, offset int, v uint64) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) data[offset+4] = uint8(v >> 32) data[offset+5] = uint8(v >> 40) data[offset+6] = uint8(v >> 48) data[offset+7] = uint8(v >> 56) return offset + 8 } func encodeFixed32Generated(data []byte, offset int, v uint32) int { data[offset] = uint8(v) data[offset+1] = uint8(v >> 8) data[offset+2] = uint8(v >> 16) data[offset+3] = uint8(v >> 24) return offset + 4 } func encodeVarintGenerated(data []byte, offset int, v uint64) int { for v >= 1<<7 { data[offset] = uint8(v&0x7f | 0x80) v >>= 7 offset++ } data[offset] = uint8(v) return offset + 1 } func (m *IntOrString) Size() (n int) { var l int _ = l n += 1 + sovGenerated(uint64(m.Type)) n += 1 + sovGenerated(uint64(m.IntVal)) l = len(m.StrVal) n += 1 + l + sovGenerated(uint64(l)) return n } func sovGenerated(x uint64) (n int) { for { n++ x >>= 7 if x == 0 { break } } return n } func sozGenerated(x uint64) (n int) { return sovGenerated(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *IntOrString) Unmarshal(data []byte) error { l := len(data) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: IntOrString: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: IntOrString: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Type", wireType) } m.Type = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ m.Type |= (Type(b) & 0x7F) << shift if b < 0x80 { break } } case 2: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field IntVal", wireType) } m.IntVal = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ m.IntVal |= (int32(b) & 0x7F) << shift if b < 0x80 { break } } case 3: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field StrVal", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowGenerated } if iNdEx >= l { return io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ stringLen |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthGenerated } postIndex := iNdEx + intStringLen if postIndex > l { return io.ErrUnexpectedEOF } m.StrVal = string(data[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipGenerated(data[iNdEx:]) if err != nil { return err } if skippy < 0 { return ErrInvalidLengthGenerated } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF } iNdEx += skippy } } if iNdEx > l { return io.ErrUnexpectedEOF } return nil } func skipGenerated(data []byte) (n int, err error) { l := len(data) iNdEx := 0 for iNdEx < l { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } wireType := int(wire & 0x7) switch wireType { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } iNdEx++ if data[iNdEx-1] < 0x80 { break } } return iNdEx, nil case 1: iNdEx += 8 return iNdEx, nil case 2: var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthGenerated } return iNdEx, nil case 3: for { var innerWire uint64 var start int = iNdEx for shift := uint(0); ; shift += 7 { if shift >= 64 { return 0, ErrIntOverflowGenerated } if iNdEx >= l { return 0, io.ErrUnexpectedEOF } b := data[iNdEx] iNdEx++ innerWire |= (uint64(b) & 0x7F) << shift if b < 0x80 { break } } innerWireType := int(innerWire & 0x7) if innerWireType == 4 { break } next, err := skipGenerated(data[start:]) if err != nil { return 0, err } iNdEx = start + next } return iNdEx, nil case 4: return iNdEx, nil case 5: iNdEx += 4 return iNdEx, nil default: return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } } panic("unreachable") } var ( ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling") ErrIntOverflowGenerated = fmt.Errorf("proto: integer overflow") ) var fileDescriptorGenerated = []byte{ // 256 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0x32, 0xcc, 0xb6, 0x28, 0xd6, 0xcb, 0xcc, 0xd7, 0xcf, 0x2e, 0x4d, 0x4a, 0x2d, 0xca, 0x4b, 0x2d, 0x49, 0x2d, 0xd6, 0x2f, 0xc8, 0x4e, 0xd7, 0x2f, 0x2d, 0xc9, 0xcc, 0xd1, 0xcf, 0xcc, 0x2b, 0x29, 0x2e, 0x29, 0xd2, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0x4a, 0x2c, 0x49, 0x4d, 0xd1, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x52, 0x84, 0x68, 0xd1, 0x43, 0x68, 0xd1, 0x03, 0x6a, 0xd1, 0x03, 0x69, 0xd1, 0x83, 0x68, 0x91, 0xd2, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0x4f, 0xcf, 0xd7, 0x07, 0xeb, 0x4c, 0x2a, 0x4d, 0x03, 0xf3, 0xc0, 0x1c, 0x30, 0x0b, 0x62, 0xa2, 0xd2, 0x44, 0x46, 0x2e, 0x6e, 0xcf, 0xbc, 0x12, 0xff, 0xa2, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x21, 0x0d, 0x2e, 0x96, 0x92, 0xca, 0x82, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x66, 0x27, 0x91, 0x13, 0xf7, 0xe4, 0x19, 0x1e, 0xdd, 0x93, 0x67, 0x09, 0x01, 0x8a, 0xfd, 0x82, 0xd2, 0x41, 0x60, 0x15, 0x42, 0x6a, 0x5c, 0x6c, 0x40, 0x2b, 0xc3, 0x12, 0x73, 0x24, 0x98, 0x80, 0x6a, 0x59, 0x9d, 0xf8, 0xa0, 0x6a, 0xd9, 0x3c, 0xc1, 0xa2, 0x41, 0x50, 0x59, 0x90, 0x3a, 0xa0, 0xbb, 0x40, 0xea, 0x98, 0x81, 0xea, 0x38, 0x11, 0xea, 0x82, 0xc1, 0xa2, 0x41, 0x50, 0x59, 0x2b, 0x8e, 0x19, 0x0b, 0xe4, 0x19, 0x1a, 0xee, 0x28, 0x30, 0x38, 0x69, 0x9c, 0x78, 0x28, 0xc7, 0x70, 0x01, 0x88, 0x6f, 0x00, 0x71, 0xc3, 0x23, 0x39, 0xc6, 0x13, 0x40, 0x7c, 0x01, 0x88, 0x1f, 0x00, 0xf1, 0x84, 0xc7, 0x72, 0x0c, 0x51, 0x6c, 0x10, 0xcf, 0x02, 0x02, 0x00, 0x00, 0xff, 0xff, 0x68, 0x57, 0xfb, 0xfa, 0x43, 0x01, 0x00, 0x00, }
<script> window.onload = function() { setTimeout(function() { if (sessionStorage.getItem("backToGet") == "step1") { sessionStorage.setItem("backToGet", "step2"); location.assign("../back-to-get-after-post.php"); } else { sessionStorage.removeItem("backToGet"); if (window.testRunner) testRunner.notifyDone(); } }, 0); }; </script>
/* * Copyright (C) 2011 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: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DOMNodeHighlighter.h" #if ENABLE(INSPECTOR) #include "Element.h" #include "Frame.h" #include "FrameView.h" #include "GraphicsContext.h" #include "Page.h" #include "Range.h" #include "RenderInline.h" #include "Settings.h" #include "StyledElement.h" #include "TextRun.h" namespace WebCore { namespace { Path quadToPath(const FloatQuad& quad) { Path quadPath; quadPath.moveTo(quad.p1()); quadPath.addLineTo(quad.p2()); quadPath.addLineTo(quad.p3()); quadPath.addLineTo(quad.p4()); quadPath.closeSubpath(); return quadPath; } void drawOutlinedQuad(GraphicsContext& context, const FloatQuad& quad, const Color& fillColor) { static const int outlineThickness = 2; static const Color outlineColor(62, 86, 180, 228); Path quadPath = quadToPath(quad); // Clip out the quad, then draw with a 2px stroke to get a pixel // of outline (because inflating a quad is hard) { context.save(); context.clipOut(quadPath); context.setStrokeThickness(outlineThickness); context.setStrokeColor(outlineColor, ColorSpaceDeviceRGB); context.strokePath(quadPath); context.restore(); } // Now do the fill context.setFillColor(fillColor, ColorSpaceDeviceRGB); context.fillPath(quadPath); } void drawOutlinedQuadWithClip(GraphicsContext& context, const FloatQuad& quad, const FloatQuad& clipQuad, const Color& fillColor) { context.save(); Path clipQuadPath = quadToPath(clipQuad); context.clipOut(clipQuadPath); drawOutlinedQuad(context, quad, fillColor); context.restore(); } void drawHighlightForBox(GraphicsContext& context, const FloatQuad& contentQuad, const FloatQuad& paddingQuad, const FloatQuad& borderQuad, const FloatQuad& marginQuad, DOMNodeHighlighter::HighlightMode mode) { static const Color contentBoxColor(125, 173, 217, 128); static const Color paddingBoxColor(125, 173, 217, 160); static const Color borderBoxColor(125, 173, 217, 192); static const Color marginBoxColor(125, 173, 217, 228); FloatQuad clipQuad; if (mode == DOMNodeHighlighter::HighlightMargin || (mode == DOMNodeHighlighter::HighlightAll && marginQuad != borderQuad)) { drawOutlinedQuadWithClip(context, marginQuad, borderQuad, marginBoxColor); clipQuad = borderQuad; } if (mode == DOMNodeHighlighter::HighlightBorder || (mode == DOMNodeHighlighter::HighlightAll && borderQuad != paddingQuad)) { drawOutlinedQuadWithClip(context, borderQuad, paddingQuad, borderBoxColor); clipQuad = paddingQuad; } if (mode == DOMNodeHighlighter::HighlightPadding || (mode == DOMNodeHighlighter::HighlightAll && paddingQuad != contentQuad)) { drawOutlinedQuadWithClip(context, paddingQuad, contentQuad, paddingBoxColor); clipQuad = contentQuad; } if (mode == DOMNodeHighlighter::HighlightContent || mode == DOMNodeHighlighter::HighlightAll) drawOutlinedQuad(context, contentQuad, contentBoxColor); else drawOutlinedQuadWithClip(context, clipQuad, clipQuad, contentBoxColor); } void drawHighlightForLineBoxesOrSVGRenderer(GraphicsContext& context, const Vector<FloatQuad>& lineBoxQuads) { static const Color lineBoxColor(125, 173, 217, 128); for (size_t i = 0; i < lineBoxQuads.size(); ++i) drawOutlinedQuad(context, lineBoxQuads[i], lineBoxColor); } inline IntSize frameToMainFrameOffset(Frame* frame) { IntPoint mainFramePoint = frame->page()->mainFrame()->view()->windowToContents(frame->view()->contentsToWindow(IntPoint())); return mainFramePoint - IntPoint(); } void drawElementTitle(GraphicsContext& context, Node* node, const IntRect& boundingBox, const IntRect& anchorBox, const FloatRect& overlayRect, WebCore::Settings* settings) { static const int rectInflatePx = 4; static const int fontHeightPx = 12; static const int borderWidthPx = 1; static const Color tooltipBackgroundColor(255, 255, 194, 255); static const Color tooltipBorderColor(Color::black); static const Color tooltipFontColor(Color::black); Element* element = static_cast<Element*>(node); bool isXHTML = element->document()->isXHTMLDocument(); String nodeTitle = isXHTML ? element->nodeName() : element->nodeName().lower(); const AtomicString& idValue = element->getIdAttribute(); if (!idValue.isNull() && !idValue.isEmpty()) { nodeTitle += "#"; nodeTitle += idValue; } if (element->hasClass() && element->isStyledElement()) { const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames(); size_t classNameCount = classNamesString.size(); if (classNameCount) { HashSet<AtomicString> usedClassNames; for (size_t i = 0; i < classNameCount; ++i) { const AtomicString& className = classNamesString[i]; if (usedClassNames.contains(className)) continue; usedClassNames.add(className); nodeTitle += "."; nodeTitle += className; } } } nodeTitle += " ["; nodeTitle += String::number(boundingBox.width()); nodeTitle.append(static_cast<UChar>(0x00D7)); // &times; nodeTitle += String::number(boundingBox.height()); nodeTitle += "]"; FontDescription desc; FontFamily family; family.setFamily(settings->fixedFontFamily()); desc.setFamily(family); desc.setComputedSize(fontHeightPx); Font font = Font(desc, 0, 0); font.update(0); TextRun nodeTitleRun(nodeTitle); IntPoint titleBasePoint = IntPoint(anchorBox.x(), anchorBox.maxY() - 1); titleBasePoint.move(rectInflatePx, rectInflatePx); IntRect titleRect = enclosingIntRect(font.selectionRectForText(nodeTitleRun, titleBasePoint, fontHeightPx)); titleRect.inflate(rectInflatePx); // The initial offsets needed to compensate for a 1px-thick border stroke (which is not a part of the rectangle). int dx = -borderWidthPx; int dy = borderWidthPx; // If the tip sticks beyond the right of overlayRect, right-align the tip with the said boundary. if (titleRect.maxX() > overlayRect.maxX()) dx = overlayRect.maxX() - titleRect.maxX(); // If the tip sticks beyond the left of overlayRect, left-align the tip with the said boundary. if (titleRect.x() + dx < overlayRect.x()) dx = overlayRect.x() - titleRect.x() - borderWidthPx; // If the tip sticks beyond the bottom of overlayRect, show the tip at top of bounding box. if (titleRect.maxY() > overlayRect.maxY()) { dy = anchorBox.y() - titleRect.maxY() - borderWidthPx; // If the tip still sticks beyond the bottom of overlayRect, bottom-align the tip with the said boundary. if (titleRect.maxY() + dy > overlayRect.maxY()) dy = overlayRect.maxY() - titleRect.maxY(); } // If the tip sticks beyond the top of overlayRect, show the tip at top of overlayRect. if (titleRect.y() + dy < overlayRect.y()) dy = overlayRect.y() - titleRect.y() + borderWidthPx; titleRect.move(dx, dy); context.setStrokeColor(tooltipBorderColor, ColorSpaceDeviceRGB); context.setStrokeThickness(borderWidthPx); context.setFillColor(tooltipBackgroundColor, ColorSpaceDeviceRGB); context.drawRect(titleRect); context.setFillColor(tooltipFontColor, ColorSpaceDeviceRGB); context.drawText(font, nodeTitleRun, IntPoint(titleRect.x() + rectInflatePx, titleRect.y() + font.fontMetrics().height())); } } // anonymous namespace namespace DOMNodeHighlighter { void DrawNodeHighlight(GraphicsContext& context, Node* node, HighlightMode mode) { node->document()->updateLayoutIgnorePendingStylesheets(); RenderObject* renderer = node->renderer(); Frame* containingFrame = node->document()->frame(); if (!renderer || !containingFrame) return; IntSize mainFrameOffset = frameToMainFrameOffset(containingFrame); IntRect boundingBox = renderer->absoluteBoundingBoxRect(true); boundingBox.move(mainFrameOffset); IntRect titleAnchorBox = boundingBox; FrameView* view = containingFrame->page()->mainFrame()->view(); FloatRect overlayRect = view->visibleContentRect(); if (!overlayRect.contains(boundingBox) && !boundingBox.contains(enclosingIntRect(overlayRect))) overlayRect = view->visibleContentRect(); context.translate(-overlayRect.x(), -overlayRect.y()); // RenderSVGRoot should be highlighted through the isBox() code path, all other SVG elements should just dump their absoluteQuads(). #if ENABLE(SVG) bool isSVGRenderer = renderer->node() && renderer->node()->isSVGElement() && !renderer->isSVGRoot(); #else bool isSVGRenderer = false; #endif if (renderer->isBox() && !isSVGRenderer) { RenderBox* renderBox = toRenderBox(renderer); // RenderBox returns the "pure" content area box, exclusive of the scrollbars (if present), which also count towards the content area in CSS. IntRect contentBox = renderBox->contentBoxRect(); contentBox.setWidth(contentBox.width() + renderBox->verticalScrollbarWidth()); contentBox.setHeight(contentBox.height() + renderBox->horizontalScrollbarHeight()); IntRect paddingBox(contentBox.x() - renderBox->paddingLeft(), contentBox.y() - renderBox->paddingTop(), contentBox.width() + renderBox->paddingLeft() + renderBox->paddingRight(), contentBox.height() + renderBox->paddingTop() + renderBox->paddingBottom()); IntRect borderBox(paddingBox.x() - renderBox->borderLeft(), paddingBox.y() - renderBox->borderTop(), paddingBox.width() + renderBox->borderLeft() + renderBox->borderRight(), paddingBox.height() + renderBox->borderTop() + renderBox->borderBottom()); IntRect marginBox(borderBox.x() - renderBox->marginLeft(), borderBox.y() - renderBox->marginTop(), borderBox.width() + renderBox->marginLeft() + renderBox->marginRight(), borderBox.height() + renderBox->marginTop() + renderBox->marginBottom()); FloatQuad absContentQuad = renderBox->localToAbsoluteQuad(FloatRect(contentBox)); FloatQuad absPaddingQuad = renderBox->localToAbsoluteQuad(FloatRect(paddingBox)); FloatQuad absBorderQuad = renderBox->localToAbsoluteQuad(FloatRect(borderBox)); FloatQuad absMarginQuad = renderBox->localToAbsoluteQuad(FloatRect(marginBox)); absContentQuad.move(mainFrameOffset); absPaddingQuad.move(mainFrameOffset); absBorderQuad.move(mainFrameOffset); absMarginQuad.move(mainFrameOffset); titleAnchorBox = absMarginQuad.enclosingBoundingBox(); drawHighlightForBox(context, absContentQuad, absPaddingQuad, absBorderQuad, absMarginQuad, mode); } else if (renderer->isRenderInline() || isSVGRenderer) { // FIXME: We should show margins/padding/border for inlines. Vector<FloatQuad> lineBoxQuads; renderer->absoluteQuads(lineBoxQuads); for (unsigned i = 0; i < lineBoxQuads.size(); ++i) lineBoxQuads[i] += mainFrameOffset; drawHighlightForLineBoxesOrSVGRenderer(context, lineBoxQuads); } // Draw node title if necessary. if (!node->isElementNode()) return; WebCore::Settings* settings = containingFrame->settings(); if (mode == DOMNodeHighlighter::HighlightAll) drawElementTitle(context, node, boundingBox, titleAnchorBox, overlayRect, settings); } } // namespace DOMNodeHighlighter } // namespace WebCore #endif // ENABLE(INSPECTOR)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>Dynamic handling of combinators</title> <style type="text/css"> #test { background: red; display: block; padding: 1em; } #stub ~ div div + div > div { background: lime; } </style> <link rel="first" href="css3-modsel-1.html" title="Groups of selectors"> <link rel="prev" href="css3-modsel-d1b.html" title="Dynamic handling of :empty"> <link rel="next" href="css3-modsel-d4.html" title="Dynamic updating of :first-child and :last-child"> <link rel="last" href="css3-modsel-d4.html" title="Dynamic updating of :first-child and :last-child"> <link rel="up" href="./index.html"> <link rel="top" href="../../index.html"> </head> <body> <div> <script type="text/javascript"> function test() { el = document.getElementById('test'); el.parentNode.parentNode.insertBefore(document.createElement('div'), el.parentNode); } window.onload = test; </script> <p> The following bar should be green. </p> <div id="stub"></div> <div></div> <div><div><!-- <div/> --><div><div id="test"></div></div></div></div> </div> </body> </html>
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v5.0.0-alpha.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 csvCreator_1 = require("./csvCreator"); var rowRenderer_1 = require("./rendering/rowRenderer"); var headerRenderer_1 = require("./headerRendering/headerRenderer"); var filterManager_1 = require("./filter/filterManager"); var columnController_1 = require("./columnController/columnController"); var selectionController_1 = require("./selectionController"); var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); var gridPanel_1 = require("./gridPanel/gridPanel"); var valueService_1 = require("./valueService"); var masterSlaveService_1 = require("./masterSlaveService"); var eventService_1 = require("./eventService"); var floatingRowModel_1 = require("./rowControllers/floatingRowModel"); var constants_1 = require("./constants"); var context_1 = require("./context/context"); var gridCore_1 = require("./gridCore"); var sortController_1 = require("./sortController"); var paginationController_1 = require("./rowControllers/paginationController"); var focusedCellController_1 = require("./focusedCellController"); var utils_1 = require("./utils"); var cellRendererFactory_1 = require("./rendering/cellRendererFactory"); var cellEditorFactory_1 = require("./rendering/cellEditorFactory"); var GridApi = (function () { function GridApi() { } GridApi.prototype.init = function () { if (this.rowModel.getType() === constants_1.Constants.ROW_MODEL_TYPE_NORMAL) { this.inMemoryRowModel = this.rowModel; } }; /** Used internally by grid. Not intended to be used by the client. Interface may change between releases. */ GridApi.prototype.__getMasterSlaveService = function () { return this.masterSlaveService; }; GridApi.prototype.getFirstRenderedRow = function () { return this.rowRenderer.getFirstVirtualRenderedRow(); }; GridApi.prototype.getLastRenderedRow = function () { return this.rowRenderer.getLastVirtualRenderedRow(); }; GridApi.prototype.getDataAsCsv = function (params) { return this.csvCreator.getDataAsCsv(params); }; GridApi.prototype.exportDataAsCsv = function (params) { this.csvCreator.exportDataAsCsv(params); }; GridApi.prototype.setDatasource = function (datasource) { if (this.gridOptionsWrapper.isRowModelPagination()) { this.paginationController.setDatasource(datasource); } else if (this.gridOptionsWrapper.isRowModelVirtual()) { this.rowModel.setDatasource(datasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIRTUAL + "' or '" + constants_1.Constants.ROW_MODEL_TYPE_PAGINATION + "'"); } }; GridApi.prototype.setViewportDatasource = function (viewportDatasource) { if (this.gridOptionsWrapper.isRowModelViewport()) { // this is bad coding, because it's using an interface that's exposed in the enterprise. // really we should create an interface in the core for viewportDatasource and let // the enterprise implement it, rather than casting to 'any' here this.rowModel.setViewportDatasource(viewportDatasource); } else { console.warn("ag-Grid: you can only use a datasource when gridOptions.rowModelType is '" + constants_1.Constants.ROW_MODEL_TYPE_VIEWPORT + "'"); } }; GridApi.prototype.setRowData = function (rowData) { if (this.gridOptionsWrapper.isRowModelDefault()) { this.inMemoryRowModel.setRowData(rowData, true); } else { console.log('cannot call setRowData unless using normal row model'); } }; GridApi.prototype.setFloatingTopRowData = function (rows) { this.floatingRowModel.setFloatingTopRowData(rows); }; GridApi.prototype.setFloatingBottomRowData = function (rows) { this.floatingRowModel.setFloatingBottomRowData(rows); }; GridApi.prototype.setColumnDefs = function (colDefs) { this.columnController.setColumnDefs(colDefs); }; GridApi.prototype.refreshRows = function (rowNodes) { this.rowRenderer.refreshRows(rowNodes); }; GridApi.prototype.refreshCells = function (rowNodes, colIds, animate) { if (animate === void 0) { animate = false; } this.rowRenderer.refreshCells(rowNodes, colIds, animate); }; GridApi.prototype.rowDataChanged = function (rows) { this.rowRenderer.rowDataChanged(rows); }; GridApi.prototype.refreshView = function () { this.rowRenderer.refreshView(); }; GridApi.prototype.softRefreshView = function () { this.rowRenderer.softRefreshView(); }; GridApi.prototype.refreshGroupRows = function () { this.rowRenderer.refreshGroupRows(); }; GridApi.prototype.refreshHeader = function () { // need to review this - the refreshHeader should also refresh all icons in the header this.headerRenderer.refreshHeader(); }; GridApi.prototype.isAnyFilterPresent = function () { return this.filterManager.isAnyFilterPresent(); }; GridApi.prototype.isAdvancedFilterPresent = function () { return this.filterManager.isAdvancedFilterPresent(); }; GridApi.prototype.isQuickFilterPresent = function () { return this.filterManager.isQuickFilterPresent(); }; GridApi.prototype.getModel = function () { return this.rowModel; }; GridApi.prototype.onGroupExpandedOrCollapsed = function (refreshFromIndex) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call onGroupExpandedOrCollapsed unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_MAP, refreshFromIndex); }; GridApi.prototype.refreshInMemoryRowModel = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call refreshInMemoryRowModel unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_EVERYTHING); }; GridApi.prototype.expandAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call expandAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(true); }; GridApi.prototype.collapseAll = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call collapseAll unless using normal row model'); } this.inMemoryRowModel.expandOrCollapseAll(false); }; GridApi.prototype.addVirtualRowListener = function (eventName, rowIndex, callback) { if (typeof eventName !== 'string') { console.log('ag-Grid: addVirtualRowListener is deprecated, please use addRenderedRowListener.'); } this.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.addRenderedRowListener = function (eventName, rowIndex, callback) { if (eventName === 'virtualRowRemoved') { console.log('ag-Grid: event virtualRowRemoved is deprecated, now called renderedRowRemoved'); eventName = '' + ''; } if (eventName === 'virtualRowSelected') { console.log('ag-Grid: event virtualRowSelected is deprecated, to register for individual row ' + 'selection events, add a listener directly to the row node.'); } this.rowRenderer.addRenderedRowListener(eventName, rowIndex, callback); }; GridApi.prototype.setQuickFilter = function (newFilter) { this.filterManager.setQuickFilter(newFilter); }; GridApi.prototype.selectIndex = function (index, tryMulti, suppressEvents) { console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.selectIndex(index, tryMulti); }; GridApi.prototype.deselectIndex = function (index, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: do not use api for selection, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } this.selectionController.deselectIndex(index); }; GridApi.prototype.selectNode = function (node, tryMulti, suppressEvents) { if (tryMulti === void 0) { tryMulti = false; } if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: true, clearSelection: !tryMulti }); }; GridApi.prototype.deselectNode = function (node, suppressEvents) { if (suppressEvents === void 0) { suppressEvents = false; } console.log('ag-Grid: API for selection is deprecated, call node.setSelected(value) instead'); if (suppressEvents) { console.log('ag-Grid: suppressEvents is no longer supported, stop listening for the event if you no longer want it'); } node.setSelectedParams({ newValue: false }); }; GridApi.prototype.selectAll = function () { this.selectionController.selectAllRowNodes(); }; GridApi.prototype.deselectAll = function () { this.selectionController.deselectAllRowNodes(); }; GridApi.prototype.recomputeAggregates = function () { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call recomputeAggregates unless using normal row model'); } this.inMemoryRowModel.refreshModel(constants_1.Constants.STEP_AGGREGATE); }; GridApi.prototype.sizeColumnsToFit = function () { if (this.gridOptionsWrapper.isForPrint()) { console.warn('ag-grid: sizeColumnsToFit does not work when forPrint=true'); return; } this.gridPanel.sizeColumnsToFit(); }; GridApi.prototype.showLoadingOverlay = function () { this.gridPanel.showLoadingOverlay(); }; GridApi.prototype.showNoRowsOverlay = function () { this.gridPanel.showNoRowsOverlay(); }; GridApi.prototype.hideOverlay = function () { this.gridPanel.hideOverlay(); }; GridApi.prototype.isNodeSelected = function (node) { console.log('ag-Grid: no need to call api.isNodeSelected(), just call node.isSelected() instead'); return node.isSelected(); }; GridApi.prototype.getSelectedNodesById = function () { console.error('ag-Grid: since version 3.4, getSelectedNodesById no longer exists, use getSelectedNodes() instead'); return null; }; GridApi.prototype.getSelectedNodes = function () { return this.selectionController.getSelectedNodes(); }; GridApi.prototype.getSelectedRows = function () { return this.selectionController.getSelectedRows(); }; GridApi.prototype.getBestCostNodeSelection = function () { return this.selectionController.getBestCostNodeSelection(); }; GridApi.prototype.getRenderedNodes = function () { return this.rowRenderer.getRenderedNodes(); }; GridApi.prototype.ensureColIndexVisible = function (index) { console.warn('ag-Grid: ensureColIndexVisible(index) no longer supported, use ensureColumnVisible(colKey) instead.'); }; GridApi.prototype.ensureColumnVisible = function (key) { this.gridPanel.ensureColumnVisible(key); }; GridApi.prototype.ensureIndexVisible = function (index) { this.gridPanel.ensureIndexVisible(index); }; GridApi.prototype.ensureNodeVisible = function (comparator) { this.gridCore.ensureNodeVisible(comparator); }; GridApi.prototype.forEachLeafNode = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachLeafNode(callback); }; GridApi.prototype.forEachNode = function (callback) { this.rowModel.forEachNode(callback); }; GridApi.prototype.forEachNodeAfterFilter = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilter unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilter(callback); }; GridApi.prototype.forEachNodeAfterFilterAndSort = function (callback) { if (utils_1.Utils.missing(this.inMemoryRowModel)) { console.log('cannot call forEachNodeAfterFilterAndSort unless using normal row model'); } this.inMemoryRowModel.forEachNodeAfterFilterAndSort(callback); }; GridApi.prototype.getFilterApiForColDef = function (colDef) { console.warn('ag-grid API method getFilterApiForColDef deprecated, use getFilterApi instead'); return this.getFilterApi(colDef); }; GridApi.prototype.getFilterApi = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.getFilterApi(column); } }; GridApi.prototype.destroyFilter = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return this.filterManager.destroyFilter(column); } }; GridApi.prototype.getColumnDef = function (key) { var column = this.columnController.getPrimaryColumn(key); if (column) { return column.getColDef(); } else { return null; } }; GridApi.prototype.onFilterChanged = function () { this.filterManager.onFilterChanged(); }; GridApi.prototype.setSortModel = function (sortModel) { this.sortController.setSortModel(sortModel); }; GridApi.prototype.getSortModel = function () { return this.sortController.getSortModel(); }; GridApi.prototype.setFilterModel = function (model) { this.filterManager.setFilterModel(model); }; GridApi.prototype.getFilterModel = function () { return this.filterManager.getFilterModel(); }; GridApi.prototype.getFocusedCell = function () { return this.focusedCellController.getFocusedCell(); }; GridApi.prototype.setFocusedCell = function (rowIndex, colKey, floating) { this.focusedCellController.setFocusedCell(rowIndex, colKey, floating, true); }; GridApi.prototype.setHeaderHeight = function (headerHeight) { this.gridOptionsWrapper.setHeaderHeight(headerHeight); }; GridApi.prototype.showToolPanel = function (show) { this.gridCore.showToolPanel(show); }; GridApi.prototype.isToolPanelShowing = function () { return this.gridCore.isToolPanelShowing(); }; GridApi.prototype.doLayout = function () { this.gridCore.doLayout(); }; GridApi.prototype.getValue = function (colKey, rowNode) { var column = this.columnController.getPrimaryColumn(colKey); return this.valueService.getValue(column, rowNode); }; GridApi.prototype.addEventListener = function (eventType, listener) { this.eventService.addEventListener(eventType, listener); }; GridApi.prototype.addGlobalListener = function (listener) { this.eventService.addGlobalListener(listener); }; GridApi.prototype.removeEventListener = function (eventType, listener) { this.eventService.removeEventListener(eventType, listener); }; GridApi.prototype.removeGlobalListener = function (listener) { this.eventService.removeGlobalListener(listener); }; GridApi.prototype.dispatchEvent = function (eventType, event) { this.eventService.dispatchEvent(eventType, event); }; GridApi.prototype.destroy = function () { this.context.destroy(); }; GridApi.prototype.resetQuickFilter = function () { this.rowModel.forEachNode(function (node) { return node.quickFilterAggregateText = null; }); }; GridApi.prototype.getRangeSelections = function () { if (this.rangeController) { return this.rangeController.getCellRanges(); } else { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); return null; } }; GridApi.prototype.addRangeSelection = function (rangeSelection) { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.addRange(rangeSelection); }; GridApi.prototype.clearRangeSelection = function () { if (!this.rangeController) { console.warn('ag-Grid: cell range selection is only available in ag-Grid Enterprise'); } this.rangeController.clearSelection(); }; GridApi.prototype.copySelectedRowsToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRowsToClipboard(); }; GridApi.prototype.copySelectedRangeToClipboard = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copySelectedRangeToClipboard(); }; GridApi.prototype.copySelectedRangeDown = function () { if (!this.clipboardService) { console.warn('ag-Grid: clipboard is only available in ag-Grid Enterprise'); } this.clipboardService.copyRangeDown(); }; GridApi.prototype.showColumnMenuAfterButtonClick = function (colKey, buttonElement) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterButtonClick(column, buttonElement); }; GridApi.prototype.showColumnMenuAfterMouseClick = function (colKey, mouseEvent) { var column = this.columnController.getPrimaryColumn(colKey); this.menuFactory.showMenuAfterMouseEvent(column, mouseEvent); }; GridApi.prototype.stopEditing = function (cancel) { if (cancel === void 0) { cancel = false; } this.rowRenderer.stopEditing(cancel); }; GridApi.prototype.addAggFunc = function (key, aggFunc) { if (this.aggFuncService) { this.aggFuncService.addAggFunc(key, aggFunc); } }; GridApi.prototype.addAggFuncs = function (aggFuncs) { if (this.aggFuncService) { this.aggFuncService.addAggFuncs(aggFuncs); } }; GridApi.prototype.clearAggFuncs = function () { if (this.aggFuncService) { this.aggFuncService.clear(); } }; __decorate([ context_1.Autowired('csvCreator'), __metadata('design:type', csvCreator_1.CsvCreator) ], GridApi.prototype, "csvCreator", void 0); __decorate([ context_1.Autowired('gridCore'), __metadata('design:type', gridCore_1.GridCore) ], GridApi.prototype, "gridCore", void 0); __decorate([ context_1.Autowired('rowRenderer'), __metadata('design:type', rowRenderer_1.RowRenderer) ], GridApi.prototype, "rowRenderer", void 0); __decorate([ context_1.Autowired('headerRenderer'), __metadata('design:type', headerRenderer_1.HeaderRenderer) ], GridApi.prototype, "headerRenderer", void 0); __decorate([ context_1.Autowired('filterManager'), __metadata('design:type', filterManager_1.FilterManager) ], GridApi.prototype, "filterManager", void 0); __decorate([ context_1.Autowired('columnController'), __metadata('design:type', columnController_1.ColumnController) ], GridApi.prototype, "columnController", void 0); __decorate([ context_1.Autowired('selectionController'), __metadata('design:type', selectionController_1.SelectionController) ], GridApi.prototype, "selectionController", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper) ], GridApi.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('gridPanel'), __metadata('design:type', gridPanel_1.GridPanel) ], GridApi.prototype, "gridPanel", void 0); __decorate([ context_1.Autowired('valueService'), __metadata('design:type', valueService_1.ValueService) ], GridApi.prototype, "valueService", void 0); __decorate([ context_1.Autowired('masterSlaveService'), __metadata('design:type', masterSlaveService_1.MasterSlaveService) ], GridApi.prototype, "masterSlaveService", void 0); __decorate([ context_1.Autowired('eventService'), __metadata('design:type', eventService_1.EventService) ], GridApi.prototype, "eventService", void 0); __decorate([ context_1.Autowired('floatingRowModel'), __metadata('design:type', floatingRowModel_1.FloatingRowModel) ], GridApi.prototype, "floatingRowModel", void 0); __decorate([ context_1.Autowired('context'), __metadata('design:type', context_1.Context) ], GridApi.prototype, "context", void 0); __decorate([ context_1.Autowired('rowModel'), __metadata('design:type', Object) ], GridApi.prototype, "rowModel", void 0); __decorate([ context_1.Autowired('sortController'), __metadata('design:type', sortController_1.SortController) ], GridApi.prototype, "sortController", void 0); __decorate([ context_1.Autowired('paginationController'), __metadata('design:type', paginationController_1.PaginationController) ], GridApi.prototype, "paginationController", void 0); __decorate([ context_1.Autowired('focusedCellController'), __metadata('design:type', focusedCellController_1.FocusedCellController) ], GridApi.prototype, "focusedCellController", void 0); __decorate([ context_1.Optional('rangeController'), __metadata('design:type', Object) ], GridApi.prototype, "rangeController", void 0); __decorate([ context_1.Optional('clipboardService'), __metadata('design:type', Object) ], GridApi.prototype, "clipboardService", void 0); __decorate([ context_1.Optional('aggFuncService'), __metadata('design:type', Object) ], GridApi.prototype, "aggFuncService", void 0); __decorate([ context_1.Autowired('menuFactory'), __metadata('design:type', Object) ], GridApi.prototype, "menuFactory", void 0); __decorate([ context_1.Autowired('cellRendererFactory'), __metadata('design:type', cellRendererFactory_1.CellRendererFactory) ], GridApi.prototype, "cellRendererFactory", void 0); __decorate([ context_1.Autowired('cellEditorFactory'), __metadata('design:type', cellEditorFactory_1.CellEditorFactory) ], GridApi.prototype, "cellEditorFactory", void 0); __decorate([ context_1.PostConstruct, __metadata('design:type', Function), __metadata('design:paramtypes', []), __metadata('design:returntype', void 0) ], GridApi.prototype, "init", null); GridApi = __decorate([ context_1.Bean('gridApi'), __metadata('design:paramtypes', []) ], GridApi); return GridApi; })(); exports.GridApi = GridApi;
/// <reference path="ng-grid.d.ts" /> var options1: ngGrid.IGridOptions = { data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }] }; var options2: ngGrid.IGridOptions = { afterSelectionChange: () => { }, beforeSelectionChange: () => {return true; }, dataUpdated: () => { } }; var options3: ngGrid.IGridOptions = { columnDefs: [ { field: 'name', displayName: 'Name' }, { field: 'age', displayName: 'Age' } ] }; var options4: ngGrid.IGridOptions = { pagingOptions: { pageSizes: [1, 2, 3, 4], pageSize: 2, totalServerItems: 100, currentPage: 1 } };
from __future__ import absolute_import, division import time import os try: unicode except NameError: unicode = str from . import LockBase, NotLocked, NotMyLock, LockTimeout, AlreadyLocked class SQLiteLockFile(LockBase): "Demonstrate SQL-based locking." testdb = None def __init__(self, path, threaded=True, timeout=None): """ >>> lock = SQLiteLockFile('somefile') >>> lock = SQLiteLockFile('somefile', threaded=False) """ LockBase.__init__(self, path, threaded, timeout) self.lock_file = unicode(self.lock_file) self.unique_name = unicode(self.unique_name) if SQLiteLockFile.testdb is None: import tempfile _fd, testdb = tempfile.mkstemp() os.close(_fd) os.unlink(testdb) del _fd, tempfile SQLiteLockFile.testdb = testdb import sqlite3 self.connection = sqlite3.connect(SQLiteLockFile.testdb) c = self.connection.cursor() try: c.execute("create table locks" "(" " lock_file varchar(32)," " unique_name varchar(32)" ")") except sqlite3.OperationalError: pass else: self.connection.commit() import atexit atexit.register(os.unlink, SQLiteLockFile.testdb) def acquire(self, timeout=None): timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout if timeout is None: wait = 0.1 elif timeout <= 0: wait = 0 else: wait = timeout / 10 cursor = self.connection.cursor() while True: if not self.is_locked(): # Not locked. Try to lock it. cursor.execute("insert into locks" " (lock_file, unique_name)" " values" " (?, ?)", (self.lock_file, self.unique_name)) self.connection.commit() # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) > 1: # Nope. Someone else got there. Remove our lock. cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() else: # Yup. We're done, so go home. return else: # Check to see if we are the only lock holder. cursor.execute("select * from locks" " where unique_name = ?", (self.unique_name,)) rows = cursor.fetchall() if len(rows) == 1: # We're the locker, so go home. return # Maybe we should wait a bit longer. if timeout is not None and time.time() > end_time: if timeout > 0: # No more waiting. raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: # Someone else has the lock and we are impatient.. raise AlreadyLocked("%s is already locked" % self.path) # Well, okay. We'll give it a bit longer. time.sleep(wait) def release(self): if not self.is_locked(): raise NotLocked("%s is not locked" % self.path) if not self.i_am_locking(): raise NotMyLock("%s is locked, but not by me (by %s)" % (self.unique_name, self._who_is_locking())) cursor = self.connection.cursor() cursor.execute("delete from locks" " where unique_name = ?", (self.unique_name,)) self.connection.commit() def _who_is_locking(self): cursor = self.connection.cursor() cursor.execute("select unique_name from locks" " where lock_file = ?", (self.lock_file,)) return cursor.fetchone()[0] def is_locked(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?", (self.lock_file,)) rows = cursor.fetchall() return not not rows def i_am_locking(self): cursor = self.connection.cursor() cursor.execute("select * from locks" " where lock_file = ?" " and unique_name = ?", (self.lock_file, self.unique_name)) return not not cursor.fetchall() def break_lock(self): cursor = self.connection.cursor() cursor.execute("delete from locks" " where lock_file = ?", (self.lock_file,)) self.connection.commit()
<!DOCTYPE html> <!--[if IE 8 ]><html lang="en" class="ie8"><![endif]--> <!--[if IE 9 ]><html lang="en" class="ie9"><![endif]--> <!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]--> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>jQuery custom scrollbar demo</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- stylesheet for demo and examples --> <link rel="stylesheet" href="style.css"> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"></script> <![endif]--> <!-- custom scrollbar stylesheet --> <link rel="stylesheet" href="../jquery.mCustomScrollbar.css"> </head> <body> <header> <a href="http://manos.malihu.gr/jquery-custom-content-scroller/" class="logo"><img src="logo.png" alt="jQuery custom scrollbar" /></a> <hr /> </header> <div id="demo" class="showcase scrollTo-demo"> <section id="info"> <div class="scrollTo"> <ul> <li><span>Content y &rarr;</span></li> <li><a href="#" rel="content-y" data-scroll-to="p:eq(2)">Scroll to 3rd paragraph</a></li> <li><a href="#bottom" rel="content-y">Scroll to bottom</a></li> <li><a href="#" rel="content-y" data-scroll-to="p:eq(0)">Scroll to 1st paragraph</a></li> <li><a href="#850" rel="content-y">Scroll to 850 pixels</a></li> <li><a href="#-=100" rel="content-y">Scroll by 100 pixels more</a></li> <li><a href="#+=100" rel="content-y">Scroll by 100 pixels less</a></li> <li><a href="#50%" rel="content-y">Scroll to 50%</a></li> </ul> </div> <div class="scrollTo"> <ul> <li><span>Content x &rarr;</span></li> <li><a href="#10%" rel="content-x">Scroll to 10%</a></li> <li><a href="##test-id" rel="content-x">Scroll to (id) red paragraph</a></li> <li><a href="#" rel="content-x" data-scroll-to="#test-id+p">Scroll to the paragraph next to the red one</a></li> <li><a href="#-=350" rel="content-x">Scroll by 350 pixels more (paragraph's outer width)</a></li> <li><a href="#first" rel="content-x">Scroll to 1st element</a></li> </ul> </div> <div class="scrollTo"> <ul> <li><span>Content yx &rarr;</span></li> <li><a href="#" rel="content-yx" data-scroll-to="p:eq(4)">Scroll to 5th paragraph</a></li> <li><a href="#['bottom','right']" rel="content-yx">Scroll to bottom/right</a></li> <li><a href="#'last'" rel="content-yx">Scroll to last element</a></li> <li><a href='#{y:"450",x:"250"}' rel="content-yx">Scroll to y:450, x:250 pixels</a></li> <li><a href="#['-=100','-=50']" rel="content-yx">Scroll by y:100 and x:50 pixels more</a></li> <li><a href="#['top',null]" rel="content-yx">Scroll to top</a></li> </ul> </div> <p>Function called: <code>&nbsp;</code></p> </section> <section id="examples"> <!-- content --> <div class="content demo-y"> <h2>Content y</h2> <hr /> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> <p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p> <p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?</p> <p>Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.</p> <p>Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.</p> <p>Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> <p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p> <p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?</p> <hr /> <p>End of content.</p> </div> <!-- content --> <div class="content demo-x"> <h2>Content x</h2> <hr /> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> <p id="test-id">Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p> <p>Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p> <p>Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>End of content.</p> </div> <!-- content --> <div class="content demo-yx"> <h2>Content yx</h2> <hr /> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.</p> <p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p> <p>Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?</p> <p>Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p> <p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.</p> <p>Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.</p> <p>Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p> <hr /> <p>End of content.</p> </div> </section> </div> <footer> <hr /> <p><a href="http://manos.malihu.gr/jquery-custom-content-scroller">Plugin home</a> <a href="https://github.com/malihu/malihu-custom-scrollbar-plugin">Project on Github</a> <a href="http://opensource.org/licenses/MIT">MIT License</a></p> </footer> <!-- Google CDN jQuery with fallback to local --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="../js/minified/jquery-1.11.0.min.js"><\/script>')</script> <!-- custom scrollbar plugin --> <script src="../jquery.mCustomScrollbar.concat.min.js"></script> <script> (function($){ $(window).load(function(){ $.mCustomScrollbar.defaults.theme="light-2"; //set "light-2" as the default theme $(".demo-y").mCustomScrollbar(); $(".demo-x").mCustomScrollbar({ axis:"x", advanced:{autoExpandHorizontalScroll:true} }); $(".demo-yx").mCustomScrollbar({ axis:"yx" }); $(".scrollTo a").click(function(e){ e.preventDefault(); var $this=$(this), rel=$this.attr("rel"), el=rel==="content-y" ? ".demo-y" : rel==="content-x" ? ".demo-x" : ".demo-yx", data=$this.data("scroll-to"), href=$this.attr("href").split(/#(.+)/)[1], to=data ? $(el).find(".mCSB_container").find(data) : el===".demo-yx" ? eval("("+href+")") : href, output=$("#info > p code"), outputTXTdata=el===".demo-yx" ? data : "'"+data+"'", outputTXThref=el===".demo-yx" ? href : "'"+href+"'", outputTXT=data ? "$('"+el+"').find('.mCSB_container').find("+outputTXTdata+")" : outputTXThref; $(el).mCustomScrollbar("scrollTo",to); output.text("$('"+el+"').mCustomScrollbar('scrollTo',"+outputTXT+");"); }); }); })(jQuery); </script> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>jQuery plugin: Tablesorter 2.0 - Custom Filter Widget Formatter (jQuery UI widgets)</title> <!-- jQuery --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script> <!-- Demo stuff --> <link class="ui-theme" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/cupertino/jquery-ui.css"> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script> <link rel="stylesheet" href="css/jq.css"> <link href="css/prettify.css" rel="stylesheet"> <script src="js/prettify.js"></script> <script src="js/docs.js"></script> <style> th { width: 15%; } </style> <!-- Tablesorter: required --> <link href="../css/theme.blue.css" rel="stylesheet"> <link href="../css/filter.formatter.css" rel="stylesheet"> <script src="../js/jquery.tablesorter.js"></script> <script src="../js/jquery.tablesorter.widgets.js"></script> <script src="../js/jquery.tablesorter.widgets-filter-formatter.js"></script> <script> $(function(){ $('.accordion').accordion({ heightStyle: 'content', collapsible : true }); }); </script> <script id="js">$(function() { // call the tablesorter plugin $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter", "stickyHeaders"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { // Rank 0 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSlider( $cell, indx, { value : 0, min : 0, max : 100, delayed : true, valueToHeader: false }); }, // Age 1 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSlider( $cell, indx, { // add any of the jQuery UI Slider options here value : 1, min : 1, max : 65, delayed : false, valueToHeader : false, exactMatch : false, allText : 'all', // this is ignored when compare is not empty compare : '>=' }); }, // Total 2 : function($cell, indx){ return $.tablesorter.filterFormatter.uiRange( $cell, indx, { values : [1, 160], min : 1, max : 160, delayed : false, valueToHeader : false }); }, // Discount 3 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSpinner( $cell, indx, { min : 0, max : 45, value : 1, step : 1, delayed : true, addToggle : true, exactMatch : true, compare: '' }); }, // Date (one input) 4 : function($cell, indx){ return $.tablesorter.filterFormatter.uiDateCompare( $cell, indx, { // defaultDate : '1/1/2014', // default date cellText : 'dates >= ', // text added before the input changeMonth : true, changeYear : true, compare : '>=' }); }, // Date (two inputs) 5 : function($cell, indx){ return $.tablesorter.filterFormatter.uiDatepicker( $cell, indx, { // from : '08/01/2013', // default from date // to : '1/18/2014', // default to date changeMonth : true, changeYear : true }); } } } }); });</script> </head> <body> <div id="banner"> <h1>table<em>sorter</em></h1> <h2>Custom Filter Widget Formatter (jQuery UI widgets)</h2> <h3>Flexible client-side table sorting</h3> <a href="index.html">Back to documentation</a> </div> <div id="main"> <p></p> <br> <div class="accordion"> <h3><a href="#">Notes</a></h3> <div> <ul> <li>As of tablesorter version 2.9+, this widget can no longer be applied to versions of tablesorter prior to version 2.8.</li> <li>This page shows you how to add a few <strong>jQuery UI widgets</strong> to interact with the filter widget using the <code>filter_formatter</code> option.</li> <li>Custom filter widget option <code>filter_formatter</code> was added in version 2.7.7.</li> <li>jQuery v1.4.3+ required.</li> </ul> </div> <h3><a href="#"><strong>jQuery UI Single Slider</strong> ("Rank" and "Age" columns)</a></h3> <div> <ul> <li>This example shows how you can add a jQuery UI slider to filter column content.</li> <li>The <code>filter_formatter</code> function provided in the extra "jquery.tablesorter.widgets-filter-formatter.js" file is used to add this custom control within the filter row.</li> <li>Make sure to include all values within the selected range, otherwise rows outside of this range will be forever hidden.</li> <li>Add the following code to apply a slider to filter a column:<pre class="prettyprint lang-javascript">$(function() { $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { 0 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSlider( $cell, indx, { // add any of the jQuery UI Slider options here (http://api.jqueryui.com/slider/) value: 0, // starting value min: 0, // minimum value max: 100, // maximum value delayed: true, // delay search (set by filter_searchDelay) valueToHeader: false, // add current slider value to the header cell exactMatch: true, // exact (true) or match (false) allText: 'all', // text shown when the slider is at the minimum value compare: '' // any comparison would override the exactMatch option }); }, 1 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSlider( $cell, indx, { // add any of the jQuery UI Slider options here (http://api.jqueryui.com/slider/) value: 0, // starting value min: 0, // minimum value max: 100, // maximum value delayed: true, // delay search (set by filter_searchDelay) valueToHeader: false, // add current slider value to the header cell exactMatch: false, // exact (true) or match (false) allText: 'all', // text shown when slider is at the minimum value; ignored when compare has a value compare: '>=' // show values >= selected value; overrides exactMatch }); } } } }); });</pre></li> <li>The tooltip above the slider is added using pure css, which is included in the "filter.formatter.css" file, but it won't work in IE7 and older. But, you set the <code>valueToHeader</code> option to <code>true</code> to add the slider value to the header cell above the filter.</li> <li>Another option named <code>exactMatch</code> was added to allow exact or general matching of column content.</li> <li>Notice that the left-most value, zero in this case, will clear the column filter to allow a method to show all column content. You can modify the "all" text using the <code>allText</code> option.</li> <li>A search delay was added in v2.7.11 (time set by <code>filter_searchDelay</code> option). It can be disabled by setting the <code>delayed</code> option to <code>false</code>.</li> <li>In <span class="version">v2.10.1</span> the <code>compare</code> option was added. This allows comparing the slider's value to the column value. The slider in the Age column is selecting values greater than or equal to itself.</li> </ul> </div> <h3><a href="#"><strong>jQuery UI Range Slider</strong> ("Total" column)</a></h3> <div> <ul> <li>This example shows how you can add a jQuery UI range slider to filter column content.</li> <li>The <code>filter_formatter</code> function provided in the extra "jquery.tablesorter.widgets-filter-formatter.js" file is used to add this custom control within the filter row.</li> <li>Make sure to include all values within the selected range, otherwise rows outside of this range will be forever hidden.</li> <li>The range slider is actually the same as the single slider described above, but was built to handle a range of values.</li> <li>Add the following code to apply a range slider to filter a column:<pre class="prettyprint lang-javascript">$(function() { $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { // Total column 2 : function($cell, indx){ return $.tablesorter.filterFormatter.uiRange( $cell, indx, { // add any of the jQuery UI Slider options (for range selection) here (http://api.jqueryui.com/slider/) values: [1, 160], // starting range min: 1, // minimum value max: 160, // maximum value delayed: true, // delay search (set by filter_searchDelay) exactMatch: true, // exact (true) or match (false) valueToHeader: false, // add current slider value to the header cell }); } } } }); });</pre></li> <li>The tooltip above the slider is added using pure css, which is included in the "filter.formatter.css" file, but it won't work in IE7 and older. But, you set the <code>valueToHeader</code> option to <code>true</code> to add the slider value to the header cell above the filter.</li> <li>Another option named <code>exactMatch</code> was added to allow exact or general matching of column content.</li> <li>A search delay was added in v2.7.11 (time set by <code>filter_searchDelay</code> option). It can be disabled by setting the <code>delayed</code> option to <code>false</code>.</li> </ul> </div> <h3><a href="#"><strong>jQuery UI Spinner</strong> ("Discount" column)</a></h3> <div> <ul> <li>This example shows how you can add a jQuery UI spinner to filter column content.</li> <li>The <code>filter_formatter</code> function provided in the extra "jquery.tablesorter.widgets-filter-formatter.js" file is used to add this custom control within the filter row.</li> <li>Add the following code to apply a spinner to filter a column:<pre class="prettyprint lang-javascript">$(function() { $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { 3 : function($cell, indx){ return $.tablesorter.filterFormatter.uiSpinner( $cell, indx, { // add any of the jQuery UI Spinner options here (http://api.jqueryui.com/spinner/) min : 0, max : 45, value: 1, step: 1, delayed: true, addToggle: true, exactMatch: true, compare : '' }); } } } }); });</pre></li> <li>This is the only jQuery UI widget that includes a toggle button. The toggle button is added by default, but if you don't want it, set the <code>addToggle</code> option to <code>false</code>. Without the toggle button, the filter is always active.</li> <li>Another option named <code>exactMatch</code> was added to allow exact or general matching of column content.</li> <li>A search delay was added in v2.7.11 (time set by <code>filter_searchDelay</code> option). It can be disabled by setting the <code>delayed</code> option to <code>false</code>.</li> </ul> </div> <h3><a href="#"><strong>jQuery UI Datepicker Comparison</strong> ("Date (one input)" column)</a></h3> <div> <ul> <li>This example shows how you can add a jQuery UI Datepicker to compare to filter column content.</li> <li>The <code>filter_formatter</code> function provided in the extra "jquery.tablesorter.widgets-filter-formatter.js" file is used to add this custom control within the filter row.</li> <li>This code follows the <a class="external" href="http://jqueryui.com/datepicker/#default">default functionality</a> example from the jQuery UI docs.</li> <li>Add the following code to apply a datepicker comparison selector to the filter row:<pre class="prettyprint lang-javascript">$(function() { $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { 4 : function($cell, indx){ return $.tablesorter.filterFormatter.uiDateCompare( $cell, indx, { // add any of the jQuery UI Datepicker options here (http://api.jqueryui.com/datepicker/) // defaultDate : '1/1/2014', // default date cellText : 'dates >=', // text added before the input changeMonth : true, changeYear : true, compare : '>=' }); } } } }); });</pre></li> <li>There is one issue with this comparison script, and that is with dates that contain a time: <ul> <li>Table data that contains dates with times will be parsed into values that include time.</li> <li>So if the <code>compare</code> option is set to <code>=</code>, it may not show any filtered table rows as none match that date at midnight. To fix this, either remove times from the table data, use a column parser that ignores the time, or use the Datepicker range selector and set the "from" input to the desired day and the "to" input to be the next day (at midnight).</li> <li><del>Using a <code>compare</code> of <code>&lt;=</code> will only show filtered dates from the selected day <em>at midnight</em> with earlier dates; i.e. a cell with the selected date but a time set to noon will not be visible</del>. As of <span class="version">v2.10/8</span>, the comparison of dates less than the selected date, now adds a time of 11:59:59 so it will include times within the selected date.</li> </ul> </li> </ul> </div> <h3><a href="#"><strong>jQuery UI Datepicker Range Selector</strong> ("Date (two inputs)" column)</a></h3> <div> <ul> <li>This example shows how you can add a jQuery UI Datepicker range to filter column content.</li> <li>The <code>filter_formatter</code> function provided in the extra "jquery.tablesorter.widgets-filter-formatter.js" file is used to add this custom control within the filter row.</li> <li>This code follows the <a class="external" href="http://jqueryui.com/datepicker/#date-range">date range</a> example from the jQuery UI docs.</li> <li>Updated two input functions so that if the "to" input is empty, all dates greater than the "from" date are shown. If the "from" input is empty, all dates less than the "to" input date are shown (<span class="version updated">v2.10.1</span>).</li> <li>Add the following code to apply a datepicker range selector to the filter row:<pre class="prettyprint lang-javascript">$(function() { $("table").tablesorter({ theme: 'blue', // hidden filter input/selects will resize the columns, so try to minimize the change widthFixed : true, // initialize zebra striping and filter widgets widgets: ["zebra", "filter"], widgetOptions : { // jQuery selector string of an element used to reset the filters filter_reset : 'button.reset', // add custom selector elements to the filter row filter_formatter : { 6 : function($cell, indx){ return $.tablesorter.filterFormatter.uiDatepicker( $cell, indx, { // add any of the jQuery UI Datepicker options here (http://api.jqueryui.com/datepicker/) // from : '8/1/2013', // starting date // to : '1/18/2014', // ending date textFrom: 'from', // "from" label text textTo: 'to', // "to" label text changeMonth: true, changeYear : true }); } } } }); });</pre></li> <li>Note that the datepicker options are slightly different from the default datepicker options: <ul> <li>Instead of using the <code>defaultDate</code> option of the datepicker widget, it has a <code>from</code> and <code>to</code> option to fullfill that purpose.</li> <li>The options added to this function will be applied to both the from and to datepicker inputs.</li> <li>As of <span class="version">v2.10.8</span>, the comparison of dates less than the selected "to" date, now adds a time of 11:59:59 so it will include times within the selected dates.</li> </ul> </li> </ul> </div> <h3><a href="#"><strong>Custom Filter Formatter Function Information</strong></a></h3> <div> If you want to write your own custom filter formatter function, there are certain requirements that should be met: <ul> <li>Required input element: <ul> <li>If your selector isn't an input (e.g. jQuery UI Slider), then you'll need to return an input of type hidden which gets updated by the selector with the filter query for the column. <pre class="prettyprint lang-javascript">filter_formatter : { 0 : function($cell, indx) { var $input = $('&lt;input type="hidden"&gt;').appendTo($cell); // add your selector code here return $input; } }</pre></li> <li>If the input contains a value that doesn't match a standard filter syntax, then you'll need to return an input of type hidden with the correct format.</li> <li>This returned input element should to be attached to the <code>$cell</code>.</li> <li>The returned input should have a "search" event triggered upon it after being updated.</li> </ul> </li> <li>Some method should be added to show the user the current value of the selector - update a data attribute for css3 tooltips, or update the header cell.</li> <li>A reset function needs to also be included; bind to the <code>filterReset</code> event and clear out or disable your custom selector when triggered. <pre class="prettyprint lang-javascript">$cell.closest('table').bind('filterReset', function(){ /* update the input here */ });</pre> </li> <li>If your selector needs a parsed value to work with, add the <code>filter-parsed</code> class name to the header cell above the filter, use this code to do that: <pre class="prettyprint lang-javascript">$cell.closest('thead').find('th[data-column=' + indx + ']').addClass('filter-parsed');</pre> </li> <li>Since, by default, the filter only matches cell content, a <code>1</code> in the filter will show all rows with a one no matter where it is located. So, if you need an exact match, add an equal sign to the end of the value (<code>1=</code>). This forces the filter to exactly match the value in the search input.</li> <li>To include a search delay, trigger the search on the hidden input and pass a boolean. If <code>true</code> or undefined, the search will be delayed and not delayed if <code>false</code>. Delay time set by <code>filter_searchDelay</code> option). <pre class="prettyprint lang-javascript">$input.val( newVal ).trigger('search', false); // no search delay</pre> </li> </ul> </div> </div> <h1>Demo</h1> <button type="button" class="reset">Reset Search</button> <div id="demo"><table class="tablesorter"> <thead> <tr> <th>Rank (exact)</th> <th>Age (greater than)</th> <th>Total (range)</th> <th>Discount (exact)</th> <th data-placeholder="Try 1/20/2013">Date (one input; greater than)</th> <th>Date (two inputs; range)</th> </tr> </thead> <tbody> <tr><td>1</td><td>25</td><td>$5.95</td><td>22%</td><td>Jun 26, 2013 7:22 AM</td><td>Jun 26, 2013 7:22 AM</td></tr> <tr><td>11</td><td>12</td><td>$82.99</td><td>5%</td><td>Aug 21, 2013 12:21 PM</td><td>Aug 21, 2013 12:21 PM</td></tr> <tr><td>12</td><td>51</td><td>$99.29</td><td>18%</td><td>Oct 13, 2013 1:15 PM</td><td>Oct 13, 2013 1:15 PM</td></tr> <tr><td>51</td><td>28</td><td>$9.99</td><td>20%</td><td>Jul 6, 2013 8:14 AM</td><td>Jul 6, 2013 8:14 AM</td></tr> <tr><td>21</td><td>33</td><td>$19.99</td><td>25%</td><td>Dec 10, 2012 5:14 AM</td><td>Dec 10, 2012 5:14 AM</td></tr> <tr><td>013</td><td>18</td><td>$65.89</td><td>45%</td><td>Jan 12, 2013 11:14 AM</td><td>Jan 12, 2013 11:14 AM</td></tr> <tr><td>005</td><td>45</td><td>$153.19</td><td>45%</td><td>Jan 18, 2014 9:12 AM</td><td>Jan 18, 2014 9:12 AM</td></tr> <tr><td>10</td><td>3</td><td>$5.29</td><td>4%</td><td>Jan 8, 2013 5:11 PM</td><td>Jan 8, 2013 5:11 PM</td></tr> <tr><td>16</td><td>24</td><td>$14.19</td><td>14%</td><td>Jan 14, 2014 11:23 AM</td><td>Jan 14, 2014 11:23 AM</td></tr> <tr><td>66</td><td>22</td><td>$13.19</td><td>11%</td><td>Jan 18, 2013 9:12 AM</td><td>Jan 18, 2013 9:12 AM</td></tr> <tr><td>100</td><td>18</td><td>$55.20</td><td>15%</td><td>Feb 12, 2013 7:23 PM</td><td>Feb 12, 2013 7:23 PM</td></tr> <tr><td>55</td><td>65</td><td>$123.00</td><td>32%</td><td>Jan 20, 2014 1:12 PM</td><td>Jan 20, 2014 1:12 PM</td></tr> <tr><td>9</td><td>25</td><td>$22.09</td><td>17%</td><td>Jun 11, 2013 10:55 AM</td><td>Jun 11, 2013 10:55 AM</td></tr> </tbody> </table></div> <h1>Page Header</h1> <div> <pre class="prettyprint lang-html">&lt;!-- jQuery UI for range slider --&gt; &lt;link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/cupertino/jquery-ui.css"&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;!-- tablesorter plugin --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;../css/theme.blue.css&quot;&gt; &lt;script src=&quot;../js/jquery.tablesorter.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;../js/jquery.tablesorter.widgets.js&quot;&gt;&lt;/script&gt; &lt;!-- filter formatter code --&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;../css/filter.formatter.css&quot;&gt; &lt;script src=&quot;../js/jquery.tablesorter.widgets-filter-formatter.js&quot;&gt;&lt;/script&gt;</pre> </div> <h1>Javascript</h1> <div id="javascript"> <pre class="prettyprint lang-javascript"></pre> </div> <h1>HTML</h1> <div id="html"> <pre class="prettyprint lang-html"></pre> </div> <div class="next-up"> <hr /> Next up: <a href="example-widget-filter-formatter-2.html">jQuery custom filter widget formatter (HTML5 Elements) &rsaquo;&rsaquo;</a> </div> </div> </body> </html>
/* arch/arm/mach-msm/include/mach/memory.h * * Copyright (C) 2007 Google, Inc. * Copyright (c) 2009-2013, The Linux Foundation. All rights reserved. * * 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. * */ #ifndef __ASM_ARCH_MEMORY_H #define __ASM_ARCH_MEMORY_H #include <linux/types.h> /* physical offset of RAM */ #define PLAT_PHYS_OFFSET UL(CONFIG_PHYS_OFFSET) #if defined(CONFIG_KEXEC_HARDBOOT) #if defined(CONFIG_MACH_APQ8064_FLO) #define KEXEC_HB_PAGE_ADDR UL(0x88C00000) #elif defined(CONFIG_MACH_APQ8064_MAKO) #define KEXEC_HB_PAGE_ADDR UL(0x88600000) #elif defined(CONFIG_ARCH_MSM8226) #define KEXEC_HB_PAGE_ADDR UL(0x3e9e0000) /*#define KEXEC_HB_KERNEL_LOC UL(0x5000000)*/ #else #error "Adress for kexec hardboot page not defined" #endif #endif #define MAX_PHYSMEM_BITS 32 #define SECTION_SIZE_BITS 28 /* Maximum number of Memory Regions * The largest system can have 4 memory banks, each divided into 8 regions */ #define MAX_NR_REGIONS 32 /* The number of regions each memory bank is divided into */ #define NR_REGIONS_PER_BANK 8 /* Certain configurations of MSM7x30 have multiple memory banks. * One or more of these banks can contain holes in the memory map as well. * These macros define appropriate conversion routines between the physical * and virtual address domains for supporting these configurations using * SPARSEMEM and a 3G/1G VM split. */ #if defined(CONFIG_ARCH_MSM7X30) #define EBI0_PHYS_OFFSET PHYS_OFFSET #define EBI0_PAGE_OFFSET PAGE_OFFSET #define EBI0_SIZE 0x10000000 #ifndef __ASSEMBLY__ extern unsigned long ebi1_phys_offset; #define EBI1_PHYS_OFFSET (ebi1_phys_offset) #define EBI1_PAGE_OFFSET (EBI0_PAGE_OFFSET + EBI0_SIZE) #if (defined(CONFIG_SPARSEMEM) && defined(CONFIG_VMSPLIT_3G)) #define __phys_to_virt(phys) \ ((phys) >= EBI1_PHYS_OFFSET ? \ (phys) - EBI1_PHYS_OFFSET + EBI1_PAGE_OFFSET : \ (phys) - EBI0_PHYS_OFFSET + EBI0_PAGE_OFFSET) #define __virt_to_phys(virt) \ ((virt) >= EBI1_PAGE_OFFSET ? \ (virt) - EBI1_PAGE_OFFSET + EBI1_PHYS_OFFSET : \ (virt) - EBI0_PAGE_OFFSET + EBI0_PHYS_OFFSET) #endif #endif #endif #ifndef __ASSEMBLY__ void *allocate_contiguous_ebi(unsigned long, unsigned long, int); phys_addr_t allocate_contiguous_ebi_nomap(unsigned long, unsigned long); void clean_and_invalidate_caches(unsigned long, unsigned long, unsigned long); void clean_caches(unsigned long, unsigned long, unsigned long); void invalidate_caches(unsigned long, unsigned long, unsigned long); int msm_get_memory_type_from_name(const char *memtype_name); unsigned long get_ddr_size(void); #if defined(CONFIG_ARCH_MSM_ARM11) || defined(CONFIG_ARCH_MSM_CORTEX_A5) void write_to_strongly_ordered_memory(void); void map_page_strongly_ordered(void); #endif #ifdef CONFIG_CACHE_L2X0 extern void l2x0_cache_sync(void); #define finish_arch_switch(prev) do { l2x0_cache_sync(); } while (0) #endif #if defined(CONFIG_ARCH_MSM8X60) || defined(CONFIG_ARCH_MSM8960) extern void store_ttbr0(void); #define finish_arch_switch(prev) do { store_ttbr0(); } while (0) #endif #define MAX_HOLE_ADDRESS (PHYS_OFFSET + 0x10000000) extern phys_addr_t memory_hole_offset; extern phys_addr_t memory_hole_start; extern phys_addr_t memory_hole_end; extern unsigned long memory_hole_align; extern unsigned long virtual_hole_start; extern unsigned long virtual_hole_end; #ifdef CONFIG_DONT_MAP_HOLE_AFTER_MEMBANK0 void find_memory_hole(void); #define MEM_HOLE_END_PHYS_OFFSET (memory_hole_end) #define MEM_HOLE_PAGE_OFFSET (PAGE_OFFSET + memory_hole_offset + \ memory_hole_align) #define __phys_to_virt(phys) \ ({ \ unsigned long __phys = (unsigned long)phys; \ ((MEM_HOLE_END_PHYS_OFFSET && \ ((__phys) >= MEM_HOLE_END_PHYS_OFFSET)) ? \ (__phys) - MEM_HOLE_END_PHYS_OFFSET + MEM_HOLE_PAGE_OFFSET : \ (__phys) - PHYS_OFFSET + PAGE_OFFSET); \ }) #define __virt_to_phys(virt) \ ({ \ unsigned long __virt = (unsigned long)virt; \ ((MEM_HOLE_END_PHYS_OFFSET && ((__virt) >= MEM_HOLE_PAGE_OFFSET)) ? \ (__virt) - MEM_HOLE_PAGE_OFFSET + MEM_HOLE_END_PHYS_OFFSET : \ (__virt) - PAGE_OFFSET + PHYS_OFFSET); \ }) #endif /* * Need a temporary unique variable that no one will ever see to * hold the compat string. Line number gives this easily. * Need another layer of indirection to get __LINE__ to expand * properly as opposed to appending and ending up with * __compat___LINE__ */ #define __CONCAT(a, b) ___CONCAT(a, b) #define ___CONCAT(a, b) a ## b #define EXPORT_COMPAT(com) \ static char *__CONCAT(__compat_, __LINE__) __used \ __attribute((__section__(".exportcompat.init"))) = com extern char *__compat_exports_start[]; extern char *__compat_exports_end[]; #endif #if defined CONFIG_ARCH_MSM_SCORPION || defined CONFIG_ARCH_MSM_KRAIT #define arch_has_speculative_dfetch() 1 #endif #endif /* these correspond to values known by the modem */ #define MEMORY_DEEP_POWERDOWN 0 #define MEMORY_SELF_REFRESH 1 #define MEMORY_ACTIVE 2 #define NPA_MEMORY_NODE_NAME "/mem/apps/ddr_dpd" #ifndef CONFIG_ARCH_MSM7X27 #define CONSISTENT_DMA_SIZE (SZ_1M * 14) #endif
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ContentContentPaste = function ContentContentPaste(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M19 2h-4.18C14.4.84 13.3 0 12 0c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm7 18H5V4h2v3h10V4h2v16z' }) ); }; ContentContentPaste = (0, _pure2.default)(ContentContentPaste); ContentContentPaste.displayName = 'ContentContentPaste'; ContentContentPaste.muiName = 'SvgIcon'; exports.default = ContentContentPaste;
<!-- This file is auto-generated from texturefiltering_test_generator.py DO NOT EDIT! --> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>WebGL Texture Filtering Tests</title> <link rel="stylesheet" href="../../../../resources/js-test-style.css"/> <script src=/resources/testharness.js></script> <script src=/resources/testharnessreport.js></script> <script src="../../../../js/js-test-pre.js"></script> <script src="../../../../js/webgl-test-utils.js"></script> <script src="../../../../closure-library/closure/goog/base.js"></script> <script src="../../../deqp-deps.js"></script> <script>goog.require('functional.gles3.es3fTextureFilteringTests');</script> </head> <body> <div id="description"></div> <div id="console"></div> <canvas id="canvas" width="300" height="300"> </canvas> <script> var wtu = WebGLTestUtils; var gl = wtu.create3DContext('canvas', null, 2); functional.gles3.es3fTextureFilteringTests.run(gl, [3, 4]); </script> </body> </html>
{{+partials.standard_extensions_article article:intros.background_pages}}
cask "pdfelement-express" do version "1.2.1,1441" sha256 :no_check url "https://download.wondershare.com/cbs_down/mac-pdfelement-express_full4133.dmg" appcast "https://cbs.wondershare.com/go.php?m=upgrade_info&pid=4133" name "PDFelement Express" homepage "https://pdf.wondershare.com/pdfelement-express-mac.html" depends_on macos: ">= :sierra" app "PDFelement Express.app" end
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */ /* vim: set ts=2 et sw=2 tw=80: */ /************************************************************* * * MathJax/localization/vi/MathML.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("vi","MathML",{ version: "2.5.0", isLoaded: true, strings: { BadMglyph: "mglyph h\u1ECFng: %1", BadMglyphFont: "Ph\u00F4ng ch\u1EEF h\u1ECFng: %1", MathPlayer: "MathJax kh\u00F4ng th\u1EC3 thi\u1EBFt l\u1EADp MathPlayer.\n\nN\u1EBFu MathPlayer ch\u01B0a \u0111\u01B0\u1EE3c c\u00E0i \u0111\u1EB7t, b\u1EA1n c\u1EA7n ph\u1EA3i c\u00E0i \u0111\u1EB7t n\u00F3 tr\u01B0\u1EDBc ti\u00EAn.\nN\u1EBFu kh\u00F4ng, c\u00E1c t\u00F9y ch\u1ECDn b\u1EA3o m\u1EADt c\u1EE7a b\u1EA1n c\u00F3 th\u1EC3 ng\u0103n tr\u1EDF c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m c\u00E1c h\u1ED9p \u201CCh\u1EA1y \u0111i\u1EC1u khi\u1EC3n ActiveX\u201D v\u00E0 \u201CH\u00E0nh vi nh\u1ECB ph\u00E2n v\u00E0 k\u1ECBch b\u1EA3n\u201D.\n\nHi\u1EC7n t\u1EA1i b\u1EA1n s\u1EBD g\u1EB7p c\u00E1c th\u00F4ng b\u00E1o l\u1ED7i thay v\u00EC to\u00E1n h\u1ECDc \u0111\u01B0\u1EE3c k\u1EBFt xu\u1EA5t.", CantCreateXMLParser: "MathJax kh\u00F4ng th\u1EC3 t\u1EA1o ra b\u1ED9 ph\u00E2n t\u00EDch XML cho MathML. H\u00E3y ch\u1ECDn T\u00F9y ch\u1ECDn Internet trong tr\u00ECnh \u0111\u01A1n C\u00F4ng c\u1EE5, qua th\u1EBB B\u1EA3o m\u1EADt, v\u00E0 b\u1EA5m n\u00FAt M\u1EE9c t\u00F9y ch\u1EC9nh. Ki\u1EC3m h\u1ED9p \u201CScript c\u00E1c \u0111i\u1EC1u khi\u1EC3n ActiveX \u0111\u01B0\u1EE3c \u0111\u00E1nh d\u1EA5u l\u00E0 an to\u00E0n\u201D.\n\nMathJax s\u1EBD kh\u00F4ng th\u1EC3 x\u1EED l\u00FD c\u00E1c ph\u01B0\u01A1ng tr\u00ECnh MathML.", UnknownNodeType: "Ki\u1EC3u n\u00FAt kh\u00F4ng r\u00F5: %1", UnexpectedTextNode: "N\u00FAt v\u0103n b\u1EA3n b\u1EA5t ng\u1EEB: %1", ErrorParsingMathML: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML", ParsingError: "L\u1ED7i khi ph\u00E2n t\u00EDch MathML: %1", MathMLSingleElement: "MathML ph\u1EA3i ch\u1EC9 c\u00F3 m\u1ED9t ph\u1EA7n t\u1EED g\u1ED1c", MathMLRootElement: "Ph\u1EA7n t\u1EED g\u1ED1c c\u1EE7a MathML ph\u1EA3i l\u00E0 \u003Cmath\u003E, ch\u1EE9 kh\u00F4ng ph\u1EA3i %1" } }); MathJax.Ajax.loadComplete("[MathJax]/localization/vi/MathML.js");
<?php function mce_put_file( $path, $content ) { if ( function_exists('file_put_contents') ) return @file_put_contents( $path, $content ); $newfile = false; $fp = @fopen( $path, 'wb' ); if ($fp) { $newfile = fwrite( $fp, $content ); fclose($fp); } return $newfile; } // escape text only if it needs translating function mce_escape($text) { global $language; if ( 'en' == $language ) return $text; else return esc_js($text); } $lang = 'tinyMCE.addI18n({' . $language . ':{ common:{ edit_confirm:"' . mce_escape( __('Do you want to use the WYSIWYG mode for this textarea?') ) . '", apply:"' . mce_escape( __('Apply') ) . '", insert:"' . mce_escape( __('Insert') ) . '", update:"' . mce_escape( __('Update') ) . '", cancel:"' . mce_escape( __('Cancel') ) . '", close:"' . mce_escape( __('Close') ) . '", browse:"' . mce_escape( __('Browse') ) . '", class_name:"' . mce_escape( __('Class') ) . '", not_set:"' . mce_escape( __('-- Not set --') ) . '", clipboard_msg:"' . mce_escape( __('Copy/Cut/Paste is not available in Mozilla and Firefox.') ) . '", clipboard_no_support:"' . mce_escape( __('Currently not supported by your browser, use keyboard shortcuts instead.') ) . '", popup_blocked:"' . mce_escape( __('Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.') ) . '", invalid_data:"' . mce_escape( __('Error: Invalid values entered, these are marked in red.') ) . '", more_colors:"' . mce_escape( __('More colors') ) . '" }, contextmenu:{ align:"' . mce_escape( __('Alignment') ) . '", left:"' . mce_escape( __('Left') ) . '", center:"' . mce_escape( __('Center') ) . '", right:"' . mce_escape( __('Right') ) . '", full:"' . mce_escape( __('Full') ) . '" }, insertdatetime:{ date_fmt:"' . mce_escape( __('%Y-%m-%d') ) . '", time_fmt:"' . mce_escape( __('%H:%M:%S') ) . '", insertdate_desc:"' . mce_escape( __('Insert date') ) . '", inserttime_desc:"' . mce_escape( __('Insert time') ) . '", months_long:"' . mce_escape( __('January').','.__('February').','.__('March').','.__('April').','.__('May').','.__('June').','.__('July').','.__('August').','.__('September').','.__('October').','.__('November').','.__('December') ) . '", months_short:"' . mce_escape( __('Jan_January_abbreviation').','.__('Feb_February_abbreviation').','.__('Mar_March_abbreviation').','.__('Apr_April_abbreviation').','.__('May_May_abbreviation').','.__('Jun_June_abbreviation').','.__('Jul_July_abbreviation').','.__('Aug_August_abbreviation').','.__('Sep_September_abbreviation').','.__('Oct_October_abbreviation').','.__('Nov_November_abbreviation').','.__('Dec_December_abbreviation') ) . '", day_long:"' . mce_escape( __('Sunday').','.__('Monday').','.__('Tuesday').','.__('Wednesday').','.__('Thursday').','.__('Friday').','.__('Saturday') ) . '", day_short:"' . mce_escape( __('Sun').','.__('Mon').','.__('Tue').','.__('Wed').','.__('Thu').','.__('Fri').','.__('Sat') ) . '" }, print:{ print_desc:"' . mce_escape( __('Print') ) . '" }, preview:{ preview_desc:"' . mce_escape( __('Preview') ) . '" }, directionality:{ ltr_desc:"' . mce_escape( __('Direction left to right') ) . '", rtl_desc:"' . mce_escape( __('Direction right to left') ) . '" }, layer:{ insertlayer_desc:"' . mce_escape( __('Insert new layer') ) . '", forward_desc:"' . mce_escape( __('Move forward') ) . '", backward_desc:"' . mce_escape( __('Move backward') ) . '", absolute_desc:"' . mce_escape( __('Toggle absolute positioning') ) . '", content:"' . mce_escape( __('New layer...') ) . '" }, save:{ save_desc:"' . mce_escape( __('Save') ) . '", cancel_desc:"' . mce_escape( __('Cancel all changes') ) . '" }, nonbreaking:{ nonbreaking_desc:"' . mce_escape( __('Insert non-breaking space character') ) . '" }, iespell:{ iespell_desc:"' . mce_escape( __('Run spell checking') ) . '", download:"' . mce_escape( __('ieSpell not detected. Do you want to install it now?') ) . '" }, advhr:{ advhr_desc:"' . mce_escape( __('Horizontale rule') ) . '" }, emotions:{ emotions_desc:"' . mce_escape( __('Emotions') ) . '" }, searchreplace:{ search_desc:"' . mce_escape( __('Find') ) . '", replace_desc:"' . mce_escape( __('Find/Replace') ) . '" }, advimage:{ image_desc:"' . mce_escape( __('Insert/edit image') ) . '" }, advlink:{ link_desc:"' . mce_escape( __('Insert/edit link') ) . '" }, xhtmlxtras:{ cite_desc:"' . mce_escape( __('Citation') ) . '", abbr_desc:"' . mce_escape( __('Abbreviation') ) . '", acronym_desc:"' . mce_escape( __('Acronym') ) . '", del_desc:"' . mce_escape( __('Deletion') ) . '", ins_desc:"' . mce_escape( __('Insertion') ) . '", attribs_desc:"' . mce_escape( __('Insert/Edit Attributes') ) . '" }, style:{ desc:"' . mce_escape( __('Edit CSS Style') ) . '" }, paste:{ paste_text_desc:"' . mce_escape( __('Paste as Plain Text') ) . '", paste_word_desc:"' . mce_escape( __('Paste from Word') ) . '", selectall_desc:"' . mce_escape( __('Select All') ) . '" }, paste_dlg:{ text_title:"' . mce_escape( __('Use CTRL+V on your keyboard to paste the text into the window.') ) . '", text_linebreaks:"' . mce_escape( __('Keep linebreaks') ) . '", word_title:"' . mce_escape( __('Use CTRL+V on your keyboard to paste the text into the window.') ) . '" }, table:{ desc:"' . mce_escape( __('Inserts a new table') ) . '", row_before_desc:"' . mce_escape( __('Insert row before') ) . '", row_after_desc:"' . mce_escape( __('Insert row after') ) . '", delete_row_desc:"' . mce_escape( __('Delete row') ) . '", col_before_desc:"' . mce_escape( __('Insert column before') ) . '", col_after_desc:"' . mce_escape( __('Insert column after') ) . '", delete_col_desc:"' . mce_escape( __('Remove column') ) . '", split_cells_desc:"' . mce_escape( __('Split merged table cells') ) . '", merge_cells_desc:"' . mce_escape( __('Merge table cells') ) . '", row_desc:"' . mce_escape( __('Table row properties') ) . '", cell_desc:"' . mce_escape( __('Table cell properties') ) . '", props_desc:"' . mce_escape( __('Table properties') ) . '", paste_row_before_desc:"' . mce_escape( __('Paste table row before') ) . '", paste_row_after_desc:"' . mce_escape( __('Paste table row after') ) . '", cut_row_desc:"' . mce_escape( __('Cut table row') ) . '", copy_row_desc:"' . mce_escape( __('Copy table row') ) . '", del:"' . mce_escape( __('Delete table') ) . '", row:"' . mce_escape( __('Row') ) . '", col:"' . mce_escape( __('Column') ) . '", cell:"' . mce_escape( __('Cell') ) . '" }, autosave:{ unload_msg:"' . mce_escape( __('The changes you made will be lost if you navigate away from this page.') ) . '" }, fullscreen:{ desc:"' . mce_escape( __('Toggle fullscreen mode') ) . ' (Alt+Shift+G)" }, media:{ desc:"' . mce_escape( __('Insert / edit embedded media') ) . '", delta_width:"' . /* translators: Extra width for the media popup in pixels */ mce_escape( _x('0', 'media popup width') ) . '", delta_height:"' . /* translators: Extra height for the media popup in pixels */ mce_escape( _x('0', 'media popup height') ) . '", edit:"' . mce_escape( __('Edit embedded media') ) . '" }, fullpage:{ desc:"' . mce_escape( __('Document properties') ) . '" }, template:{ desc:"' . mce_escape( __('Insert predefined template content') ) . '" }, visualchars:{ desc:"' . mce_escape( __('Visual control characters on/off.') ) . '" }, spellchecker:{ desc:"' . mce_escape( __('Toggle spellchecker') ) . ' (Alt+Shift+N)", menu:"' . mce_escape( __('Spellchecker settings') ) . '", ignore_word:"' . mce_escape( __('Ignore word') ) . '", ignore_words:"' . mce_escape( __('Ignore all') ) . '", langs:"' . mce_escape( __('Languages') ) . '", wait:"' . mce_escape( __('Please wait...') ) . '", sug:"' . mce_escape( __('Suggestions') ) . '", no_sug:"' . mce_escape( __('No suggestions') ) . '", no_mpell:"' . mce_escape( __('No misspellings found.') ) . '" }, pagebreak:{ desc:"' . mce_escape( __('Insert page break.') ) . '" }}}); tinyMCE.addI18n("' . $language . '.advanced",{ style_select:"' . mce_escape( /* translators: TinyMCE font styles */ _x('Styles', 'TinyMCE font styles') ) . '", font_size:"' . mce_escape( __('Font size') ) . '", fontdefault:"' . mce_escape( __('Font family') ) . '", block:"' . mce_escape( __('Format') ) . '", paragraph:"' . mce_escape( __('Paragraph') ) . '", div:"' . mce_escape( __('Div') ) . '", address:"' . mce_escape( __('Address') ) . '", pre:"' . mce_escape( __('Preformatted') ) . '", h1:"' . mce_escape( __('Heading 1') ) . '", h2:"' . mce_escape( __('Heading 2') ) . '", h3:"' . mce_escape( __('Heading 3') ) . '", h4:"' . mce_escape( __('Heading 4') ) . '", h5:"' . mce_escape( __('Heading 5') ) . '", h6:"' . mce_escape( __('Heading 6') ) . '", blockquote:"' . mce_escape( __('Blockquote') ) . '", code:"' . mce_escape( __('Code') ) . '", samp:"' . mce_escape( __('Code sample') ) . '", dt:"' . mce_escape( __('Definition term ') ) . '", dd:"' . mce_escape( __('Definition description') ) . '", bold_desc:"' . mce_escape( __('Bold') ) . ' (Ctrl / Alt+Shift + B)", italic_desc:"' . mce_escape( __('Italic') ) . ' (Ctrl / Alt+Shift + I)", underline_desc:"' . mce_escape( __('Underline') ) . '", striketrough_desc:"' . mce_escape( __('Strikethrough') ) . ' (Alt+Shift+D)", justifyleft_desc:"' . mce_escape( __('Align left') ) . ' (Alt+Shift+L)", justifycenter_desc:"' . mce_escape( __('Align center') ) . ' (Alt+Shift+C)", justifyright_desc:"' . mce_escape( __('Align right') ) . ' (Alt+Shift+R)", justifyfull_desc:"' . mce_escape( __('Align full') ) . ' (Alt+Shift+J)", bullist_desc:"' . mce_escape( __('Unordered list') ) . ' (Alt+Shift+U)", numlist_desc:"' . mce_escape( __('Ordered list') ) . ' (Alt+Shift+O)", outdent_desc:"' . mce_escape( __('Outdent') ) . '", indent_desc:"' . mce_escape( __('Indent') ) . '", undo_desc:"' . mce_escape( __('Undo') ) . ' (Ctrl+Z)", redo_desc:"' . mce_escape( __('Redo') ) . ' (Ctrl+Y)", link_desc:"' . mce_escape( __('Insert/edit link') ) . ' (Alt+Shift+A)", link_delta_width:"' . /* translators: Extra width for the link popup in pixels */ mce_escape( _x('0', 'link popup width') ) . '", link_delta_height:"' . /* translators: Extra height for the link popup in pixels */ mce_escape( _x('0', 'link popup height') ) . '", unlink_desc:"' . mce_escape( __('Unlink') ) . ' (Alt+Shift+S)", image_desc:"' . mce_escape( __('Insert/edit image') ) . ' (Alt+Shift+M)", image_delta_width:"' . /* translators: Extra width for the image popup in pixels */ mce_escape( _x('0', 'image popup width') ) . '", image_delta_height:"' . /* translators: Extra height for the image popup in pixels */ mce_escape( _x('0', 'image popup height') ) . '", cleanup_desc:"' . mce_escape( __('Cleanup messy code') ) . '", code_desc:"' . mce_escape( __('Edit HTML Source') ) . '", sub_desc:"' . mce_escape( __('Subscript') ) . '", sup_desc:"' . mce_escape( __('Superscript') ) . '", hr_desc:"' . mce_escape( __('Insert horizontal ruler') ) . '", removeformat_desc:"' . mce_escape( __('Remove formatting') ) . '", forecolor_desc:"' . mce_escape( __('Select text color') ) . '", backcolor_desc:"' . mce_escape( __('Select background color') ) . '", charmap_desc:"' . mce_escape( __('Insert custom character') ) . '", visualaid_desc:"' . mce_escape( __('Toggle guidelines/invisible elements') ) . '", anchor_desc:"' . mce_escape( __('Insert/edit anchor') ) . '", cut_desc:"' . mce_escape( __('Cut') ) . '", copy_desc:"' . mce_escape( __('Copy') ) . '", paste_desc:"' . mce_escape( __('Paste') ) . '", image_props_desc:"' . mce_escape( __('Image properties') ) . '", newdocument_desc:"' . mce_escape( __('New document') ) . '", help_desc:"' . mce_escape( __('Help') ) . '", blockquote_desc:"' . mce_escape( __('Blockquote') ) . ' (Alt+Shift+Q)", clipboard_msg:"' . mce_escape( __('Copy/Cut/Paste is not available in Mozilla and Firefox.') ) . '", path:"' . mce_escape( __('Path') ) . '", newdocument:"' . mce_escape( __('Are you sure you want to clear all contents?') ) . '", toolbar_focus:"' . mce_escape( __('Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X') ) . '", more_colors:"' . mce_escape( __('More colors') ) . '", colorpicker_delta_width:"' . /* translators: Extra width for the colorpicker popup in pixels */ mce_escape( _x('0', 'colorpicker popup width') ) . '", colorpicker_delta_height:"' . /* translators: Extra height for the colorpicker popup in pixels */ mce_escape( _x('0', 'colorpicker popup height') ) . '" }); tinyMCE.addI18n("' . $language . '.advanced_dlg",{ about_title:"' . mce_escape( __('About TinyMCE') ) . '", about_general:"' . mce_escape( __('About') ) . '", about_help:"' . mce_escape( __('Help') ) . '", about_license:"' . mce_escape( __('License') ) . '", about_plugins:"' . mce_escape( __('Plugins') ) . '", about_plugin:"' . mce_escape( __('Plugin') ) . '", about_author:"' . mce_escape( __('Author') ) . '", about_version:"' . mce_escape( __('Version') ) . '", about_loaded:"' . mce_escape( __('Loaded plugins') ) . '", anchor_title:"' . mce_escape( __('Insert/edit anchor') ) . '", anchor_name:"' . mce_escape( __('Anchor name') ) . '", code_title:"' . mce_escape( __('HTML Source Editor') ) . '", code_wordwrap:"' . mce_escape( __('Word wrap') ) . '", colorpicker_title:"' . mce_escape( __('Select a color') ) . '", colorpicker_picker_tab:"' . mce_escape( __('Picker') ) . '", colorpicker_picker_title:"' . mce_escape( __('Color picker') ) . '", colorpicker_palette_tab:"' . mce_escape( __('Palette') ) . '", colorpicker_palette_title:"' . mce_escape( __('Palette colors') ) . '", colorpicker_named_tab:"' . mce_escape( __('Named') ) . '", colorpicker_named_title:"' . mce_escape( __('Named colors') ) . '", colorpicker_color:"' . mce_escape( __('Color:') ) . '", colorpicker_name:"' . mce_escape( __('Name:') ) . '", charmap_title:"' . mce_escape( __('Select custom character') ) . '", image_title:"' . mce_escape( __('Insert/edit image') ) . '", image_src:"' . mce_escape( __('Image URL') ) . '", image_alt:"' . mce_escape( __('Image description') ) . '", image_list:"' . mce_escape( __('Image list') ) . '", image_border:"' . mce_escape( __('Border') ) . '", image_dimensions:"' . mce_escape( __('Dimensions') ) . '", image_vspace:"' . mce_escape( __('Vertical space') ) . '", image_hspace:"' . mce_escape( __('Horizontal space') ) . '", image_align:"' . mce_escape( __('Alignment') ) . '", image_align_baseline:"' . mce_escape( __('Baseline') ) . '", image_align_top:"' . mce_escape( __('Top') ) . '", image_align_middle:"' . mce_escape( __('Middle') ) . '", image_align_bottom:"' . mce_escape( __('Bottom') ) . '", image_align_texttop:"' . mce_escape( __('Text top') ) . '", image_align_textbottom:"' . mce_escape( __('Text bottom') ) . '", image_align_left:"' . mce_escape( __('Left') ) . '", image_align_right:"' . mce_escape( __('Right') ) . '", link_title:"' . mce_escape( __('Insert/edit link') ) . '", link_url:"' . mce_escape( __('Link URL') ) . '", link_target:"' . mce_escape( __('Target') ) . '", link_target_same:"' . mce_escape( __('Open link in the same window') ) . '", link_target_blank:"' . mce_escape( __('Open link in a new window') ) . '", link_titlefield:"' . mce_escape( __('Title') ) . '", link_is_email:"' . mce_escape( __('The URL you entered seems to be an email address, do you want to add the required mailto: prefix?') ) . '", link_is_external:"' . mce_escape( __('The URL you entered seems to external link, do you want to add the required http:// prefix?') ) . '", link_list:"' . mce_escape( __('Link list') ) . '" }); tinyMCE.addI18n("' . $language . '.media_dlg",{ title:"' . mce_escape( __('Insert / edit embedded media') ) . '", general:"' . mce_escape( __('General') ) . '", advanced:"' . mce_escape( __('Advanced') ) . '", file:"' . mce_escape( __('File/URL') ) . '", list:"' . mce_escape( __('List') ) . '", size:"' . mce_escape( __('Dimensions') ) . '", preview:"' . mce_escape( __('Preview') ) . '", constrain_proportions:"' . mce_escape( __('Constrain proportions') ) . '", type:"' . mce_escape( __('Type') ) . '", id:"' . mce_escape( __('Id') ) . '", name:"' . mce_escape( __('Name') ) . '", class_name:"' . mce_escape( __('Class') ) . '", vspace:"' . mce_escape( __('V-Space') ) . '", hspace:"' . mce_escape( __('H-Space') ) . '", play:"' . mce_escape( __('Auto play') ) . '", loop:"' . mce_escape( __('Loop') ) . '", menu:"' . mce_escape( __('Show menu') ) . '", quality:"' . mce_escape( __('Quality') ) . '", scale:"' . mce_escape( __('Scale') ) . '", align:"' . mce_escape( __('Align') ) . '", salign:"' . mce_escape( __('SAlign') ) . '", wmode:"' . mce_escape( __('WMode') ) . '", bgcolor:"' . mce_escape( __('Background') ) . '", base:"' . mce_escape( __('Base') ) . '", flashvars:"' . mce_escape( __('Flashvars') ) . '", liveconnect:"' . mce_escape( __('SWLiveConnect') ) . '", autohref:"' . mce_escape( __('AutoHREF') ) . '", cache:"' . mce_escape( __('Cache') ) . '", hidden:"' . mce_escape( __('Hidden') ) . '", controller:"' . mce_escape( __('Controller') ) . '", kioskmode:"' . mce_escape( __('Kiosk mode') ) . '", playeveryframe:"' . mce_escape( __('Play every frame') ) . '", targetcache:"' . mce_escape( __('Target cache') ) . '", correction:"' . mce_escape( __('No correction') ) . '", enablejavascript:"' . mce_escape( __('Enable JavaScript') ) . '", starttime:"' . mce_escape( __('Start time') ) . '", endtime:"' . mce_escape( __('End time') ) . '", href:"' . mce_escape( __('Href') ) . '", qtsrcchokespeed:"' . mce_escape( __('Choke speed') ) . '", target:"' . mce_escape( __('Target') ) . '", volume:"' . mce_escape( __('Volume') ) . '", autostart:"' . mce_escape( __('Auto start') ) . '", enabled:"' . mce_escape( __('Enabled') ) . '", fullscreen:"' . mce_escape( __('Fullscreen') ) . '", invokeurls:"' . mce_escape( __('Invoke URLs') ) . '", mute:"' . mce_escape( __('Mute') ) . '", stretchtofit:"' . mce_escape( __('Stretch to fit') ) . '", windowlessvideo:"' . mce_escape( __('Windowless video') ) . '", balance:"' . mce_escape( __('Balance') ) . '", baseurl:"' . mce_escape( __('Base URL') ) . '", captioningid:"' . mce_escape( __('Captioning id') ) . '", currentmarker:"' . mce_escape( __('Current marker') ) . '", currentposition:"' . mce_escape( __('Current position') ) . '", defaultframe:"' . mce_escape( __('Default frame') ) . '", playcount:"' . mce_escape( __('Play count') ) . '", rate:"' . mce_escape( __('Rate') ) . '", uimode:"' . mce_escape( __('UI Mode') ) . '", flash_options:"' . mce_escape( __('Flash options') ) . '", qt_options:"' . mce_escape( __('Quicktime options') ) . '", wmp_options:"' . mce_escape( __('Windows media player options') ) . '", rmp_options:"' . mce_escape( __('Real media player options') ) . '", shockwave_options:"' . mce_escape( __('Shockwave options') ) . '", autogotourl:"' . mce_escape( __('Auto goto URL') ) . '", center:"' . mce_escape( __('Center') ) . '", imagestatus:"' . mce_escape( __('Image status') ) . '", maintainaspect:"' . mce_escape( __('Maintain aspect') ) . '", nojava:"' . mce_escape( __('No java') ) . '", prefetch:"' . mce_escape( __('Prefetch') ) . '", shuffle:"' . mce_escape( __('Shuffle') ) . '", console:"' . mce_escape( __('Console') ) . '", numloop:"' . mce_escape( __('Num loops') ) . '", controls:"' . mce_escape( __('Controls') ) . '", scriptcallbacks:"' . mce_escape( __('Script callbacks') ) . '", swstretchstyle:"' . mce_escape( __('Stretch style') ) . '", swstretchhalign:"' . mce_escape( __('Stretch H-Align') ) . '", swstretchvalign:"' . mce_escape( __('Stretch V-Align') ) . '", sound:"' . mce_escape( __('Sound') ) . '", progress:"' . mce_escape( __('Progress') ) . '", qtsrc:"' . mce_escape( __('QT Src') ) . '", qt_stream_warn:"' . mce_escape( __('Streamed rtsp resources should be added to the QT Src field under the advanced tab.') ) . '", align_top:"' . mce_escape( __('Top') ) . '", align_right:"' . mce_escape( __('Right') ) . '", align_bottom:"' . mce_escape( __('Bottom') ) . '", align_left:"' . mce_escape( __('Left') ) . '", align_center:"' . mce_escape( __('Center') ) . '", align_top_left:"' . mce_escape( __('Top left') ) . '", align_top_right:"' . mce_escape( __('Top right') ) . '", align_bottom_left:"' . mce_escape( __('Bottom left') ) . '", align_bottom_right:"' . mce_escape( __('Bottom right') ) . '", flv_options:"' . mce_escape( __('Flash video options') ) . '", flv_scalemode:"' . mce_escape( __('Scale mode') ) . '", flv_buffer:"' . mce_escape( __('Buffer') ) . '", flv_startimage:"' . mce_escape( __('Start image') ) . '", flv_starttime:"' . mce_escape( __('Start time') ) . '", flv_defaultvolume:"' . mce_escape( __('Default volume') ) . '", flv_hiddengui:"' . mce_escape( __('Hidden GUI') ) . '", flv_autostart:"' . mce_escape( __('Auto start') ) . '", flv_loop:"' . mce_escape( __('Loop') ) . '", flv_showscalemodes:"' . mce_escape( __('Show scale modes') ) . '", flv_smoothvideo:"' . mce_escape( __('Smooth video') ) . '", flv_jscallback:"' . mce_escape( __('JS Callback') ) . '" }); tinyMCE.addI18n("' . $language . '.wordpress",{ wp_adv_desc:"' . mce_escape( __('Show/Hide Kitchen Sink') ) . ' (Alt+Shift+Z)", wp_more_desc:"' . mce_escape( __('Insert More tag') ) . ' (Alt+Shift+T)", wp_page_desc:"' . mce_escape( __('Insert Page break') ) . ' (Alt+Shift+P)", wp_help_desc:"' . mce_escape( __('Help') ) . ' (Alt+Shift+H)", wp_more_alt:"' . mce_escape( __('More...') ) . '", wp_page_alt:"' . mce_escape( __('Next page...') ) . '", add_media:"' . mce_escape( __('Add Media') ) . '", add_image:"' . mce_escape( __('Add an Image') ) . '", add_video:"' . mce_escape( __('Add Video') ) . '", add_audio:"' . mce_escape( __('Add Audio') ) . '", editgallery:"' . mce_escape( __('Edit Gallery') ) . '", delgallery:"' . mce_escape( __('Delete Gallery') ) . '" }); tinyMCE.addI18n("' . $language . '.wpeditimage",{ edit_img:"' . mce_escape( __('Edit Image') ) . '", del_img:"' . mce_escape( __('Delete Image') ) . '", adv_settings:"' . mce_escape( __('Advanced Settings') ) . '", none:"' . mce_escape( __('None') ) . '", size:"' . mce_escape( __('Size') ) . '", thumbnail:"' . mce_escape( __('Thumbnail') ) . '", medium:"' . mce_escape( __('Medium') ) . '", full_size:"' . mce_escape( __('Full Size') ) . '", current_link:"' . mce_escape( __('Current Link') ) . '", link_to_img:"' . mce_escape( __('Link to Image') ) . '", link_help:"' . mce_escape( __('Enter a link URL or click above for presets.') ) . '", adv_img_settings:"' . mce_escape( __('Advanced Image Settings') ) . '", source:"' . mce_escape( __('Source') ) . '", width:"' . mce_escape( __('Width') ) . '", height:"' . mce_escape( __('Height') ) . '", orig_size:"' . mce_escape( __('Original Size') ) . '", css:"' . mce_escape( __('CSS Class') ) . '", adv_link_settings:"' . mce_escape( __('Advanced Link Settings') ) . '", link_rel:"' . mce_escape( __('Link Rel') ) . '", height:"' . mce_escape( __('Height') ) . '", orig_size:"' . mce_escape( __('Original Size') ) . '", css:"' . mce_escape( __('CSS Class') ) . '", s60:"' . mce_escape( __('60%') ) . '", s70:"' . mce_escape( __('70%') ) . '", s80:"' . mce_escape( __('80%') ) . '", s90:"' . mce_escape( __('90%') ) . '", s100:"' . mce_escape( __('100%') ) . '", s110:"' . mce_escape( __('110%') ) . '", s120:"' . mce_escape( __('120%') ) . '", s130:"' . mce_escape( __('130%') ) . '", img_title:"' . mce_escape( __('Edit Image Title') ) . '", caption:"' . mce_escape( __('Edit Image Caption') ) . '", alt:"' . mce_escape( __('Edit Alternate Text') ) . '" }); ';
all: include ../lib.mk .PHONY: all all_32 all_64 warn_32bit_failure clean TARGETS_C_BOTHBITS := single_step_syscall sysret_ss_attrs syscall_nt ptrace_syscall \ check_initial_reg_state sigreturn ldt_gdt iopl TARGETS_C_32BIT_ONLY := entry_from_vm86 syscall_arg_fault test_syscall_vdso unwind_vdso \ test_FCMOV test_FCOMI test_FISTTP \ vdso_restorer TARGETS_C_64BIT_ONLY := fsgsbase TARGETS_C_32BIT_ALL := $(TARGETS_C_BOTHBITS) $(TARGETS_C_32BIT_ONLY) TARGETS_C_64BIT_ALL := $(TARGETS_C_BOTHBITS) $(TARGETS_C_64BIT_ONLY) BINARIES_32 := $(TARGETS_C_32BIT_ALL:%=%_32) BINARIES_64 := $(TARGETS_C_64BIT_ALL:%=%_64) CFLAGS := -O2 -g -std=gnu99 -pthread -Wall UNAME_M := $(shell uname -m) CAN_BUILD_I386 := $(shell ./check_cc.sh $(CC) trivial_32bit_program.c -m32) CAN_BUILD_X86_64 := $(shell ./check_cc.sh $(CC) trivial_64bit_program.c) ifeq ($(CAN_BUILD_I386),1) all: all_32 TEST_PROGS += $(BINARIES_32) endif ifeq ($(CAN_BUILD_X86_64),1) all: all_64 TEST_PROGS += $(BINARIES_64) endif all_32: $(BINARIES_32) all_64: $(BINARIES_64) clean: $(RM) $(BINARIES_32) $(BINARIES_64) $(TARGETS_C_32BIT_ALL:%=%_32): %_32: %.c $(CC) -m32 -o $@ $(CFLAGS) $(EXTRA_CFLAGS) $^ -lrt -ldl -lm $(TARGETS_C_64BIT_ALL:%=%_64): %_64: %.c $(CC) -m64 -o $@ $(CFLAGS) $(EXTRA_CFLAGS) $^ -lrt -ldl # x86_64 users should be encouraged to install 32-bit libraries ifeq ($(CAN_BUILD_I386)$(CAN_BUILD_X86_64),01) all: warn_32bit_failure warn_32bit_failure: @echo "Warning: you seem to have a broken 32-bit build" 2>&1; \ echo "environment. This will reduce test coverage of 64-bit" 2>&1; \ echo "kernels. If you are using a Debian-like distribution," 2>&1; \ echo "try:"; 2>&1; \ echo ""; \ echo " apt-get install gcc-multilib libc6-i386 libc6-dev-i386"; \ echo ""; \ echo "If you are using a Fedora-like distribution, try:"; \ echo ""; \ echo " yum install glibc-devel.*i686"; \ exit 0; endif # Some tests have additional dependencies. sysret_ss_attrs_64: thunks.S ptrace_syscall_32: raw_syscall_helper_32.S test_syscall_vdso_32: thunks_32.S # check_initial_reg_state is special: it needs a custom entry, and it # needs to be static so that its interpreter doesn't destroy its initial # state. check_initial_reg_state_32: CFLAGS += -Wl,-ereal_start -static check_initial_reg_state_64: CFLAGS += -Wl,-ereal_start -static
/* Functional tests for the "target" attribute and pragma. */ /* { dg-do compile } */ /* { dg-require-effective-target target_attribute } */ /* { dg-options "-mno-mvcle -march=z13 -O3" } */ #pragma GCC target("mvcle") void p1(char *b) { __builtin_memset (b, 0, 400); } #pragma GCC reset_options __attribute__ ((target("mvcle"))) void a1(char *b) { __builtin_memset (b, 0, 400); } /* { dg-final { scan-assembler-times "\tmvcle\t" 2 } } */
/*============================================================================= Copyright (c) 2001-2011 Hartmut Kaiser Copyright (c) 2001-2014 Joel de Guzman Copyright (c) 2013 Agustin Berge Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_SPIRIT_X3_ATTR_JUL_23_2008_0956AM #define BOOST_SPIRIT_X3_ATTR_JUL_23_2008_0956AM #include <boost/spirit/home/x3/core/parser.hpp> #include <boost/spirit/home/x3/support/unused.hpp> #include <boost/spirit/home/x3/support/traits/container_traits.hpp> #include <boost/spirit/home/x3/support/traits/move_to.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/remove_cv.hpp> #include <boost/type_traits/remove_reference.hpp> #include <algorithm> #include <cstddef> #include <string> #include <utility> namespace boost { namespace spirit { namespace x3 { template <typename Value> struct attr_parser : parser<attr_parser<Value>> { typedef Value attribute_type; static bool const has_attribute = !is_same<unused_type, attribute_type>::value; static bool const handles_container = traits::is_container<attribute_type>::value; attr_parser(Value const& value) : value_(value) {} attr_parser(Value&& value) : value_(std::move(value)) {} template <typename Iterator, typename Context , typename RuleContext, typename Attribute> bool parse(Iterator& /* first */, Iterator const& /* last */ , Context const& /* context */, RuleContext&, Attribute& attr_) const { // $$$ Change to copy_to once we have it $$$ traits::move_to(value_, attr_); return true; } Value value_; private: // silence MSVC warning C4512: assignment operator could not be generated attr_parser& operator= (attr_parser const&); }; template <typename Value, std::size_t N> struct attr_parser<Value[N]> : parser<attr_parser<Value[N]>> { typedef Value attribute_type[N]; static bool const has_attribute = !is_same<unused_type, attribute_type>::value; static bool const handles_container = true; attr_parser(Value const (&value)[N]) { std::copy(value + 0, value + N, value_ + 0); } attr_parser(Value (&&value)[N]) { std::move(value + 0, value + N, value_ + 0); } template <typename Iterator, typename Context , typename RuleContext, typename Attribute> bool parse(Iterator& /* first */, Iterator const& /* last */ , Context const& /* context */, RuleContext&, Attribute& attr_) const { // $$$ Change to copy_to once we have it $$$ traits::move_to(value_ + 0, value_ + N, attr_); return true; } Value value_[N]; private: // silence MSVC warning C4512: assignment operator could not be generated attr_parser& operator= (attr_parser const&); }; template <typename Value> struct get_info<attr_parser<Value>> { typedef std::string result_type; std::string operator()(attr_parser<Value> const& /*p*/) const { return "attr"; } }; struct attr_gen { template <typename Value> attr_parser<typename remove_cv< typename remove_reference<Value>::type>::type> operator()(Value&& value) const { return { std::forward<Value>(value) }; } template <typename Value, std::size_t N> attr_parser<typename remove_cv<Value>::type[N]> operator()(Value (&value)[N]) const { return { value }; } template <typename Value, std::size_t N> attr_parser<typename remove_cv<Value>::type[N]> operator()(Value (&&value)[N]) const { return { value }; } }; auto const attr = attr_gen{}; }}} #endif
<?php class Migrations_Migration314 Extends Shopware\Components\Migrations\AbstractMigration { public function up($modus) { $this->addSql(' ALTER TABLE `s_order_details` ADD `pack_unit` VARCHAR(255) NULL DEFAULT NULL ; '); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract partial class CompilerDiagnosticAnalyzer : DiagnosticAnalyzer { private const string Origin = "Origin"; private const string Syntactic = "Syntactic"; private const string Declaration = "Declaration"; private static readonly ImmutableDictionary<string, string> s_syntactic = ImmutableDictionary<string, string>.Empty.Add(Origin, Syntactic); private static readonly ImmutableDictionary<string, string> s_declaration = ImmutableDictionary<string, string>.Empty.Add(Origin, Declaration); /// <summary> /// Per-compilation DiagnosticAnalyzer for compiler's syntax/semantic/compilation diagnostics. /// </summary> private class CompilationAnalyzer { private readonly Compilation _compilation; public CompilationAnalyzer(Compilation compilation) { _compilation = compilation; } public void AnalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { var semanticModel = _compilation.GetSemanticModel(context.Tree); var diagnostics = semanticModel.GetSyntaxDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(diagnostics, context.ReportDiagnostic, IsSourceLocation, s_syntactic); } public static void AnalyzeSemanticModel(SemanticModelAnalysisContext context) { var declDiagnostics = context.SemanticModel.GetDeclarationDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(declDiagnostics, context.ReportDiagnostic, IsSourceLocation, s_declaration); var bodyDiagnostics = context.SemanticModel.GetMethodBodyDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(bodyDiagnostics, context.ReportDiagnostic, IsSourceLocation); } public static void AnalyzeCompilation(CompilationAnalysisContext context) { var diagnostics = context.Compilation.GetDeclarationDiagnostics(cancellationToken: context.CancellationToken); ReportDiagnostics(diagnostics, context.ReportDiagnostic, location => !IsSourceLocation(location), s_declaration); } private static bool IsSourceLocation(Location location) { return location != null && location.Kind == LocationKind.SourceFile; } private static void ReportDiagnostics( ImmutableArray<Diagnostic> diagnostics, Action<Diagnostic> reportDiagnostic, Func<Location, bool> locationFilter, ImmutableDictionary<string, string> properties = null) { foreach (var diagnostic in diagnostics) { if (locationFilter(diagnostic.Location) && diagnostic.Severity != DiagnosticSeverity.Hidden) { var current = properties == null ? diagnostic : new CompilerDiagnostic(diagnostic, properties); reportDiagnostic(current); } } } private class CompilerDiagnostic : Diagnostic { private readonly Diagnostic _original; private readonly ImmutableDictionary<string, string> _properties; public CompilerDiagnostic(Diagnostic original, ImmutableDictionary<string, string> properties) { _original = original; _properties = properties; } #pragma warning disable RS0013 // we are delegating so it is okay here public override DiagnosticDescriptor Descriptor => _original.Descriptor; #pragma warning restore RS0013 public override string Id => _original.Id; public override DiagnosticSeverity Severity => _original.Severity; public override int WarningLevel => _original.WarningLevel; public override Location Location => _original.Location; public override IReadOnlyList<Location> AdditionalLocations => _original.AdditionalLocations; public override ImmutableDictionary<string, string> Properties => _properties; public override string GetMessage(IFormatProvider formatProvider = null) { return _original.GetMessage(formatProvider); } public override bool Equals(object obj) { return _original.Equals(obj); } public override int GetHashCode() { return _original.GetHashCode(); } public override bool Equals(Diagnostic obj) { return _original.Equals(obj); } internal override Diagnostic WithLocation(Location location) { return new CompilerDiagnostic(_original.WithLocation(location), _properties); } internal override Diagnostic WithSeverity(DiagnosticSeverity severity) { return new CompilerDiagnostic(_original.WithSeverity(severity), _properties); } } } } }
/* * Copyright 2000-2014 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.openapi.wm.ex; import com.intellij.openapi.Disposable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowEP; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.impl.DesktopLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; public abstract class ToolWindowManagerEx extends ToolWindowManager { public abstract void initToolWindow(@NotNull ToolWindowEP bean); public static ToolWindowManagerEx getInstanceEx(final Project project){ return (ToolWindowManagerEx)getInstance(project); } public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l); public abstract void addToolWindowManagerListener(@NotNull ToolWindowManagerListener l, @NotNull Disposable parentDisposable); public abstract void removeToolWindowManagerListener(@NotNull ToolWindowManagerListener l); /** * @return <code>ID</code> of tool window that was activated last time. */ @Nullable public abstract String getLastActiveToolWindowId(); /** * @return <code>ID</code> of tool window which was last activated among tool windows satisfying the current condition */ @Nullable public abstract String getLastActiveToolWindowId(@Nullable Condition<JComponent> condition); /** * @return layout of tool windows. */ public abstract DesktopLayout getLayout(); public abstract void setLayoutToRestoreLater(DesktopLayout layout); public abstract DesktopLayout getLayoutToRestoreLater(); /** * Copied <code>layout</code> into internal layout and rearranges tool windows. */ public abstract void setLayout(@NotNull DesktopLayout layout); public abstract void clearSideStack(); public abstract void hideToolWindow(@NotNull String id, boolean hideSide); public abstract List<String> getIdsOn(@NotNull ToolWindowAnchor anchor); }
/* savage_drm.h -- Public header for the savage driver * * Copyright 2004 Felix Kuehling * All Rights Reserved. * * 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, sub license, * 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 (including the * next paragraph) 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 * NON-INFRINGEMENT. IN NO EVENT SHALL FELIX KUEHLING 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 __SAVAGE_DRM_H__ #define __SAVAGE_DRM_H__ #include "drm.h" #if defined(__cplusplus) extern "C" { #endif #ifndef __SAVAGE_SAREA_DEFINES__ #define __SAVAGE_SAREA_DEFINES__ /* 2 heaps (1 for card, 1 for agp), each divided into up to 128 * regions, subject to a minimum region size of (1<<16) == 64k. * * Clients may subdivide regions internally, but when sharing between * clients, the region size is the minimum granularity. */ #define SAVAGE_CARD_HEAP 0 #define SAVAGE_AGP_HEAP 1 #define SAVAGE_NR_TEX_HEAPS 2 #define SAVAGE_NR_TEX_REGIONS 16 #define SAVAGE_LOG_MIN_TEX_REGION_SIZE 16 #endif /* __SAVAGE_SAREA_DEFINES__ */ typedef struct _drm_savage_sarea { /* LRU lists for texture memory in agp space and on the card. */ struct drm_tex_region texList[SAVAGE_NR_TEX_HEAPS][SAVAGE_NR_TEX_REGIONS + 1]; unsigned int texAge[SAVAGE_NR_TEX_HEAPS]; /* Mechanism to validate card state. */ int ctxOwner; } drm_savage_sarea_t, *drm_savage_sarea_ptr; /* Savage-specific ioctls */ #define DRM_SAVAGE_BCI_INIT 0x00 #define DRM_SAVAGE_BCI_CMDBUF 0x01 #define DRM_SAVAGE_BCI_EVENT_EMIT 0x02 #define DRM_SAVAGE_BCI_EVENT_WAIT 0x03 #define DRM_IOCTL_SAVAGE_BCI_INIT DRM_IOW( DRM_COMMAND_BASE + DRM_SAVAGE_BCI_INIT, drm_savage_init_t) #define DRM_IOCTL_SAVAGE_BCI_CMDBUF DRM_IOW( DRM_COMMAND_BASE + DRM_SAVAGE_BCI_CMDBUF, drm_savage_cmdbuf_t) #define DRM_IOCTL_SAVAGE_BCI_EVENT_EMIT DRM_IOWR(DRM_COMMAND_BASE + DRM_SAVAGE_BCI_EVENT_EMIT, drm_savage_event_emit_t) #define DRM_IOCTL_SAVAGE_BCI_EVENT_WAIT DRM_IOW( DRM_COMMAND_BASE + DRM_SAVAGE_BCI_EVENT_WAIT, drm_savage_event_wait_t) #define SAVAGE_DMA_PCI 1 #define SAVAGE_DMA_AGP 3 typedef struct drm_savage_init { enum { SAVAGE_INIT_BCI = 1, SAVAGE_CLEANUP_BCI = 2 } func; unsigned int sarea_priv_offset; /* some parameters */ unsigned int cob_size; unsigned int bci_threshold_lo, bci_threshold_hi; unsigned int dma_type; /* frame buffer layout */ unsigned int fb_bpp; unsigned int front_offset, front_pitch; unsigned int back_offset, back_pitch; unsigned int depth_bpp; unsigned int depth_offset, depth_pitch; /* local textures */ unsigned int texture_offset; unsigned int texture_size; /* physical locations of non-permanent maps */ unsigned long status_offset; unsigned long buffers_offset; unsigned long agp_textures_offset; unsigned long cmd_dma_offset; } drm_savage_init_t; typedef union drm_savage_cmd_header drm_savage_cmd_header_t; typedef struct drm_savage_cmdbuf { /* command buffer in client's address space */ drm_savage_cmd_header_t __user *cmd_addr; unsigned int size; /* size of the command buffer in 64bit units */ unsigned int dma_idx; /* DMA buffer index to use */ int discard; /* discard DMA buffer when done */ /* vertex buffer in client's address space */ unsigned int __user *vb_addr; unsigned int vb_size; /* size of client vertex buffer in bytes */ unsigned int vb_stride; /* stride of vertices in 32bit words */ /* boxes in client's address space */ struct drm_clip_rect __user *box_addr; unsigned int nbox; /* number of clipping boxes */ } drm_savage_cmdbuf_t; #define SAVAGE_WAIT_2D 0x1 /* wait for 2D idle before updating event tag */ #define SAVAGE_WAIT_3D 0x2 /* wait for 3D idle before updating event tag */ #define SAVAGE_WAIT_IRQ 0x4 /* emit or wait for IRQ, not implemented yet */ typedef struct drm_savage_event { unsigned int count; unsigned int flags; } drm_savage_event_emit_t, drm_savage_event_wait_t; /* Commands for the cmdbuf ioctl */ #define SAVAGE_CMD_STATE 0 /* a range of state registers */ #define SAVAGE_CMD_DMA_PRIM 1 /* vertices from DMA buffer */ #define SAVAGE_CMD_VB_PRIM 2 /* vertices from client vertex buffer */ #define SAVAGE_CMD_DMA_IDX 3 /* indexed vertices from DMA buffer */ #define SAVAGE_CMD_VB_IDX 4 /* indexed vertices client vertex buffer */ #define SAVAGE_CMD_CLEAR 5 /* clear buffers */ #define SAVAGE_CMD_SWAP 6 /* swap buffers */ /* Primitive types */ #define SAVAGE_PRIM_TRILIST 0 /* triangle list */ #define SAVAGE_PRIM_TRISTRIP 1 /* triangle strip */ #define SAVAGE_PRIM_TRIFAN 2 /* triangle fan */ #define SAVAGE_PRIM_TRILIST_201 3 /* reorder verts for correct flat * shading on s3d */ /* Skip flags (vertex format) */ #define SAVAGE_SKIP_Z 0x01 #define SAVAGE_SKIP_W 0x02 #define SAVAGE_SKIP_C0 0x04 #define SAVAGE_SKIP_C1 0x08 #define SAVAGE_SKIP_S0 0x10 #define SAVAGE_SKIP_T0 0x20 #define SAVAGE_SKIP_ST0 0x30 #define SAVAGE_SKIP_S1 0x40 #define SAVAGE_SKIP_T1 0x80 #define SAVAGE_SKIP_ST1 0xc0 #define SAVAGE_SKIP_ALL_S3D 0x3f #define SAVAGE_SKIP_ALL_S4 0xff /* Buffer names for clear command */ #define SAVAGE_FRONT 0x1 #define SAVAGE_BACK 0x2 #define SAVAGE_DEPTH 0x4 /* 64-bit command header */ union drm_savage_cmd_header { struct { unsigned char cmd; /* command */ unsigned char pad0; unsigned short pad1; unsigned short pad2; unsigned short pad3; } cmd; /* generic */ struct { unsigned char cmd; unsigned char global; /* need idle engine? */ unsigned short count; /* number of consecutive registers */ unsigned short start; /* first register */ unsigned short pad3; } state; /* SAVAGE_CMD_STATE */ struct { unsigned char cmd; unsigned char prim; /* primitive type */ unsigned short skip; /* vertex format (skip flags) */ unsigned short count; /* number of vertices */ unsigned short start; /* first vertex in DMA/vertex buffer */ } prim; /* SAVAGE_CMD_DMA_PRIM, SAVAGE_CMD_VB_PRIM */ struct { unsigned char cmd; unsigned char prim; unsigned short skip; unsigned short count; /* number of indices that follow */ unsigned short pad3; } idx; /* SAVAGE_CMD_DMA_IDX, SAVAGE_CMD_VB_IDX */ struct { unsigned char cmd; unsigned char pad0; unsigned short pad1; unsigned int flags; } clear0; /* SAVAGE_CMD_CLEAR */ struct { unsigned int mask; unsigned int value; } clear1; /* SAVAGE_CMD_CLEAR data */ }; #if defined(__cplusplus) } #endif #endif
<?php /** * Part of the Fuel framework. * * @package Fuel * @version 1.7 * @author Fuel Development Team * @license MIT License * @copyright 2010 - 2015 Fuel Development Team * @link http://fuelphp.com */ namespace Fuel\Core; /** * Fieldset class tests * * @group Core * @group Fieldset */ class Test_Fieldset extends TestCase { public function setUp() { // fake the uri for this request isset($_SERVER['PATH_INFO']) and $this->pathinfo = $_SERVER['PATH_INFO']; $_SERVER['PATH_INFO'] = '/welcome/index'; // set Request::$main $request = \Request::forge('welcome/index'); $rp = new \ReflectionProperty($request, 'main'); $rp->setAccessible(true); $rp->setValue($request, $request); \Request::active($request); } public function tearDown() { // remove the fake uri if (property_exists($this, 'pathinfo')) { $_SERVER['PATH_INFO'] = $this->pathinfo; } else { unset($_SERVER['PATH_INFO']); } // reset Request::$main $request = \Request::forge(); $rp = new \ReflectionProperty($request, 'main'); $rp->setAccessible(true); $rp->setValue($request, false); } /** * Test of "for" attribute in label tag */ public function test_for_in_label() { $form = Fieldset::forge(__METHOD__)->set_config(array( // regular form definitions 'prep_value' => true, 'auto_id' => true, 'auto_id_prefix' => 'form_', 'form_method' => 'post', 'form_template' => "\n\t\t{open}\n\t\t<table>\n{fields}\n\t\t</table>\n\t\t{close}\n", 'fieldset_template' => "\n\t\t<tr><td colspan=\"2\">{open}<table>\n{fields}</table></td></tr>\n\t\t{close}\n", 'field_template' => "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{field} <span>{description}</span> {error_msg}</td>\n\t\t</tr>\n", 'multi_field_template' => "\t\t<tr>\n\t\t\t<td class=\"{error_class}\">{group_label}{required}</td>\n\t\t\t<td class=\"{error_class}\">{fields}\n\t\t\t\t{field} {label}<br />\n{fields}<span>{description}</span>\t\t\t{error_msg}\n\t\t\t</td>\n\t\t</tr>\n", 'error_template' => '<span>{error_msg}</span>', 'group_label' => '<span>{label}</span>', 'required_mark' => '*', 'inline_errors' => false, 'error_class' => 'validation_error', // tabular form definitions 'tabular_form_template' => "<table>{fields}</table>\n", 'tabular_field_template' => "{field}", 'tabular_row_template' => "<tr>{fields}</tr>\n", 'tabular_row_field_template' => "\t\t\t<td>{label}{required}&nbsp;{field} {icon} {error_msg}</td>\n", 'tabular_delete_label' => "Delete?", )); $ops = array('male', 'female'); $form->add('gender', '', array( 'options' => $ops, 'type' => 'radio', 'value' => 1, )); $output = $form->build(); $output = str_replace(array("\n", "\t"), "", $output); $expected = '<form action="welcome/index" accept-charset="utf-8" method="post"><table><tr><td class=""></td><td class=""><input type="radio" value="0" id="form_gender_0" name="gender" /> <label for="form_gender_0">male</label><br /><input type="radio" value="1" id="form_gender_1" name="gender" checked="checked" /> <label for="form_gender_1">female</label><br /><span></span></td></tr></table></form>'; $this->assertEquals($expected, $output); } }
import * as _ from "lodash"; declare const sampleSize: typeof _.sampleSize; export default sampleSize;
#ifndef _DIRENT_H_ #define _DIRENT_H_ #ifdef __cplusplus extern "C" { #endif #include <sys/cdefs.h> #include <sys/dirent.h> #if !defined(MAXNAMLEN) && __BSD_VISIBLE #define MAXNAMLEN 1024 #endif #ifdef __cplusplus } #endif #endif /*_DIRENT_H_*/
/* Copyright 2012-15 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. * * Authors: AMD * */ #ifndef __DC_DMCU_H__ #define __DC_DMCU_H__ #include "dm_services_types.h" enum dmcu_state { DMCU_NOT_INITIALIZED = 0, DMCU_RUNNING = 1 }; struct dmcu { struct dc_context *ctx; const struct dmcu_funcs *funcs; enum dmcu_state dmcu_state; struct dmcu_version dmcu_version; unsigned int cached_wait_loop_number; }; struct dmcu_funcs { bool (*dmcu_init)(struct dmcu *dmcu); bool (*load_iram)(struct dmcu *dmcu, unsigned int start_offset, const char *src, unsigned int bytes); void (*set_psr_enable)(struct dmcu *dmcu, bool enable, bool wait); bool (*setup_psr)(struct dmcu *dmcu, struct dc_link *link, struct psr_context *psr_context); void (*get_psr_state)(struct dmcu *dmcu, uint32_t *psr_state); void (*set_psr_wait_loop)(struct dmcu *dmcu, unsigned int wait_loop_number); void (*get_psr_wait_loop)(struct dmcu *dmcu, unsigned int *psr_wait_loop_number); bool (*is_dmcu_initialized)(struct dmcu *dmcu); }; #endif
/* * Copyright (C) 2013-2014 Allwinner Tech Co., Ltd * Author: Sugar <shuge@allwinnertech.com> * * Copyright (C) 2014 Maxime Ripard * Maxime Ripard <maxime.ripard@free-electrons.com> * * 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. */ #include <linux/clk.h> #include <linux/delay.h> #include <linux/dmaengine.h> #include <linux/dmapool.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/of_dma.h> #include <linux/of_device.h> #include <linux/platform_device.h> #include <linux/reset.h> #include <linux/slab.h> #include <linux/types.h> #include "virt-dma.h" /* * Common registers */ #define DMA_IRQ_EN(x) ((x) * 0x04) #define DMA_IRQ_HALF BIT(0) #define DMA_IRQ_PKG BIT(1) #define DMA_IRQ_QUEUE BIT(2) #define DMA_IRQ_CHAN_NR 8 #define DMA_IRQ_CHAN_WIDTH 4 #define DMA_IRQ_STAT(x) ((x) * 0x04 + 0x10) #define DMA_STAT 0x30 /* * sun8i specific registers */ #define SUN8I_DMA_GATE 0x20 #define SUN8I_DMA_GATE_ENABLE 0x4 /* * Channels specific registers */ #define DMA_CHAN_ENABLE 0x00 #define DMA_CHAN_ENABLE_START BIT(0) #define DMA_CHAN_ENABLE_STOP 0 #define DMA_CHAN_PAUSE 0x04 #define DMA_CHAN_PAUSE_PAUSE BIT(1) #define DMA_CHAN_PAUSE_RESUME 0 #define DMA_CHAN_LLI_ADDR 0x08 #define DMA_CHAN_CUR_CFG 0x0c #define DMA_CHAN_CFG_SRC_DRQ(x) ((x) & 0x1f) #define DMA_CHAN_CFG_SRC_IO_MODE BIT(5) #define DMA_CHAN_CFG_SRC_LINEAR_MODE (0 << 5) #define DMA_CHAN_CFG_SRC_BURST(x) (((x) & 0x3) << 7) #define DMA_CHAN_CFG_SRC_WIDTH(x) (((x) & 0x3) << 9) #define DMA_CHAN_CFG_DST_DRQ(x) (DMA_CHAN_CFG_SRC_DRQ(x) << 16) #define DMA_CHAN_CFG_DST_IO_MODE (DMA_CHAN_CFG_SRC_IO_MODE << 16) #define DMA_CHAN_CFG_DST_LINEAR_MODE (DMA_CHAN_CFG_SRC_LINEAR_MODE << 16) #define DMA_CHAN_CFG_DST_BURST(x) (DMA_CHAN_CFG_SRC_BURST(x) << 16) #define DMA_CHAN_CFG_DST_WIDTH(x) (DMA_CHAN_CFG_SRC_WIDTH(x) << 16) #define DMA_CHAN_CUR_SRC 0x10 #define DMA_CHAN_CUR_DST 0x14 #define DMA_CHAN_CUR_CNT 0x18 #define DMA_CHAN_CUR_PARA 0x1c /* * Various hardware related defines */ #define LLI_LAST_ITEM 0xfffff800 #define NORMAL_WAIT 8 #define DRQ_SDRAM 1 /* * Hardware channels / ports representation * * The hardware is used in several SoCs, with differing numbers * of channels and endpoints. This structure ties those numbers * to a certain compatible string. */ struct sun6i_dma_config { u32 nr_max_channels; u32 nr_max_requests; u32 nr_max_vchans; }; /* * Hardware representation of the LLI * * The hardware will be fed the physical address of this structure, * and read its content in order to start the transfer. */ struct sun6i_dma_lli { u32 cfg; u32 src; u32 dst; u32 len; u32 para; u32 p_lli_next; /* * This field is not used by the DMA controller, but will be * used by the CPU to go through the list (mostly for dumping * or freeing it). */ struct sun6i_dma_lli *v_lli_next; }; struct sun6i_desc { struct virt_dma_desc vd; dma_addr_t p_lli; struct sun6i_dma_lli *v_lli; }; struct sun6i_pchan { u32 idx; void __iomem *base; struct sun6i_vchan *vchan; struct sun6i_desc *desc; struct sun6i_desc *done; }; struct sun6i_vchan { struct virt_dma_chan vc; struct list_head node; struct dma_slave_config cfg; struct sun6i_pchan *phy; u8 port; u8 irq_type; bool cyclic; }; struct sun6i_dma_dev { struct dma_device slave; void __iomem *base; struct clk *clk; int irq; spinlock_t lock; struct reset_control *rstc; struct tasklet_struct task; atomic_t tasklet_shutdown; struct list_head pending; struct dma_pool *pool; struct sun6i_pchan *pchans; struct sun6i_vchan *vchans; const struct sun6i_dma_config *cfg; }; static struct device *chan2dev(struct dma_chan *chan) { return &chan->dev->device; } static inline struct sun6i_dma_dev *to_sun6i_dma_dev(struct dma_device *d) { return container_of(d, struct sun6i_dma_dev, slave); } static inline struct sun6i_vchan *to_sun6i_vchan(struct dma_chan *chan) { return container_of(chan, struct sun6i_vchan, vc.chan); } static inline struct sun6i_desc * to_sun6i_desc(struct dma_async_tx_descriptor *tx) { return container_of(tx, struct sun6i_desc, vd.tx); } static inline void sun6i_dma_dump_com_regs(struct sun6i_dma_dev *sdev) { dev_dbg(sdev->slave.dev, "Common register:\n" "\tmask0(%04x): 0x%08x\n" "\tmask1(%04x): 0x%08x\n" "\tpend0(%04x): 0x%08x\n" "\tpend1(%04x): 0x%08x\n" "\tstats(%04x): 0x%08x\n", DMA_IRQ_EN(0), readl(sdev->base + DMA_IRQ_EN(0)), DMA_IRQ_EN(1), readl(sdev->base + DMA_IRQ_EN(1)), DMA_IRQ_STAT(0), readl(sdev->base + DMA_IRQ_STAT(0)), DMA_IRQ_STAT(1), readl(sdev->base + DMA_IRQ_STAT(1)), DMA_STAT, readl(sdev->base + DMA_STAT)); } static inline void sun6i_dma_dump_chan_regs(struct sun6i_dma_dev *sdev, struct sun6i_pchan *pchan) { phys_addr_t reg = virt_to_phys(pchan->base); dev_dbg(sdev->slave.dev, "Chan %d reg: %pa\n" "\t___en(%04x): \t0x%08x\n" "\tpause(%04x): \t0x%08x\n" "\tstart(%04x): \t0x%08x\n" "\t__cfg(%04x): \t0x%08x\n" "\t__src(%04x): \t0x%08x\n" "\t__dst(%04x): \t0x%08x\n" "\tcount(%04x): \t0x%08x\n" "\t_para(%04x): \t0x%08x\n\n", pchan->idx, &reg, DMA_CHAN_ENABLE, readl(pchan->base + DMA_CHAN_ENABLE), DMA_CHAN_PAUSE, readl(pchan->base + DMA_CHAN_PAUSE), DMA_CHAN_LLI_ADDR, readl(pchan->base + DMA_CHAN_LLI_ADDR), DMA_CHAN_CUR_CFG, readl(pchan->base + DMA_CHAN_CUR_CFG), DMA_CHAN_CUR_SRC, readl(pchan->base + DMA_CHAN_CUR_SRC), DMA_CHAN_CUR_DST, readl(pchan->base + DMA_CHAN_CUR_DST), DMA_CHAN_CUR_CNT, readl(pchan->base + DMA_CHAN_CUR_CNT), DMA_CHAN_CUR_PARA, readl(pchan->base + DMA_CHAN_CUR_PARA)); } static inline s8 convert_burst(u32 maxburst) { switch (maxburst) { case 1: return 0; case 8: return 2; default: return -EINVAL; } } static inline s8 convert_buswidth(enum dma_slave_buswidth addr_width) { if ((addr_width < DMA_SLAVE_BUSWIDTH_1_BYTE) || (addr_width > DMA_SLAVE_BUSWIDTH_4_BYTES)) return -EINVAL; return addr_width >> 1; } static size_t sun6i_get_chan_size(struct sun6i_pchan *pchan) { struct sun6i_desc *txd = pchan->desc; struct sun6i_dma_lli *lli; size_t bytes; dma_addr_t pos; pos = readl(pchan->base + DMA_CHAN_LLI_ADDR); bytes = readl(pchan->base + DMA_CHAN_CUR_CNT); if (pos == LLI_LAST_ITEM) return bytes; for (lli = txd->v_lli; lli; lli = lli->v_lli_next) { if (lli->p_lli_next == pos) { for (lli = lli->v_lli_next; lli; lli = lli->v_lli_next) bytes += lli->len; break; } } return bytes; } static void *sun6i_dma_lli_add(struct sun6i_dma_lli *prev, struct sun6i_dma_lli *next, dma_addr_t next_phy, struct sun6i_desc *txd) { if ((!prev && !txd) || !next) return NULL; if (!prev) { txd->p_lli = next_phy; txd->v_lli = next; } else { prev->p_lli_next = next_phy; prev->v_lli_next = next; } next->p_lli_next = LLI_LAST_ITEM; next->v_lli_next = NULL; return next; } static inline void sun6i_dma_dump_lli(struct sun6i_vchan *vchan, struct sun6i_dma_lli *lli) { phys_addr_t p_lli = virt_to_phys(lli); dev_dbg(chan2dev(&vchan->vc.chan), "\n\tdesc: p - %pa v - 0x%p\n" "\t\tc - 0x%08x s - 0x%08x d - 0x%08x\n" "\t\tl - 0x%08x p - 0x%08x n - 0x%08x\n", &p_lli, lli, lli->cfg, lli->src, lli->dst, lli->len, lli->para, lli->p_lli_next); } static void sun6i_dma_free_desc(struct virt_dma_desc *vd) { struct sun6i_desc *txd = to_sun6i_desc(&vd->tx); struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vd->tx.chan->device); struct sun6i_dma_lli *v_lli, *v_next; dma_addr_t p_lli, p_next; if (unlikely(!txd)) return; p_lli = txd->p_lli; v_lli = txd->v_lli; while (v_lli) { v_next = v_lli->v_lli_next; p_next = v_lli->p_lli_next; dma_pool_free(sdev->pool, v_lli, p_lli); v_lli = v_next; p_lli = p_next; } kfree(txd); } static int sun6i_dma_start_desc(struct sun6i_vchan *vchan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(vchan->vc.chan.device); struct virt_dma_desc *desc = vchan_next_desc(&vchan->vc); struct sun6i_pchan *pchan = vchan->phy; u32 irq_val, irq_reg, irq_offset; if (!pchan) return -EAGAIN; if (!desc) { pchan->desc = NULL; pchan->done = NULL; return -EAGAIN; } list_del(&desc->node); pchan->desc = to_sun6i_desc(&desc->tx); pchan->done = NULL; sun6i_dma_dump_lli(vchan, pchan->desc->v_lli); irq_reg = pchan->idx / DMA_IRQ_CHAN_NR; irq_offset = pchan->idx % DMA_IRQ_CHAN_NR; vchan->irq_type = vchan->cyclic ? DMA_IRQ_PKG : DMA_IRQ_QUEUE; irq_val = readl(sdev->base + DMA_IRQ_EN(irq_reg)); irq_val &= ~((DMA_IRQ_HALF | DMA_IRQ_PKG | DMA_IRQ_QUEUE) << (irq_offset * DMA_IRQ_CHAN_WIDTH)); irq_val |= vchan->irq_type << (irq_offset * DMA_IRQ_CHAN_WIDTH); writel(irq_val, sdev->base + DMA_IRQ_EN(irq_reg)); writel(pchan->desc->p_lli, pchan->base + DMA_CHAN_LLI_ADDR); writel(DMA_CHAN_ENABLE_START, pchan->base + DMA_CHAN_ENABLE); sun6i_dma_dump_com_regs(sdev); sun6i_dma_dump_chan_regs(sdev, pchan); return 0; } static void sun6i_dma_tasklet(unsigned long data) { struct sun6i_dma_dev *sdev = (struct sun6i_dma_dev *)data; const struct sun6i_dma_config *cfg = sdev->cfg; struct sun6i_vchan *vchan; struct sun6i_pchan *pchan; unsigned int pchan_alloc = 0; unsigned int pchan_idx; list_for_each_entry(vchan, &sdev->slave.channels, vc.chan.device_node) { spin_lock_irq(&vchan->vc.lock); pchan = vchan->phy; if (pchan && pchan->done) { if (sun6i_dma_start_desc(vchan)) { /* * No current txd associated with this channel */ dev_dbg(sdev->slave.dev, "pchan %u: free\n", pchan->idx); /* Mark this channel free */ vchan->phy = NULL; pchan->vchan = NULL; } } spin_unlock_irq(&vchan->vc.lock); } spin_lock_irq(&sdev->lock); for (pchan_idx = 0; pchan_idx < cfg->nr_max_channels; pchan_idx++) { pchan = &sdev->pchans[pchan_idx]; if (pchan->vchan || list_empty(&sdev->pending)) continue; vchan = list_first_entry(&sdev->pending, struct sun6i_vchan, node); /* Remove from pending channels */ list_del_init(&vchan->node); pchan_alloc |= BIT(pchan_idx); /* Mark this channel allocated */ pchan->vchan = vchan; vchan->phy = pchan; dev_dbg(sdev->slave.dev, "pchan %u: alloc vchan %p\n", pchan->idx, &vchan->vc); } spin_unlock_irq(&sdev->lock); for (pchan_idx = 0; pchan_idx < cfg->nr_max_channels; pchan_idx++) { if (!(pchan_alloc & BIT(pchan_idx))) continue; pchan = sdev->pchans + pchan_idx; vchan = pchan->vchan; if (vchan) { spin_lock_irq(&vchan->vc.lock); sun6i_dma_start_desc(vchan); spin_unlock_irq(&vchan->vc.lock); } } } static irqreturn_t sun6i_dma_interrupt(int irq, void *dev_id) { struct sun6i_dma_dev *sdev = dev_id; struct sun6i_vchan *vchan; struct sun6i_pchan *pchan; int i, j, ret = IRQ_NONE; u32 status; for (i = 0; i < sdev->cfg->nr_max_channels / DMA_IRQ_CHAN_NR; i++) { status = readl(sdev->base + DMA_IRQ_STAT(i)); if (!status) continue; dev_dbg(sdev->slave.dev, "DMA irq status %s: 0x%x\n", i ? "high" : "low", status); writel(status, sdev->base + DMA_IRQ_STAT(i)); for (j = 0; (j < DMA_IRQ_CHAN_NR) && status; j++) { pchan = sdev->pchans + j; vchan = pchan->vchan; if (vchan && (status & vchan->irq_type)) { if (vchan->cyclic) { vchan_cyclic_callback(&pchan->desc->vd); } else { spin_lock(&vchan->vc.lock); vchan_cookie_complete(&pchan->desc->vd); pchan->done = pchan->desc; spin_unlock(&vchan->vc.lock); } } status = status >> DMA_IRQ_CHAN_WIDTH; } if (!atomic_read(&sdev->tasklet_shutdown)) tasklet_schedule(&sdev->task); ret = IRQ_HANDLED; } return ret; } static int set_config(struct sun6i_dma_dev *sdev, struct dma_slave_config *sconfig, enum dma_transfer_direction direction, u32 *p_cfg) { s8 src_width, dst_width, src_burst, dst_burst; switch (direction) { case DMA_MEM_TO_DEV: src_burst = convert_burst(sconfig->src_maxburst ? sconfig->src_maxburst : 8); src_width = convert_buswidth(sconfig->src_addr_width != DMA_SLAVE_BUSWIDTH_UNDEFINED ? sconfig->src_addr_width : DMA_SLAVE_BUSWIDTH_4_BYTES); dst_burst = convert_burst(sconfig->dst_maxburst); dst_width = convert_buswidth(sconfig->dst_addr_width); break; case DMA_DEV_TO_MEM: src_burst = convert_burst(sconfig->src_maxburst); src_width = convert_buswidth(sconfig->src_addr_width); dst_burst = convert_burst(sconfig->dst_maxburst ? sconfig->dst_maxburst : 8); dst_width = convert_buswidth(sconfig->dst_addr_width != DMA_SLAVE_BUSWIDTH_UNDEFINED ? sconfig->dst_addr_width : DMA_SLAVE_BUSWIDTH_4_BYTES); break; default: return -EINVAL; } if (src_burst < 0) return src_burst; if (src_width < 0) return src_width; if (dst_burst < 0) return dst_burst; if (dst_width < 0) return dst_width; *p_cfg = DMA_CHAN_CFG_SRC_BURST(src_burst) | DMA_CHAN_CFG_SRC_WIDTH(src_width) | DMA_CHAN_CFG_DST_BURST(dst_burst) | DMA_CHAN_CFG_DST_WIDTH(dst_width); return 0; } static struct dma_async_tx_descriptor *sun6i_dma_prep_dma_memcpy( struct dma_chan *chan, dma_addr_t dest, dma_addr_t src, size_t len, unsigned long flags) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_dma_lli *v_lli; struct sun6i_desc *txd; dma_addr_t p_lli; s8 burst, width; dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %zu. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &dest, &src, len, flags); if (!len) return NULL; txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) { dev_err(sdev->slave.dev, "Failed to alloc lli memory\n"); goto err_txd_free; } v_lli->src = src; v_lli->dst = dest; v_lli->len = len; v_lli->para = NORMAL_WAIT; burst = convert_burst(8); width = convert_buswidth(DMA_SLAVE_BUSWIDTH_4_BYTES); v_lli->cfg |= DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_BURST(burst) | DMA_CHAN_CFG_SRC_WIDTH(width) | DMA_CHAN_CFG_DST_BURST(burst) | DMA_CHAN_CFG_DST_WIDTH(width); sun6i_dma_lli_add(NULL, v_lli, p_lli, txd); sun6i_dma_dump_lli(vchan, v_lli); return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_txd_free: kfree(txd); return NULL; } static struct dma_async_tx_descriptor *sun6i_dma_prep_slave_sg( struct dma_chan *chan, struct scatterlist *sgl, unsigned int sg_len, enum dma_transfer_direction dir, unsigned long flags, void *context) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct dma_slave_config *sconfig = &vchan->cfg; struct sun6i_dma_lli *v_lli, *prev = NULL; struct sun6i_desc *txd; struct scatterlist *sg; dma_addr_t p_lli; u32 lli_cfg; int i, ret; if (!sgl) return NULL; ret = set_config(sdev, sconfig, dir, &lli_cfg); if (ret) { dev_err(chan2dev(chan), "Invalid DMA configuration\n"); return NULL; } txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; for_each_sg(sgl, sg, sg_len, i) { v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) goto err_lli_free; v_lli->len = sg_dma_len(sg); v_lli->para = NORMAL_WAIT; if (dir == DMA_MEM_TO_DEV) { v_lli->src = sg_dma_address(sg); v_lli->dst = sconfig->dst_addr; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_IO_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(vchan->port); dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %u. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &sconfig->dst_addr, &sg_dma_address(sg), sg_dma_len(sg), flags); } else { v_lli->src = sconfig->src_addr; v_lli->dst = sg_dma_address(sg); v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_IO_MODE | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_SRC_DRQ(vchan->port); dev_dbg(chan2dev(chan), "%s; chan: %d, dest: %pad, src: %pad, len: %u. flags: 0x%08lx\n", __func__, vchan->vc.chan.chan_id, &sg_dma_address(sg), &sconfig->src_addr, sg_dma_len(sg), flags); } prev = sun6i_dma_lli_add(prev, v_lli, p_lli, txd); } dev_dbg(chan2dev(chan), "First: %pad\n", &txd->p_lli); for (prev = txd->v_lli; prev; prev = prev->v_lli_next) sun6i_dma_dump_lli(vchan, prev); return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: for (prev = txd->v_lli; prev; prev = prev->v_lli_next) dma_pool_free(sdev->pool, prev, virt_to_phys(prev)); kfree(txd); return NULL; } static struct dma_async_tx_descriptor *sun6i_dma_prep_dma_cyclic( struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len, size_t period_len, enum dma_transfer_direction dir, unsigned long flags) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct dma_slave_config *sconfig = &vchan->cfg; struct sun6i_dma_lli *v_lli, *prev = NULL; struct sun6i_desc *txd; dma_addr_t p_lli; u32 lli_cfg; unsigned int i, periods = buf_len / period_len; int ret; ret = set_config(sdev, sconfig, dir, &lli_cfg); if (ret) { dev_err(chan2dev(chan), "Invalid DMA configuration\n"); return NULL; } txd = kzalloc(sizeof(*txd), GFP_NOWAIT); if (!txd) return NULL; for (i = 0; i < periods; i++) { v_lli = dma_pool_alloc(sdev->pool, GFP_NOWAIT, &p_lli); if (!v_lli) { dev_err(sdev->slave.dev, "Failed to alloc lli memory\n"); goto err_lli_free; } v_lli->len = period_len; v_lli->para = NORMAL_WAIT; if (dir == DMA_MEM_TO_DEV) { v_lli->src = buf_addr + period_len * i; v_lli->dst = sconfig->dst_addr; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_IO_MODE | DMA_CHAN_CFG_SRC_LINEAR_MODE | DMA_CHAN_CFG_SRC_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_DST_DRQ(vchan->port); } else { v_lli->src = sconfig->src_addr; v_lli->dst = buf_addr + period_len * i; v_lli->cfg = lli_cfg | DMA_CHAN_CFG_DST_LINEAR_MODE | DMA_CHAN_CFG_SRC_IO_MODE | DMA_CHAN_CFG_DST_DRQ(DRQ_SDRAM) | DMA_CHAN_CFG_SRC_DRQ(vchan->port); } prev = sun6i_dma_lli_add(prev, v_lli, p_lli, txd); } prev->p_lli_next = txd->p_lli; /* cyclic list */ vchan->cyclic = true; return vchan_tx_prep(&vchan->vc, &txd->vd, flags); err_lli_free: for (prev = txd->v_lli; prev; prev = prev->v_lli_next) dma_pool_free(sdev->pool, prev, virt_to_phys(prev)); kfree(txd); return NULL; } static int sun6i_dma_config(struct dma_chan *chan, struct dma_slave_config *config) { struct sun6i_vchan *vchan = to_sun6i_vchan(chan); memcpy(&vchan->cfg, config, sizeof(*config)); return 0; } static int sun6i_dma_pause(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; dev_dbg(chan2dev(chan), "vchan %p: pause\n", &vchan->vc); if (pchan) { writel(DMA_CHAN_PAUSE_PAUSE, pchan->base + DMA_CHAN_PAUSE); } else { spin_lock(&sdev->lock); list_del_init(&vchan->node); spin_unlock(&sdev->lock); } return 0; } static int sun6i_dma_resume(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; unsigned long flags; dev_dbg(chan2dev(chan), "vchan %p: resume\n", &vchan->vc); spin_lock_irqsave(&vchan->vc.lock, flags); if (pchan) { writel(DMA_CHAN_PAUSE_RESUME, pchan->base + DMA_CHAN_PAUSE); } else if (!list_empty(&vchan->vc.desc_issued)) { spin_lock(&sdev->lock); list_add_tail(&vchan->node, &sdev->pending); spin_unlock(&sdev->lock); } spin_unlock_irqrestore(&vchan->vc.lock, flags); return 0; } static int sun6i_dma_terminate_all(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; unsigned long flags; LIST_HEAD(head); spin_lock(&sdev->lock); list_del_init(&vchan->node); spin_unlock(&sdev->lock); spin_lock_irqsave(&vchan->vc.lock, flags); if (vchan->cyclic) { vchan->cyclic = false; if (pchan && pchan->desc) { struct virt_dma_desc *vd = &pchan->desc->vd; struct virt_dma_chan *vc = &vchan->vc; list_add_tail(&vd->node, &vc->desc_completed); } } vchan_get_all_descriptors(&vchan->vc, &head); if (pchan) { writel(DMA_CHAN_ENABLE_STOP, pchan->base + DMA_CHAN_ENABLE); writel(DMA_CHAN_PAUSE_RESUME, pchan->base + DMA_CHAN_PAUSE); vchan->phy = NULL; pchan->vchan = NULL; pchan->desc = NULL; pchan->done = NULL; } spin_unlock_irqrestore(&vchan->vc.lock, flags); vchan_dma_desc_free_list(&vchan->vc, &head); return 0; } static enum dma_status sun6i_dma_tx_status(struct dma_chan *chan, dma_cookie_t cookie, struct dma_tx_state *state) { struct sun6i_vchan *vchan = to_sun6i_vchan(chan); struct sun6i_pchan *pchan = vchan->phy; struct sun6i_dma_lli *lli; struct virt_dma_desc *vd; struct sun6i_desc *txd; enum dma_status ret; unsigned long flags; size_t bytes = 0; ret = dma_cookie_status(chan, cookie, state); if (ret == DMA_COMPLETE) return ret; spin_lock_irqsave(&vchan->vc.lock, flags); vd = vchan_find_desc(&vchan->vc, cookie); txd = to_sun6i_desc(&vd->tx); if (vd) { for (lli = txd->v_lli; lli != NULL; lli = lli->v_lli_next) bytes += lli->len; } else if (!pchan || !pchan->desc) { bytes = 0; } else { bytes = sun6i_get_chan_size(pchan); } spin_unlock_irqrestore(&vchan->vc.lock, flags); dma_set_residue(state, bytes); return ret; } static void sun6i_dma_issue_pending(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); unsigned long flags; spin_lock_irqsave(&vchan->vc.lock, flags); if (vchan_issue_pending(&vchan->vc)) { spin_lock(&sdev->lock); if (!vchan->phy && list_empty(&vchan->node)) { list_add_tail(&vchan->node, &sdev->pending); tasklet_schedule(&sdev->task); dev_dbg(chan2dev(chan), "vchan %p: issued\n", &vchan->vc); } spin_unlock(&sdev->lock); } else { dev_dbg(chan2dev(chan), "vchan %p: nothing to issue\n", &vchan->vc); } spin_unlock_irqrestore(&vchan->vc.lock, flags); } static void sun6i_dma_free_chan_resources(struct dma_chan *chan) { struct sun6i_dma_dev *sdev = to_sun6i_dma_dev(chan->device); struct sun6i_vchan *vchan = to_sun6i_vchan(chan); unsigned long flags; spin_lock_irqsave(&sdev->lock, flags); list_del_init(&vchan->node); spin_unlock_irqrestore(&sdev->lock, flags); vchan_free_chan_resources(&vchan->vc); } static struct dma_chan *sun6i_dma_of_xlate(struct of_phandle_args *dma_spec, struct of_dma *ofdma) { struct sun6i_dma_dev *sdev = ofdma->of_dma_data; struct sun6i_vchan *vchan; struct dma_chan *chan; u8 port = dma_spec->args[0]; if (port > sdev->cfg->nr_max_requests) return NULL; chan = dma_get_any_slave_channel(&sdev->slave); if (!chan) return NULL; vchan = to_sun6i_vchan(chan); vchan->port = port; return chan; } static inline void sun6i_kill_tasklet(struct sun6i_dma_dev *sdev) { /* Disable all interrupts from DMA */ writel(0, sdev->base + DMA_IRQ_EN(0)); writel(0, sdev->base + DMA_IRQ_EN(1)); /* Prevent spurious interrupts from scheduling the tasklet */ atomic_inc(&sdev->tasklet_shutdown); /* Make sure we won't have any further interrupts */ devm_free_irq(sdev->slave.dev, sdev->irq, sdev); /* Actually prevent the tasklet from being scheduled */ tasklet_kill(&sdev->task); } static inline void sun6i_dma_free(struct sun6i_dma_dev *sdev) { int i; for (i = 0; i < sdev->cfg->nr_max_vchans; i++) { struct sun6i_vchan *vchan = &sdev->vchans[i]; list_del(&vchan->vc.chan.device_node); tasklet_kill(&vchan->vc.task); } } /* * For A31: * * There's 16 physical channels that can work in parallel. * * However we have 30 different endpoints for our requests. * * Since the channels are able to handle only an unidirectional * transfer, we need to allocate more virtual channels so that * everyone can grab one channel. * * Some devices can't work in both direction (mostly because it * wouldn't make sense), so we have a bit fewer virtual channels than * 2 channels per endpoints. */ static struct sun6i_dma_config sun6i_a31_dma_cfg = { .nr_max_channels = 16, .nr_max_requests = 30, .nr_max_vchans = 53, }; /* * The A23 only has 8 physical channels, a maximum DRQ port id of 24, * and a total of 37 usable source and destination endpoints. */ static struct sun6i_dma_config sun8i_a23_dma_cfg = { .nr_max_channels = 8, .nr_max_requests = 24, .nr_max_vchans = 37, }; /* * The H3 has 12 physical channels, a maximum DRQ port id of 27, * and a total of 34 usable source and destination endpoints. */ static struct sun6i_dma_config sun8i_h3_dma_cfg = { .nr_max_channels = 12, .nr_max_requests = 27, .nr_max_vchans = 34, }; static const struct of_device_id sun6i_dma_match[] = { { .compatible = "allwinner,sun6i-a31-dma", .data = &sun6i_a31_dma_cfg }, { .compatible = "allwinner,sun8i-a23-dma", .data = &sun8i_a23_dma_cfg }, { .compatible = "allwinner,sun8i-h3-dma", .data = &sun8i_h3_dma_cfg }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, sun6i_dma_match); static int sun6i_dma_probe(struct platform_device *pdev) { const struct of_device_id *device; struct sun6i_dma_dev *sdc; struct resource *res; int ret, i; sdc = devm_kzalloc(&pdev->dev, sizeof(*sdc), GFP_KERNEL); if (!sdc) return -ENOMEM; device = of_match_device(sun6i_dma_match, &pdev->dev); if (!device) return -ENODEV; sdc->cfg = device->data; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); sdc->base = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(sdc->base)) return PTR_ERR(sdc->base); sdc->irq = platform_get_irq(pdev, 0); if (sdc->irq < 0) { dev_err(&pdev->dev, "Cannot claim IRQ\n"); return sdc->irq; } sdc->clk = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(sdc->clk)) { dev_err(&pdev->dev, "No clock specified\n"); return PTR_ERR(sdc->clk); } sdc->rstc = devm_reset_control_get(&pdev->dev, NULL); if (IS_ERR(sdc->rstc)) { dev_err(&pdev->dev, "No reset controller specified\n"); return PTR_ERR(sdc->rstc); } sdc->pool = dmam_pool_create(dev_name(&pdev->dev), &pdev->dev, sizeof(struct sun6i_dma_lli), 4, 0); if (!sdc->pool) { dev_err(&pdev->dev, "No memory for descriptors dma pool\n"); return -ENOMEM; } platform_set_drvdata(pdev, sdc); INIT_LIST_HEAD(&sdc->pending); spin_lock_init(&sdc->lock); dma_cap_set(DMA_PRIVATE, sdc->slave.cap_mask); dma_cap_set(DMA_MEMCPY, sdc->slave.cap_mask); dma_cap_set(DMA_SLAVE, sdc->slave.cap_mask); dma_cap_set(DMA_CYCLIC, sdc->slave.cap_mask); INIT_LIST_HEAD(&sdc->slave.channels); sdc->slave.device_free_chan_resources = sun6i_dma_free_chan_resources; sdc->slave.device_tx_status = sun6i_dma_tx_status; sdc->slave.device_issue_pending = sun6i_dma_issue_pending; sdc->slave.device_prep_slave_sg = sun6i_dma_prep_slave_sg; sdc->slave.device_prep_dma_memcpy = sun6i_dma_prep_dma_memcpy; sdc->slave.device_prep_dma_cyclic = sun6i_dma_prep_dma_cyclic; sdc->slave.copy_align = DMAENGINE_ALIGN_4_BYTES; sdc->slave.device_config = sun6i_dma_config; sdc->slave.device_pause = sun6i_dma_pause; sdc->slave.device_resume = sun6i_dma_resume; sdc->slave.device_terminate_all = sun6i_dma_terminate_all; sdc->slave.src_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | BIT(DMA_SLAVE_BUSWIDTH_4_BYTES); sdc->slave.dst_addr_widths = BIT(DMA_SLAVE_BUSWIDTH_1_BYTE) | BIT(DMA_SLAVE_BUSWIDTH_2_BYTES) | BIT(DMA_SLAVE_BUSWIDTH_4_BYTES); sdc->slave.directions = BIT(DMA_DEV_TO_MEM) | BIT(DMA_MEM_TO_DEV); sdc->slave.residue_granularity = DMA_RESIDUE_GRANULARITY_BURST; sdc->slave.dev = &pdev->dev; sdc->pchans = devm_kcalloc(&pdev->dev, sdc->cfg->nr_max_channels, sizeof(struct sun6i_pchan), GFP_KERNEL); if (!sdc->pchans) return -ENOMEM; sdc->vchans = devm_kcalloc(&pdev->dev, sdc->cfg->nr_max_vchans, sizeof(struct sun6i_vchan), GFP_KERNEL); if (!sdc->vchans) return -ENOMEM; tasklet_init(&sdc->task, sun6i_dma_tasklet, (unsigned long)sdc); for (i = 0; i < sdc->cfg->nr_max_channels; i++) { struct sun6i_pchan *pchan = &sdc->pchans[i]; pchan->idx = i; pchan->base = sdc->base + 0x100 + i * 0x40; } for (i = 0; i < sdc->cfg->nr_max_vchans; i++) { struct sun6i_vchan *vchan = &sdc->vchans[i]; INIT_LIST_HEAD(&vchan->node); vchan->vc.desc_free = sun6i_dma_free_desc; vchan_init(&vchan->vc, &sdc->slave); } ret = reset_control_deassert(sdc->rstc); if (ret) { dev_err(&pdev->dev, "Couldn't deassert the device from reset\n"); goto err_chan_free; } ret = clk_prepare_enable(sdc->clk); if (ret) { dev_err(&pdev->dev, "Couldn't enable the clock\n"); goto err_reset_assert; } ret = devm_request_irq(&pdev->dev, sdc->irq, sun6i_dma_interrupt, 0, dev_name(&pdev->dev), sdc); if (ret) { dev_err(&pdev->dev, "Cannot request IRQ\n"); goto err_clk_disable; } ret = dma_async_device_register(&sdc->slave); if (ret) { dev_warn(&pdev->dev, "Failed to register DMA engine device\n"); goto err_irq_disable; } ret = of_dma_controller_register(pdev->dev.of_node, sun6i_dma_of_xlate, sdc); if (ret) { dev_err(&pdev->dev, "of_dma_controller_register failed\n"); goto err_dma_unregister; } /* * sun8i variant requires us to toggle a dma gating register, * as seen in Allwinner's SDK. This register is not documented * in the A23 user manual. */ if (of_device_is_compatible(pdev->dev.of_node, "allwinner,sun8i-a23-dma")) writel(SUN8I_DMA_GATE_ENABLE, sdc->base + SUN8I_DMA_GATE); return 0; err_dma_unregister: dma_async_device_unregister(&sdc->slave); err_irq_disable: sun6i_kill_tasklet(sdc); err_clk_disable: clk_disable_unprepare(sdc->clk); err_reset_assert: reset_control_assert(sdc->rstc); err_chan_free: sun6i_dma_free(sdc); return ret; } static int sun6i_dma_remove(struct platform_device *pdev) { struct sun6i_dma_dev *sdc = platform_get_drvdata(pdev); of_dma_controller_free(pdev->dev.of_node); dma_async_device_unregister(&sdc->slave); sun6i_kill_tasklet(sdc); clk_disable_unprepare(sdc->clk); reset_control_assert(sdc->rstc); sun6i_dma_free(sdc); return 0; } static struct platform_driver sun6i_dma_driver = { .probe = sun6i_dma_probe, .remove = sun6i_dma_remove, .driver = { .name = "sun6i-dma", .of_match_table = sun6i_dma_match, }, }; module_platform_driver(sun6i_dma_driver); MODULE_DESCRIPTION("Allwinner A31 DMA Controller Driver"); MODULE_AUTHOR("Sugar <shuge@allwinnertech.com>"); MODULE_AUTHOR("Maxime Ripard <maxime.ripard@free-electrons.com>"); MODULE_LICENSE("GPL");
/* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 21-03-2015 */ /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = VTTCue || root.VTTCue; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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. */ (function(root) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, decoder) { this.window = window; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new self.window.VTTRegion(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new self.window.VTTCue(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this)); // If we're in node require encoding-indexes and attach it to the global. if (typeof module !== "undefined" && module.exports) { this["encoding-indexes"] = require("./encoding-indexes.js")["encoding-indexes"]; } (function(global) { 'use strict'; // // Utilities // /** * @param {number} a The number to test. * @param {number} min The minimum value in the range, inclusive. * @param {number} max The maximum value in the range, inclusive. * @return {boolean} True if a >= min and a <= max. */ function inRange(a, min, max) { return min <= a && a <= max; } /** * @param {number} n The numerator. * @param {number} d The denominator. * @return {number} The result of the integer division of n by d. */ function div(n, d) { return Math.floor(n / d); } // // Implementation of Encoding specification // http://dvcs.w3.org/hg/encoding/raw-file/tip/Overview.html // // // 3. Terminology // // // 4. Encodings // /** @const */ var EOF_byte = -1; /** @const */ var EOF_code_point = -1; /** * @constructor * @param {Uint8Array} bytes Array of bytes that provide the stream. */ function ByteInputStream(bytes) { /** @type {number} */ var pos = 0; /** * @this {ByteInputStream} * @return {number} Get the next byte from the stream. */ this.get = function() { return (pos >= bytes.length) ? EOF_byte : Number(bytes[pos]); }; /** @param {number} n Number (positive or negative) by which to * offset the byte pointer. */ this.offset = function(n) { pos += n; if (pos < 0) { throw new Error('Seeking past start of the buffer'); } if (pos > bytes.length) { throw new Error('Seeking past EOF'); } }; /** * @param {Array.<number>} test Array of bytes to compare against. * @return {boolean} True if the start of the stream matches the test * bytes. */ this.match = function(test) { if (test.length > pos + bytes.length) { return false; } var i; for (i = 0; i < test.length; i += 1) { if (Number(bytes[pos + i]) !== test[i]) { return false; } } return true; }; } /** * @constructor * @param {Array.<number>} bytes The array to write bytes into. */ function ByteOutputStream(bytes) { /** @type {number} */ var pos = 0; /** * @param {...number} var_args The byte or bytes to emit into the stream. * @return {number} The last byte emitted. */ this.emit = function(var_args) { /** @type {number} */ var last = EOF_byte; var i; for (i = 0; i < arguments.length; ++i) { last = Number(arguments[i]); bytes[pos++] = last; } return last; }; } /** * @constructor * @param {string} string The source of code units for the stream. */ function CodePointInputStream(string) { /** * @param {string} string Input string of UTF-16 code units. * @return {Array.<number>} Code points. */ function stringToCodePoints(string) { /** @type {Array.<number>} */ var cps = []; // Based on http://www.w3.org/TR/WebIDL/#idl-DOMString var i = 0, n = string.length; while (i < string.length) { var c = string.charCodeAt(i); if (!inRange(c, 0xD800, 0xDFFF)) { cps.push(c); } else if (inRange(c, 0xDC00, 0xDFFF)) { cps.push(0xFFFD); } else { // (inRange(cu, 0xD800, 0xDBFF)) if (i === n - 1) { cps.push(0xFFFD); } else { var d = string.charCodeAt(i + 1); if (inRange(d, 0xDC00, 0xDFFF)) { var a = c & 0x3FF; var b = d & 0x3FF; i += 1; cps.push(0x10000 + (a << 10) + b); } else { cps.push(0xFFFD); } } } i += 1; } return cps; } /** @type {number} */ var pos = 0; /** @type {Array.<number>} */ var cps = stringToCodePoints(string); /** @param {number} n The number of bytes (positive or negative) * to advance the code point pointer by.*/ this.offset = function(n) { pos += n; if (pos < 0) { throw new Error('Seeking past start of the buffer'); } if (pos > cps.length) { throw new Error('Seeking past EOF'); } }; /** @return {number} Get the next code point from the stream. */ this.get = function() { if (pos >= cps.length) { return EOF_code_point; } return cps[pos]; }; } /** * @constructor */ function CodePointOutputStream() { /** @type {string} */ var string = ''; /** @return {string} The accumulated string. */ this.string = function() { return string; }; /** @param {number} c The code point to encode into the stream. */ this.emit = function(c) { if (c <= 0xFFFF) { string += String.fromCharCode(c); } else { c -= 0x10000; string += String.fromCharCode(0xD800 + ((c >> 10) & 0x3ff)); string += String.fromCharCode(0xDC00 + (c & 0x3ff)); } }; } /** * @constructor * @param {string} message Description of the error. */ function EncodingError(message) { this.name = 'EncodingError'; this.message = message; this.code = 0; } EncodingError.prototype = Error.prototype; /** * @param {boolean} fatal If true, decoding errors raise an exception. * @param {number=} opt_code_point Override the standard fallback code point. * @return {number} The code point to insert on a decoding error. */ function decoderError(fatal, opt_code_point) { if (fatal) { throw new EncodingError('Decoder error'); } return opt_code_point || 0xFFFD; } /** * @param {number} code_point The code point that could not be encoded. * @return {number} Always throws, no value is actually returned. */ function encoderError(code_point) { throw new EncodingError('The code point ' + code_point + ' could not be encoded.'); } /** * @param {string} label The encoding label. * @return {?{name:string,labels:Array.<string>}} */ function getEncoding(label) { label = String(label).trim().toLowerCase(); if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) { return label_to_encoding[label]; } return null; } /** @type {Array.<{encodings: Array.<{name:string,labels:Array.<string>}>, * heading: string}>} */ var encodings = [ { "encodings": [ { "labels": [ "unicode-1-1-utf-8", "utf-8", "utf8" ], "name": "utf-8" } ], "heading": "The Encoding" }, { "encodings": [ { "labels": [ "866", "cp866", "csibm866", "ibm866" ], "name": "ibm866" }, { "labels": [ "csisolatin2", "iso-8859-2", "iso-ir-101", "iso8859-2", "iso88592", "iso_8859-2", "iso_8859-2:1987", "l2", "latin2" ], "name": "iso-8859-2" }, { "labels": [ "csisolatin3", "iso-8859-3", "iso-ir-109", "iso8859-3", "iso88593", "iso_8859-3", "iso_8859-3:1988", "l3", "latin3" ], "name": "iso-8859-3" }, { "labels": [ "csisolatin4", "iso-8859-4", "iso-ir-110", "iso8859-4", "iso88594", "iso_8859-4", "iso_8859-4:1988", "l4", "latin4" ], "name": "iso-8859-4" }, { "labels": [ "csisolatincyrillic", "cyrillic", "iso-8859-5", "iso-ir-144", "iso8859-5", "iso88595", "iso_8859-5", "iso_8859-5:1988" ], "name": "iso-8859-5" }, { "labels": [ "arabic", "asmo-708", "csiso88596e", "csiso88596i", "csisolatinarabic", "ecma-114", "iso-8859-6", "iso-8859-6-e", "iso-8859-6-i", "iso-ir-127", "iso8859-6", "iso88596", "iso_8859-6", "iso_8859-6:1987" ], "name": "iso-8859-6" }, { "labels": [ "csisolatingreek", "ecma-118", "elot_928", "greek", "greek8", "iso-8859-7", "iso-ir-126", "iso8859-7", "iso88597", "iso_8859-7", "iso_8859-7:1987", "sun_eu_greek" ], "name": "iso-8859-7" }, { "labels": [ "csiso88598e", "csisolatinhebrew", "hebrew", "iso-8859-8", "iso-8859-8-e", "iso-ir-138", "iso8859-8", "iso88598", "iso_8859-8", "iso_8859-8:1988", "visual" ], "name": "iso-8859-8" }, { "labels": [ "csiso88598i", "iso-8859-8-i", "logical" ], "name": "iso-8859-8-i" }, { "labels": [ "csisolatin6", "iso-8859-10", "iso-ir-157", "iso8859-10", "iso885910", "l6", "latin6" ], "name": "iso-8859-10" }, { "labels": [ "iso-8859-13", "iso8859-13", "iso885913" ], "name": "iso-8859-13" }, { "labels": [ "iso-8859-14", "iso8859-14", "iso885914" ], "name": "iso-8859-14" }, { "labels": [ "csisolatin9", "iso-8859-15", "iso8859-15", "iso885915", "iso_8859-15", "l9" ], "name": "iso-8859-15" }, { "labels": [ "iso-8859-16" ], "name": "iso-8859-16" }, { "labels": [ "cskoi8r", "koi", "koi8", "koi8-r", "koi8_r" ], "name": "koi8-r" }, { "labels": [ "koi8-u" ], "name": "koi8-u" }, { "labels": [ "csmacintosh", "mac", "macintosh", "x-mac-roman" ], "name": "macintosh" }, { "labels": [ "dos-874", "iso-8859-11", "iso8859-11", "iso885911", "tis-620", "windows-874" ], "name": "windows-874" }, { "labels": [ "cp1250", "windows-1250", "x-cp1250" ], "name": "windows-1250" }, { "labels": [ "cp1251", "windows-1251", "x-cp1251" ], "name": "windows-1251" }, { "labels": [ "ansi_x3.4-1968", "ascii", "cp1252", "cp819", "csisolatin1", "ibm819", "iso-8859-1", "iso-ir-100", "iso8859-1", "iso88591", "iso_8859-1", "iso_8859-1:1987", "l1", "latin1", "us-ascii", "windows-1252", "x-cp1252" ], "name": "windows-1252" }, { "labels": [ "cp1253", "windows-1253", "x-cp1253" ], "name": "windows-1253" }, { "labels": [ "cp1254", "csisolatin5", "iso-8859-9", "iso-ir-148", "iso8859-9", "iso88599", "iso_8859-9", "iso_8859-9:1989", "l5", "latin5", "windows-1254", "x-cp1254" ], "name": "windows-1254" }, { "labels": [ "cp1255", "windows-1255", "x-cp1255" ], "name": "windows-1255" }, { "labels": [ "cp1256", "windows-1256", "x-cp1256" ], "name": "windows-1256" }, { "labels": [ "cp1257", "windows-1257", "x-cp1257" ], "name": "windows-1257" }, { "labels": [ "cp1258", "windows-1258", "x-cp1258" ], "name": "windows-1258" }, { "labels": [ "x-mac-cyrillic", "x-mac-ukrainian" ], "name": "x-mac-cyrillic" } ], "heading": "Legacy single-byte encodings" }, { "encodings": [ { "labels": [ "chinese", "csgb2312", "csiso58gb231280", "gb18030", "gb2312", "gb_2312", "gb_2312-80", "gbk", "iso-ir-58", "x-gbk" ], "name": "gb18030" }, { "labels": [ "hz-gb-2312" ], "name": "hz-gb-2312" } ], "heading": "Legacy multi-byte Chinese (simplified) encodings" }, { "encodings": [ { "labels": [ "big5", "big5-hkscs", "cn-big5", "csbig5", "x-x-big5" ], "name": "big5" } ], "heading": "Legacy multi-byte Chinese (traditional) encodings" }, { "encodings": [ { "labels": [ "cseucpkdfmtjapanese", "euc-jp", "x-euc-jp" ], "name": "euc-jp" }, { "labels": [ "csiso2022jp", "iso-2022-jp" ], "name": "iso-2022-jp" }, { "labels": [ "csshiftjis", "ms_kanji", "shift-jis", "shift_jis", "sjis", "windows-31j", "x-sjis" ], "name": "shift_jis" } ], "heading": "Legacy multi-byte Japanese encodings" }, { "encodings": [ { "labels": [ "cseuckr", "csksc56011987", "euc-kr", "iso-ir-149", "korean", "ks_c_5601-1987", "ks_c_5601-1989", "ksc5601", "ksc_5601", "windows-949" ], "name": "euc-kr" } ], "heading": "Legacy multi-byte Korean encodings" }, { "encodings": [ { "labels": [ "csiso2022kr", "iso-2022-cn", "iso-2022-cn-ext", "iso-2022-kr" ], "name": "replacement" }, { "labels": [ "utf-16be" ], "name": "utf-16be" }, { "labels": [ "utf-16", "utf-16le" ], "name": "utf-16le" }, { "labels": [ "x-user-defined" ], "name": "x-user-defined" } ], "heading": "Legacy miscellaneous encodings" } ]; var name_to_encoding = {}; var label_to_encoding = {}; encodings.forEach(function(category) { category['encodings'].forEach(function(encoding) { name_to_encoding[encoding['name']] = encoding; encoding['labels'].forEach(function(label) { label_to_encoding[label] = encoding; }); }); }); // // 5. Indexes // /** * @param {number} pointer The |pointer| to search for. * @param {Array.<?number>|undefined} index The |index| to search within. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in |index|. */ function indexCodePointFor(pointer, index) { if (!index) return null; return index[pointer] || null; } /** * @param {number} code_point The |code point| to search for. * @param {Array.<?number>} index The |index| to search within. * @return {?number} The first pointer corresponding to |code point| in * |index|, or null if |code point| is not in |index|. */ function indexPointerFor(code_point, index) { var pointer = index.indexOf(code_point); return pointer === -1 ? null : pointer; } /** * @param {string} name Name of the index. * @return {(Array.<number>|Array.<Array.<number>>)} * */ function index(name) { if (!('encoding-indexes' in global)) throw new Error("Indexes missing. Did you forget to include encoding-indexes.js?"); return global['encoding-indexes'][name]; } /** * @param {number} pointer The |pointer| to search for in the gb18030 index. * @return {?number} The code point corresponding to |pointer| in |index|, * or null if |code point| is not in the gb18030 index. */ function indexGB18030CodePointFor(pointer) { if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) { return null; } var /** @type {number} */ offset = 0, /** @type {number} */ code_point_offset = 0, /** @type {Array.<Array.<number>>} */ idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { var entry = idx[i]; if (entry[0] <= pointer) { offset = entry[0]; code_point_offset = entry[1]; } else { break; } } return code_point_offset + pointer - offset; } /** * @param {number} code_point The |code point| to locate in the gb18030 index. * @return {number} The first pointer corresponding to |code point| in the * gb18030 index. */ function indexGB18030PointerFor(code_point) { var /** @type {number} */ offset = 0, /** @type {number} */ pointer_offset = 0, /** @type {Array.<Array.<number>>} */ idx = index('gb18030'); var i; for (i = 0; i < idx.length; ++i) { var entry = idx[i]; if (entry[1] <= code_point) { offset = entry[1]; pointer_offset = entry[0]; } else { break; } } return pointer_offset + code_point - offset; } // // 7. API // /** @const */ var DEFAULT_ENCODING = 'utf-8'; // 7.1 Interface TextDecoder /** * @constructor * @param {string=} opt_encoding The label of the encoding; * defaults to 'utf-8'. * @param {{fatal: boolean}=} options */ function TextDecoder(opt_encoding, options) { if (!(this instanceof TextDecoder)) { return new TextDecoder(opt_encoding, options); } opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING; options = Object(options); /** @private */ this._encoding = getEncoding(opt_encoding); if (this._encoding === null || this._encoding.name === 'replacement') throw new TypeError('Unknown encoding: ' + opt_encoding); if (!this._encoding.getDecoder) throw new Error('Decoder not present. Did you forget to include encoding-indexes.js?'); /** @private @type {boolean} */ this._streaming = false; /** @private @type {boolean} */ this._BOMseen = false; /** @private */ this._decoder = null; /** @private @type {{fatal: boolean}=} */ this._options = { fatal: Boolean(options.fatal) }; if (Object.defineProperty) { Object.defineProperty( this, 'encoding', { get: function() { return this._encoding.name; } }); } else { this.encoding = this._encoding.name; } return this; } // TODO: Issue if input byte stream is offset by decoder // TODO: BOM detection will not work if stream header spans multiple calls // (last N bytes of previous stream may need to be retained?) TextDecoder.prototype = { /** * @param {ArrayBufferView=} opt_view The buffer of bytes to decode. * @param {{stream: boolean}=} options */ decode: function decode(opt_view, options) { if (opt_view && !('buffer' in opt_view && 'byteOffset' in opt_view && 'byteLength' in opt_view)) { throw new TypeError('Expected ArrayBufferView'); } else if (!opt_view) { opt_view = new Uint8Array(0); } options = Object(options); if (!this._streaming) { this._decoder = this._encoding.getDecoder(this._options); this._BOMseen = false; } this._streaming = Boolean(options.stream); var bytes = new Uint8Array(opt_view.buffer, opt_view.byteOffset, opt_view.byteLength); var input_stream = new ByteInputStream(bytes); var output_stream = new CodePointOutputStream(); /** @type {number} */ var code_point; while (input_stream.get() !== EOF_byte) { code_point = this._decoder.decode(input_stream); if (code_point !== null && code_point !== EOF_code_point) { output_stream.emit(code_point); } } if (!this._streaming) { do { code_point = this._decoder.decode(input_stream); if (code_point !== null && code_point !== EOF_code_point) { output_stream.emit(code_point); } } while (code_point !== EOF_code_point && input_stream.get() != EOF_byte); this._decoder = null; } var result = output_stream.string(); if (!this._BOMseen && result.length) { this._BOMseen = true; if (['utf-8', 'utf-16le', 'utf-16be'].indexOf(this.encoding) !== -1 && result.charCodeAt(0) === 0xFEFF) { result = result.substring(1); } } return result; } }; // 7.2 Interface TextEncoder /** * @constructor * @param {string=} opt_encoding The label of the encoding; * defaults to 'utf-8'. * @param {{fatal: boolean}=} options */ function TextEncoder(opt_encoding, options) { if (!(this instanceof TextEncoder)) { return new TextEncoder(opt_encoding, options); } opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING; options = Object(options); /** @private */ this._encoding = getEncoding(opt_encoding); var allowLegacyEncoding = options.NONSTANDARD_allowLegacyEncoding; var isLegacyEncoding = (this._encoding.name !== 'utf-8' && this._encoding.name !== 'utf-16le' && this._encoding.name !== 'utf-16be'); if (this._encoding === null || (isLegacyEncoding && !allowLegacyEncoding)) throw new TypeError('Unknown encoding: ' + opt_encoding); if (!this._encoding.getEncoder) throw new Error('Encoder not present. Did you forget to include encoding-indexes.js?'); /** @private @type {boolean} */ this._streaming = false; /** @private */ this._encoder = null; /** @private @type {{fatal: boolean}=} */ this._options = { fatal: Boolean(options.fatal) }; if (Object.defineProperty) { Object.defineProperty( this, 'encoding', { get: function() { return this._encoding.name; } }); } else { this.encoding = this._encoding.name; } return this; } TextEncoder.prototype = { /** * @param {string=} opt_string The string to encode. * @param {{stream: boolean}=} options */ encode: function encode(opt_string, options) { opt_string = opt_string ? String(opt_string) : ''; options = Object(options); // TODO: any options? if (!this._streaming) { this._encoder = this._encoding.getEncoder(this._options); } this._streaming = Boolean(options.stream); var bytes = []; var output_stream = new ByteOutputStream(bytes); var input_stream = new CodePointInputStream(opt_string); while (input_stream.get() !== EOF_code_point) { this._encoder.encode(output_stream, input_stream); } if (!this._streaming) { /** @type {number} */ var last_byte; do { last_byte = this._encoder.encode(output_stream, input_stream); } while (last_byte !== EOF_byte); this._encoder = null; } return new Uint8Array(bytes); } }; // // 8. The encoding // // 8.1 utf-8 /** * @constructor * @param {{fatal: boolean}} options */ function UTF8Decoder(options) { var fatal = options.fatal; var /** @type {number} */ utf8_code_point = 0, /** @type {number} */ utf8_bytes_needed = 0, /** @type {number} */ utf8_bytes_seen = 0, /** @type {number} */ utf8_lower_boundary = 0; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { if (utf8_bytes_needed !== 0) { return decoderError(fatal); } return EOF_code_point; } byte_pointer.offset(1); if (utf8_bytes_needed === 0) { if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0xC2, 0xDF)) { utf8_bytes_needed = 1; utf8_lower_boundary = 0x80; utf8_code_point = bite - 0xC0; } else if (inRange(bite, 0xE0, 0xEF)) { utf8_bytes_needed = 2; utf8_lower_boundary = 0x800; utf8_code_point = bite - 0xE0; } else if (inRange(bite, 0xF0, 0xF4)) { utf8_bytes_needed = 3; utf8_lower_boundary = 0x10000; utf8_code_point = bite - 0xF0; } else { return decoderError(fatal); } utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed); return null; } if (!inRange(bite, 0x80, 0xBF)) { utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; byte_pointer.offset(-1); return decoderError(fatal); } utf8_bytes_seen += 1; utf8_code_point = utf8_code_point + (bite - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen); if (utf8_bytes_seen !== utf8_bytes_needed) { return null; } var code_point = utf8_code_point; var lower_boundary = utf8_lower_boundary; utf8_code_point = 0; utf8_bytes_needed = 0; utf8_bytes_seen = 0; utf8_lower_boundary = 0; if (inRange(code_point, lower_boundary, 0x10FFFF) && !inRange(code_point, 0xD800, 0xDFFF)) { return code_point; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function UTF8Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { /** @type {number} */ var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0xD800, 0xDFFF)) { return encoderError(code_point); } if (inRange(code_point, 0x0000, 0x007f)) { return output_byte_stream.emit(code_point); } var count, offset; if (inRange(code_point, 0x0080, 0x07FF)) { count = 1; offset = 0xC0; } else if (inRange(code_point, 0x0800, 0xFFFF)) { count = 2; offset = 0xE0; } else if (inRange(code_point, 0x10000, 0x10FFFF)) { count = 3; offset = 0xF0; } var result = output_byte_stream.emit( div(code_point, Math.pow(64, count)) + offset); while (count > 0) { var temp = div(code_point, Math.pow(64, count - 1)); result = output_byte_stream.emit(0x80 + (temp % 64)); count -= 1; } return result; }; } /** @param {{fatal: boolean}} options */ name_to_encoding['utf-8'].getEncoder = function(options) { return new UTF8Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-8'].getDecoder = function(options) { return new UTF8Decoder(options); }; // // 9. Legacy single-byte encodings // /** * @constructor * @param {Array.<number>} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteDecoder(index, options) { var fatal = options.fatal; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { return EOF_code_point; } byte_pointer.offset(1); if (inRange(bite, 0x00, 0x7F)) { return bite; } var code_point = index[bite - 0x80]; if (code_point === null) { return decoderError(fatal); } return code_point; }; } /** * @constructor * @param {Array.<?number>} index The encoding index. * @param {{fatal: boolean}} options */ function SingleByteEncoder(index, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index); if (pointer === null) { encoderError(code_point); } return output_byte_stream.emit(pointer + 0x80); }; } (function() { if (!('encoding-indexes' in global)) return; encodings.forEach(function(category) { if (category['heading'] !== 'Legacy single-byte encodings') return; category['encodings'].forEach(function(encoding) { var idx = index(encoding['name']); /** @param {{fatal: boolean}} options */ encoding.getDecoder = function(options) { return new SingleByteDecoder(idx, options); }; /** @param {{fatal: boolean}} options */ encoding.getEncoder = function(options) { return new SingleByteEncoder(idx, options); }; }); }); }()); // // 10. Legacy multi-byte Chinese (simplified) encodings // // 9.1 gb18030 /** * @constructor * @param {{fatal: boolean}} options */ function GB18030Decoder(options) { var fatal = options.fatal; var /** @type {number} */ gb18030_first = 0x00, /** @type {number} */ gb18030_second = 0x00, /** @type {number} */ gb18030_third = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && gb18030_first === 0x00 && gb18030_second === 0x00 && gb18030_third === 0x00) { return EOF_code_point; } if (bite === EOF_byte && (gb18030_first !== 0x00 || gb18030_second !== 0x00 || gb18030_third !== 0x00)) { gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; decoderError(fatal); } byte_pointer.offset(1); var code_point; if (gb18030_third !== 0x00) { code_point = null; if (inRange(bite, 0x30, 0x39)) { code_point = indexGB18030CodePointFor( (((gb18030_first - 0x81) * 10 + (gb18030_second - 0x30)) * 126 + (gb18030_third - 0x81)) * 10 + bite - 0x30); } gb18030_first = 0x00; gb18030_second = 0x00; gb18030_third = 0x00; if (code_point === null) { byte_pointer.offset(-3); return decoderError(fatal); } return code_point; } if (gb18030_second !== 0x00) { if (inRange(bite, 0x81, 0xFE)) { gb18030_third = bite; return null; } byte_pointer.offset(-2); gb18030_first = 0x00; gb18030_second = 0x00; return decoderError(fatal); } if (gb18030_first !== 0x00) { if (inRange(bite, 0x30, 0x39)) { gb18030_second = bite; return null; } var lead = gb18030_first; var pointer = null; gb18030_first = 0x00; var offset = bite < 0x7F ? 0x40 : 0x41; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) { pointer = (lead - 0x81) * 190 + (bite - offset); } code_point = pointer === null ? null : indexCodePointFor(pointer, index('gb18030')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === 0x80) { return 0x20AC; } if (inRange(bite, 0x81, 0xFE)) { gb18030_first = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function GB18030Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('gb18030')); if (pointer !== null) { var lead = div(pointer, 190) + 0x81; var trail = pointer % 190; var offset = trail < 0x3F ? 0x40 : 0x41; return output_byte_stream.emit(lead, trail + offset); } pointer = indexGB18030PointerFor(code_point); var byte1 = div(div(div(pointer, 10), 126), 10); pointer = pointer - byte1 * 10 * 126 * 10; var byte2 = div(div(pointer, 10), 126); pointer = pointer - byte2 * 10 * 126; var byte3 = div(pointer, 10); var byte4 = pointer - byte3 * 10; return output_byte_stream.emit(byte1 + 0x81, byte2 + 0x30, byte3 + 0x81, byte4 + 0x30); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['gb18030'].getEncoder = function(options) { return new GB18030Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['gb18030'].getDecoder = function(options) { return new GB18030Decoder(options); }; // 10.2 hz-gb-2312 /** * @constructor * @param {{fatal: boolean}} options */ function HZGB2312Decoder(options) { var fatal = options.fatal; var /** @type {boolean} */ hzgb2312 = false, /** @type {number} */ hzgb2312_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && hzgb2312_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && hzgb2312_lead !== 0x00) { hzgb2312_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (hzgb2312_lead === 0x7E) { hzgb2312_lead = 0x00; if (bite === 0x7B) { hzgb2312 = true; return null; } if (bite === 0x7D) { hzgb2312 = false; return null; } if (bite === 0x7E) { return 0x007E; } if (bite === 0x0A) { return null; } byte_pointer.offset(-1); return decoderError(fatal); } if (hzgb2312_lead !== 0x00) { var lead = hzgb2312_lead; hzgb2312_lead = 0x00; var code_point = null; if (inRange(bite, 0x21, 0x7E)) { code_point = indexCodePointFor((lead - 1) * 190 + (bite + 0x3F), index('gb18030')); } if (bite === 0x0A) { hzgb2312 = false; } if (code_point === null) { return decoderError(fatal); } return code_point; } if (bite === 0x7E) { hzgb2312_lead = 0x7E; return null; } if (hzgb2312) { if (inRange(bite, 0x20, 0x7F)) { hzgb2312_lead = bite; return null; } if (bite === 0x0A) { hzgb2312 = false; } return decoderError(fatal); } if (inRange(bite, 0x00, 0x7F)) { return bite; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function HZGB2312Encoder(options) { var fatal = options.fatal; /** @type {boolean} */ var hzgb2312 = false; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F) && hzgb2312) { code_point_pointer.offset(-1); hzgb2312 = false; return output_byte_stream.emit(0x7E, 0x7D); } if (code_point === 0x007E) { return output_byte_stream.emit(0x7E, 0x7E); } if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (!hzgb2312) { code_point_pointer.offset(-1); hzgb2312 = true; return output_byte_stream.emit(0x7E, 0x7B); } var pointer = indexPointerFor(code_point, index('gb18030')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 190) + 1; var trail = pointer % 190 - 0x3F; if (!inRange(lead, 0x21, 0x7E) || !inRange(trail, 0x21, 0x7E)) { return encoderError(code_point); } return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['hz-gb-2312'].getEncoder = function(options) { return new HZGB2312Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['hz-gb-2312'].getDecoder = function(options) { return new HZGB2312Decoder(options); }; // // 11. Legacy multi-byte Chinese (traditional) encodings // // 11.1 big5 /** * @constructor * @param {{fatal: boolean}} options */ function Big5Decoder(options) { var fatal = options.fatal; var /** @type {number} */ big5_lead = 0x00, /** @type {?number} */ big5_pending = null; /** * @param {ByteInputStream} byte_pointer The byte steram to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { // NOTE: Hack to support emitting two code points if (big5_pending !== null) { var pending = big5_pending; big5_pending = null; return pending; } var bite = byte_pointer.get(); if (bite === EOF_byte && big5_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && big5_lead !== 0x00) { big5_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (big5_lead !== 0x00) { var lead = big5_lead; var pointer = null; big5_lead = 0x00; var offset = bite < 0x7F ? 0x40 : 0x62; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) { pointer = (lead - 0x81) * 157 + (bite - offset); } if (pointer === 1133) { big5_pending = 0x0304; return 0x00CA; } if (pointer === 1135) { big5_pending = 0x030C; return 0x00CA; } if (pointer === 1164) { big5_pending = 0x0304; return 0x00EA; } if (pointer === 1166) { big5_pending = 0x030C; return 0x00EA; } var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('big5')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0x81, 0xFE)) { big5_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function Big5Encoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('big5')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 157) + 0x81; //if (lead < 0xA1) { // return encoderError(code_point); //} var trail = pointer % 157; var offset = trail < 0x3F ? 0x40 : 0x62; return output_byte_stream.emit(lead, trail + offset); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['big5'].getEncoder = function(options) { return new Big5Encoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['big5'].getDecoder = function(options) { return new Big5Decoder(options); }; // // 12. Legacy multi-byte Japanese encodings // // 12.1 euc.jp /** * @constructor * @param {{fatal: boolean}} options */ function EUCJPDecoder(options) { var fatal = options.fatal; var /** @type {number} */ eucjp_first = 0x00, /** @type {number} */ eucjp_second = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { if (eucjp_first === 0x00 && eucjp_second === 0x00) { return EOF_code_point; } eucjp_first = 0x00; eucjp_second = 0x00; return decoderError(fatal); } byte_pointer.offset(1); var lead, code_point; if (eucjp_second !== 0x00) { lead = eucjp_second; eucjp_second = 0x00; code_point = null; if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1, index('jis0212')); } if (!inRange(bite, 0xA1, 0xFE)) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (eucjp_first === 0x8E && inRange(bite, 0xA1, 0xDF)) { eucjp_first = 0x00; return 0xFF61 + bite - 0xA1; } if (eucjp_first === 0x8F && inRange(bite, 0xA1, 0xFE)) { eucjp_first = 0x00; eucjp_second = bite; return null; } if (eucjp_first !== 0x00) { lead = eucjp_first; eucjp_first = 0x00; code_point = null; if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) { code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1, index('jis0208')); } if (!inRange(bite, 0xA1, 0xFE)) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === 0x8E || bite === 0x8F || (inRange(bite, 0xA1, 0xFE))) { eucjp_first = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function EUCJPEncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(0x8E, code_point - 0xFF61 + 0xA1); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 94) + 0xA1; var trail = pointer % 94 + 0xA1; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['euc-jp'].getEncoder = function(options) { return new EUCJPEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['euc-jp'].getDecoder = function(options) { return new EUCJPDecoder(options); }; // 12.2 iso-2022-jp /** * @constructor * @param {{fatal: boolean}} options */ function ISO2022JPDecoder(options) { var fatal = options.fatal; /** @enum */ var state = { ASCII: 0, escape_start: 1, escape_middle: 2, escape_final: 3, lead: 4, trail: 5, Katakana: 6 }; var /** @type {number} */ iso2022jp_state = state.ASCII, /** @type {boolean} */ iso2022jp_jis0212 = false, /** @type {number} */ iso2022jp_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite !== EOF_byte) { byte_pointer.offset(1); } switch (iso2022jp_state) { default: case state.ASCII: if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (bite === EOF_byte) { return EOF_code_point; } return decoderError(fatal); case state.escape_start: if (bite === 0x24 || bite === 0x28) { iso2022jp_lead = bite; iso2022jp_state = state.escape_middle; return null; } if (bite !== EOF_byte) { byte_pointer.offset(-1); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.escape_middle: var lead = iso2022jp_lead; iso2022jp_lead = 0x00; if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) { iso2022jp_jis0212 = false; iso2022jp_state = state.lead; return null; } if (lead === 0x24 && bite === 0x28) { iso2022jp_state = state.escape_final; return null; } if (lead === 0x28 && (bite === 0x42 || bite === 0x4A)) { iso2022jp_state = state.ASCII; return null; } if (lead === 0x28 && bite === 0x49) { iso2022jp_state = state.Katakana; return null; } if (bite === EOF_byte) { byte_pointer.offset(-1); } else { byte_pointer.offset(-2); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.escape_final: if (bite === 0x44) { iso2022jp_jis0212 = true; iso2022jp_state = state.lead; return null; } if (bite === EOF_byte) { byte_pointer.offset(-2); } else { byte_pointer.offset(-3); } iso2022jp_state = state.ASCII; return decoderError(fatal); case state.lead: if (bite === 0x0A) { iso2022jp_state = state.ASCII; return decoderError(fatal, 0x000A); } if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (bite === EOF_byte) { return EOF_code_point; } iso2022jp_lead = bite; iso2022jp_state = state.trail; return null; case state.trail: iso2022jp_state = state.lead; if (bite === EOF_byte) { return decoderError(fatal); } var code_point = null; var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21; if (inRange(iso2022jp_lead, 0x21, 0x7E) && inRange(bite, 0x21, 0x7E)) { code_point = (iso2022jp_jis0212 === false) ? indexCodePointFor(pointer, index('jis0208')) : indexCodePointFor(pointer, index('jis0212')); } if (code_point === null) { return decoderError(fatal); } return code_point; case state.Katakana: if (bite === 0x1B) { iso2022jp_state = state.escape_start; return null; } if (inRange(bite, 0x21, 0x5F)) { return 0xFF61 + bite - 0x21; } if (bite === EOF_byte) { return EOF_code_point; } return decoderError(fatal); } }; } /** * @constructor * @param {{fatal: boolean}} options */ function ISO2022JPEncoder(options) { var fatal = options.fatal; /** @enum */ var state = { ASCII: 0, lead: 1, Katakana: 2 }; var /** @type {number} */ iso2022jp_state = state.ASCII; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if ((inRange(code_point, 0x0000, 0x007F) || code_point === 0x00A5 || code_point === 0x203E) && iso2022jp_state !== state.ASCII) { code_point_pointer.offset(-1); iso2022jp_state = state.ASCII; return output_byte_stream.emit(0x1B, 0x28, 0x42); } if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F) && iso2022jp_state !== state.Katakana) { code_point_pointer.offset(-1); iso2022jp_state = state.Katakana; return output_byte_stream.emit(0x1B, 0x28, 0x49); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(code_point - 0xFF61 - 0x21); } if (iso2022jp_state !== state.lead) { code_point_pointer.offset(-1); iso2022jp_state = state.lead; return output_byte_stream.emit(0x1B, 0x24, 0x42); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 94) + 0x21; var trail = pointer % 94 + 0x21; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['iso-2022-jp'].getEncoder = function(options) { return new ISO2022JPEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['iso-2022-jp'].getDecoder = function(options) { return new ISO2022JPDecoder(options); }; // 12.3 shift_jis /** * @constructor * @param {{fatal: boolean}} options */ function ShiftJISDecoder(options) { var fatal = options.fatal; var /** @type {number} */ shiftjis_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && shiftjis_lead === 0x00) { return EOF_code_point; } if (bite === EOF_byte && shiftjis_lead !== 0x00) { shiftjis_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (shiftjis_lead !== 0x00) { var lead = shiftjis_lead; shiftjis_lead = 0x00; if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) { var offset = (bite < 0x7F) ? 0x40 : 0x41; var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1; var code_point = indexCodePointFor((lead - lead_offset) * 188 + bite - offset, index('jis0208')); if (code_point === null) { return decoderError(fatal); } return code_point; } byte_pointer.offset(-1); return decoderError(fatal); } if (inRange(bite, 0x00, 0x80)) { return bite; } if (inRange(bite, 0xA1, 0xDF)) { return 0xFF61 + bite - 0xA1; } if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) { shiftjis_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function ShiftJISEncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x0080)) { return output_byte_stream.emit(code_point); } if (code_point === 0x00A5) { return output_byte_stream.emit(0x5C); } if (code_point === 0x203E) { return output_byte_stream.emit(0x7E); } if (inRange(code_point, 0xFF61, 0xFF9F)) { return output_byte_stream.emit(code_point - 0xFF61 + 0xA1); } var pointer = indexPointerFor(code_point, index('jis0208')); if (pointer === null) { return encoderError(code_point); } var lead = div(pointer, 188); var lead_offset = lead < 0x1F ? 0x81 : 0xC1; var trail = pointer % 188; var offset = trail < 0x3F ? 0x40 : 0x41; return output_byte_stream.emit(lead + lead_offset, trail + offset); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['shift_jis'].getEncoder = function(options) { return new ShiftJISEncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['shift_jis'].getDecoder = function(options) { return new ShiftJISDecoder(options); }; // // 13. Legacy multi-byte Korean encodings // // 13.1 euc-kr /** * @constructor * @param {{fatal: boolean}} options */ function EUCKRDecoder(options) { var fatal = options.fatal; var /** @type {number} */ euckr_lead = 0x00; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && euckr_lead === 0) { return EOF_code_point; } if (bite === EOF_byte && euckr_lead !== 0) { euckr_lead = 0x00; return decoderError(fatal); } byte_pointer.offset(1); if (euckr_lead !== 0x00) { var lead = euckr_lead; var pointer = null; euckr_lead = 0x00; if (inRange(lead, 0x81, 0xC6)) { var temp = (26 + 26 + 126) * (lead - 0x81); if (inRange(bite, 0x41, 0x5A)) { pointer = temp + bite - 0x41; } else if (inRange(bite, 0x61, 0x7A)) { pointer = temp + 26 + bite - 0x61; } else if (inRange(bite, 0x81, 0xFE)) { pointer = temp + 26 + 26 + bite - 0x81; } } if (inRange(lead, 0xC7, 0xFD) && inRange(bite, 0xA1, 0xFE)) { pointer = (26 + 26 + 126) * (0xC7 - 0x81) + (lead - 0xC7) * 94 + (bite - 0xA1); } var code_point = (pointer === null) ? null : indexCodePointFor(pointer, index('euc-kr')); if (pointer === null) { byte_pointer.offset(-1); } if (code_point === null) { return decoderError(fatal); } return code_point; } if (inRange(bite, 0x00, 0x7F)) { return bite; } if (inRange(bite, 0x81, 0xFD)) { euckr_lead = bite; return null; } return decoderError(fatal); }; } /** * @constructor * @param {{fatal: boolean}} options */ function EUCKREncoder(options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } var pointer = indexPointerFor(code_point, index('euc-kr')); if (pointer === null) { return encoderError(code_point); } var lead, trail; if (pointer < ((26 + 26 + 126) * (0xC7 - 0x81))) { lead = div(pointer, (26 + 26 + 126)) + 0x81; trail = pointer % (26 + 26 + 126); var offset = trail < 26 ? 0x41 : trail < 26 + 26 ? 0x47 : 0x4D; return output_byte_stream.emit(lead, trail + offset); } pointer = pointer - (26 + 26 + 126) * (0xC7 - 0x81); lead = div(pointer, 94) + 0xC7; trail = pointer % 94 + 0xA1; return output_byte_stream.emit(lead, trail); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['euc-kr'].getEncoder = function(options) { return new EUCKREncoder(options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['euc-kr'].getDecoder = function(options) { return new EUCKRDecoder(options); }; // // 14. Legacy miscellaneous encodings // // 14.1 replacement // Not needed - API throws TypeError // 14.2 utf-16 /** * @constructor * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Decoder(utf16_be, options) { var fatal = options.fatal; var /** @type {?number} */ utf16_lead_byte = null, /** @type {?number} */ utf16_lead_surrogate = null; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte && utf16_lead_byte === null && utf16_lead_surrogate === null) { return EOF_code_point; } if (bite === EOF_byte && (utf16_lead_byte !== null || utf16_lead_surrogate !== null)) { return decoderError(fatal); } byte_pointer.offset(1); if (utf16_lead_byte === null) { utf16_lead_byte = bite; return null; } var code_point; if (utf16_be) { code_point = (utf16_lead_byte << 8) + bite; } else { code_point = (bite << 8) + utf16_lead_byte; } utf16_lead_byte = null; if (utf16_lead_surrogate !== null) { var lead_surrogate = utf16_lead_surrogate; utf16_lead_surrogate = null; if (inRange(code_point, 0xDC00, 0xDFFF)) { return 0x10000 + (lead_surrogate - 0xD800) * 0x400 + (code_point - 0xDC00); } byte_pointer.offset(-2); return decoderError(fatal); } if (inRange(code_point, 0xD800, 0xDBFF)) { utf16_lead_surrogate = code_point; return null; } if (inRange(code_point, 0xDC00, 0xDFFF)) { return decoderError(fatal); } return code_point; }; } /** * @constructor * @param {boolean} utf16_be True if big-endian, false if little-endian. * @param {{fatal: boolean}} options */ function UTF16Encoder(utf16_be, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { /** * @param {number} code_unit * @return {number} last byte emitted */ function convert_to_bytes(code_unit) { var byte1 = code_unit >> 8; var byte2 = code_unit & 0x00FF; if (utf16_be) { return output_byte_stream.emit(byte1, byte2); } return output_byte_stream.emit(byte2, byte1); } var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0xD800, 0xDFFF)) { encoderError(code_point); } if (code_point <= 0xFFFF) { return convert_to_bytes(code_point); } var lead = div((code_point - 0x10000), 0x400) + 0xD800; var trail = ((code_point - 0x10000) % 0x400) + 0xDC00; convert_to_bytes(lead); return convert_to_bytes(trail); }; } // 14.3 utf-16be /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16be'].getEncoder = function(options) { return new UTF16Encoder(true, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16be'].getDecoder = function(options) { return new UTF16Decoder(true, options); }; // 14.4 utf-16le /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16le'].getEncoder = function(options) { return new UTF16Encoder(false, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['utf-16le'].getDecoder = function(options) { return new UTF16Decoder(false, options); }; // 14.5 x-user-defined /** * @constructor * @param {{fatal: boolean}} options */ function XUserDefinedDecoder(options) { var fatal = options.fatal; /** * @param {ByteInputStream} byte_pointer The byte stream to decode. * @return {?number} The next code point decoded, or null if not enough * data exists in the input stream to decode a complete code point. */ this.decode = function(byte_pointer) { var bite = byte_pointer.get(); if (bite === EOF_byte) { return EOF_code_point; } byte_pointer.offset(1); if (inRange(bite, 0x00, 0x7F)) { return bite; } return 0xF780 + bite - 0x80; }; } /** * @constructor * @param {{fatal: boolean}} options */ function XUserDefinedEncoder(index, options) { var fatal = options.fatal; /** * @param {ByteOutputStream} output_byte_stream Output byte stream. * @param {CodePointInputStream} code_point_pointer Input stream. * @return {number} The last byte emitted. */ this.encode = function(output_byte_stream, code_point_pointer) { var code_point = code_point_pointer.get(); if (code_point === EOF_code_point) { return EOF_byte; } code_point_pointer.offset(1); if (inRange(code_point, 0x0000, 0x007F)) { return output_byte_stream.emit(code_point); } if (inRange(code_point, 0xF780, 0xF7FF)) { return output_byte_stream.emit(code_point - 0xF780 + 0x80); } encoderError(code_point); }; } /** @param {{fatal: boolean}} options */ name_to_encoding['x-user-defined'].getEncoder = function(options) { return new XUserDefinedEncoder(false, options); }; /** @param {{fatal: boolean}} options */ name_to_encoding['x-user-defined'].getDecoder = function(options) { return new XUserDefinedDecoder(false, options); }; // NOTE: currently unused /** * @param {string} label The encoding label. * @param {ByteInputStream} input_stream The byte stream to test. */ function detectEncoding(label, input_stream) { if (input_stream.match([0xFF, 0xFE])) { input_stream.offset(2); return 'utf-16le'; } if (input_stream.match([0xFE, 0xFF])) { input_stream.offset(2); return 'utf-16be'; } if (input_stream.match([0xEF, 0xBB, 0xBF])) { input_stream.offset(3); return 'utf-8'; } return label; } if (!('TextEncoder' in global)) global['TextEncoder'] = TextEncoder; if (!('TextDecoder' in global)) global['TextDecoder'] = TextDecoder; }(this));
#ifndef __NET_SCHED_GENERIC_H #define __NET_SCHED_GENERIC_H #include <linux/netdevice.h> #include <linux/types.h> #include <linux/rcupdate.h> #include <linux/pkt_sched.h> #include <linux/pkt_cls.h> #include <linux/percpu.h> #include <linux/dynamic_queue_limits.h> #include <net/gen_stats.h> #include <net/rtnetlink.h> struct Qdisc_ops; struct qdisc_walker; struct tcf_walker; struct module; struct qdisc_rate_table { struct tc_ratespec rate; u32 data[256]; struct qdisc_rate_table *next; int refcnt; }; enum qdisc_state_t { __QDISC_STATE_SCHED, __QDISC_STATE_DEACTIVATED, __QDISC_STATE_THROTTLED, }; /* * following bits are only changed while qdisc lock is held */ enum qdisc___state_t { __QDISC___STATE_RUNNING = 1, }; struct qdisc_size_table { struct rcu_head rcu; struct list_head list; struct tc_sizespec szopts; int refcnt; u16 data[]; }; struct Qdisc { int (*enqueue)(struct sk_buff *skb, struct Qdisc *dev); struct sk_buff * (*dequeue)(struct Qdisc *dev); unsigned int flags; #define TCQ_F_BUILTIN 1 #define TCQ_F_INGRESS 2 #define TCQ_F_CAN_BYPASS 4 #define TCQ_F_MQROOT 8 #define TCQ_F_ONETXQUEUE 0x10 /* dequeue_skb() can assume all skbs are for * q->dev_queue : It can test * netif_xmit_frozen_or_stopped() before * dequeueing next packet. * Its true for MQ/MQPRIO slaves, or non * multiqueue device. */ #define TCQ_F_WARN_NONWC (1 << 16) #define TCQ_F_CPUSTATS 0x20 /* run using percpu statistics */ #define TCQ_F_NOPARENT 0x40 /* root of its hierarchy : * qdisc_tree_decrease_qlen() should stop. */ u32 limit; const struct Qdisc_ops *ops; struct qdisc_size_table __rcu *stab; struct list_head list; u32 handle; u32 parent; int (*reshape_fail)(struct sk_buff *skb, struct Qdisc *q); void *u32_node; /* This field is deprecated, but it is still used by CBQ * and it will live until better solution will be invented. */ struct Qdisc *__parent; struct netdev_queue *dev_queue; struct gnet_stats_rate_est64 rate_est; struct gnet_stats_basic_cpu __percpu *cpu_bstats; struct gnet_stats_queue __percpu *cpu_qstats; struct Qdisc *next_sched; struct sk_buff *gso_skb; /* * For performance sake on SMP, we put highly modified fields at the end */ unsigned long state; struct sk_buff_head q; struct gnet_stats_basic_packed bstats; unsigned int __state; struct gnet_stats_queue qstats; struct rcu_head rcu_head; int padded; atomic_t refcnt; spinlock_t busylock ____cacheline_aligned_in_smp; }; static inline bool qdisc_is_running(const struct Qdisc *qdisc) { return (qdisc->__state & __QDISC___STATE_RUNNING) ? true : false; } static inline bool qdisc_run_begin(struct Qdisc *qdisc) { if (qdisc_is_running(qdisc)) return false; qdisc->__state |= __QDISC___STATE_RUNNING; return true; } static inline void qdisc_run_end(struct Qdisc *qdisc) { qdisc->__state &= ~__QDISC___STATE_RUNNING; } static inline bool qdisc_may_bulk(const struct Qdisc *qdisc) { return qdisc->flags & TCQ_F_ONETXQUEUE; } static inline int qdisc_avail_bulklimit(const struct netdev_queue *txq) { #ifdef CONFIG_BQL /* Non-BQL migrated drivers will return 0, too. */ return dql_avail(&txq->dql); #else return 0; #endif } static inline bool qdisc_is_throttled(const struct Qdisc *qdisc) { return test_bit(__QDISC_STATE_THROTTLED, &qdisc->state) ? true : false; } static inline void qdisc_throttled(struct Qdisc *qdisc) { set_bit(__QDISC_STATE_THROTTLED, &qdisc->state); } static inline void qdisc_unthrottled(struct Qdisc *qdisc) { clear_bit(__QDISC_STATE_THROTTLED, &qdisc->state); } struct Qdisc_class_ops { /* Child qdisc manipulation */ struct netdev_queue * (*select_queue)(struct Qdisc *, struct tcmsg *); int (*graft)(struct Qdisc *, unsigned long cl, struct Qdisc *, struct Qdisc **); struct Qdisc * (*leaf)(struct Qdisc *, unsigned long cl); void (*qlen_notify)(struct Qdisc *, unsigned long); /* Class manipulation routines */ unsigned long (*get)(struct Qdisc *, u32 classid); void (*put)(struct Qdisc *, unsigned long); int (*change)(struct Qdisc *, u32, u32, struct nlattr **, unsigned long *); int (*delete)(struct Qdisc *, unsigned long); void (*walk)(struct Qdisc *, struct qdisc_walker * arg); /* Filter manipulation */ struct tcf_proto __rcu ** (*tcf_chain)(struct Qdisc *, unsigned long); unsigned long (*bind_tcf)(struct Qdisc *, unsigned long, u32 classid); void (*unbind_tcf)(struct Qdisc *, unsigned long); /* rtnetlink specific */ int (*dump)(struct Qdisc *, unsigned long, struct sk_buff *skb, struct tcmsg*); int (*dump_stats)(struct Qdisc *, unsigned long, struct gnet_dump *); }; struct Qdisc_ops { struct Qdisc_ops *next; const struct Qdisc_class_ops *cl_ops; char id[IFNAMSIZ]; int priv_size; int (*enqueue)(struct sk_buff *, struct Qdisc *); struct sk_buff * (*dequeue)(struct Qdisc *); struct sk_buff * (*peek)(struct Qdisc *); unsigned int (*drop)(struct Qdisc *); int (*init)(struct Qdisc *, struct nlattr *arg); void (*reset)(struct Qdisc *); void (*destroy)(struct Qdisc *); int (*change)(struct Qdisc *, struct nlattr *arg); void (*attach)(struct Qdisc *); int (*dump)(struct Qdisc *, struct sk_buff *); int (*dump_stats)(struct Qdisc *, struct gnet_dump *); struct module *owner; }; struct tcf_result { unsigned long class; u32 classid; }; struct tcf_proto_ops { struct list_head head; char kind[IFNAMSIZ]; int (*classify)(struct sk_buff *, const struct tcf_proto *, struct tcf_result *); int (*init)(struct tcf_proto*); bool (*destroy)(struct tcf_proto*, bool); unsigned long (*get)(struct tcf_proto*, u32 handle); int (*change)(struct net *net, struct sk_buff *, struct tcf_proto*, unsigned long, u32 handle, struct nlattr **, unsigned long *, bool); int (*delete)(struct tcf_proto*, unsigned long); void (*walk)(struct tcf_proto*, struct tcf_walker *arg); /* rtnetlink specific */ int (*dump)(struct net*, struct tcf_proto*, unsigned long, struct sk_buff *skb, struct tcmsg*); struct module *owner; }; struct tcf_proto { /* Fast access part */ struct tcf_proto __rcu *next; void __rcu *root; int (*classify)(struct sk_buff *, const struct tcf_proto *, struct tcf_result *); __be16 protocol; /* All the rest */ u32 prio; u32 classid; struct Qdisc *q; void *data; const struct tcf_proto_ops *ops; struct rcu_head rcu; }; struct qdisc_skb_cb { unsigned int pkt_len; u16 slave_dev_queue_mapping; u16 tc_classid; #define QDISC_CB_PRIV_LEN 20 unsigned char data[QDISC_CB_PRIV_LEN]; }; static inline void qdisc_cb_private_validate(const struct sk_buff *skb, int sz) { struct qdisc_skb_cb *qcb; BUILD_BUG_ON(sizeof(skb->cb) < offsetof(struct qdisc_skb_cb, data) + sz); BUILD_BUG_ON(sizeof(qcb->data) < sz); } static inline int qdisc_qlen(const struct Qdisc *q) { return q->q.qlen; } static inline struct qdisc_skb_cb *qdisc_skb_cb(const struct sk_buff *skb) { return (struct qdisc_skb_cb *)skb->cb; } static inline spinlock_t *qdisc_lock(struct Qdisc *qdisc) { return &qdisc->q.lock; } static inline struct Qdisc *qdisc_root(const struct Qdisc *qdisc) { struct Qdisc *q = rcu_dereference_rtnl(qdisc->dev_queue->qdisc); return q; } static inline struct Qdisc *qdisc_root_sleeping(const struct Qdisc *qdisc) { return qdisc->dev_queue->qdisc_sleeping; } /* The qdisc root lock is a mechanism by which to top level * of a qdisc tree can be locked from any qdisc node in the * forest. This allows changing the configuration of some * aspect of the qdisc tree while blocking out asynchronous * qdisc access in the packet processing paths. * * It is only legal to do this when the root will not change * on us. Otherwise we'll potentially lock the wrong qdisc * root. This is enforced by holding the RTNL semaphore, which * all users of this lock accessor must do. */ static inline spinlock_t *qdisc_root_lock(const struct Qdisc *qdisc) { struct Qdisc *root = qdisc_root(qdisc); ASSERT_RTNL(); return qdisc_lock(root); } static inline spinlock_t *qdisc_root_sleeping_lock(const struct Qdisc *qdisc) { struct Qdisc *root = qdisc_root_sleeping(qdisc); ASSERT_RTNL(); return qdisc_lock(root); } static inline struct net_device *qdisc_dev(const struct Qdisc *qdisc) { return qdisc->dev_queue->dev; } static inline void sch_tree_lock(const struct Qdisc *q) { spin_lock_bh(qdisc_root_sleeping_lock(q)); } static inline void sch_tree_unlock(const struct Qdisc *q) { spin_unlock_bh(qdisc_root_sleeping_lock(q)); } #define tcf_tree_lock(tp) sch_tree_lock((tp)->q) #define tcf_tree_unlock(tp) sch_tree_unlock((tp)->q) extern struct Qdisc noop_qdisc; extern struct Qdisc_ops noop_qdisc_ops; extern struct Qdisc_ops pfifo_fast_ops; extern struct Qdisc_ops mq_qdisc_ops; extern struct Qdisc_ops noqueue_qdisc_ops; extern const struct Qdisc_ops *default_qdisc_ops; struct Qdisc_class_common { u32 classid; struct hlist_node hnode; }; struct Qdisc_class_hash { struct hlist_head *hash; unsigned int hashsize; unsigned int hashmask; unsigned int hashelems; }; static inline unsigned int qdisc_class_hash(u32 id, u32 mask) { id ^= id >> 8; id ^= id >> 4; return id & mask; } static inline struct Qdisc_class_common * qdisc_class_find(const struct Qdisc_class_hash *hash, u32 id) { struct Qdisc_class_common *cl; unsigned int h; h = qdisc_class_hash(id, hash->hashmask); hlist_for_each_entry(cl, &hash->hash[h], hnode) { if (cl->classid == id) return cl; } return NULL; } int qdisc_class_hash_init(struct Qdisc_class_hash *); void qdisc_class_hash_insert(struct Qdisc_class_hash *, struct Qdisc_class_common *); void qdisc_class_hash_remove(struct Qdisc_class_hash *, struct Qdisc_class_common *); void qdisc_class_hash_grow(struct Qdisc *, struct Qdisc_class_hash *); void qdisc_class_hash_destroy(struct Qdisc_class_hash *); void dev_init_scheduler(struct net_device *dev); void dev_shutdown(struct net_device *dev); void dev_activate(struct net_device *dev); void dev_deactivate(struct net_device *dev); void dev_deactivate_many(struct list_head *head); struct Qdisc *dev_graft_qdisc(struct netdev_queue *dev_queue, struct Qdisc *qdisc); void qdisc_reset(struct Qdisc *qdisc); void qdisc_destroy(struct Qdisc *qdisc); void qdisc_tree_decrease_qlen(struct Qdisc *qdisc, unsigned int n); struct Qdisc *qdisc_alloc(struct netdev_queue *dev_queue, const struct Qdisc_ops *ops); struct Qdisc *qdisc_create_dflt(struct netdev_queue *dev_queue, const struct Qdisc_ops *ops, u32 parentid); void __qdisc_calculate_pkt_len(struct sk_buff *skb, const struct qdisc_size_table *stab); bool tcf_destroy(struct tcf_proto *tp, bool force); void tcf_destroy_chain(struct tcf_proto __rcu **fl); int skb_do_redirect(struct sk_buff *); static inline bool skb_at_tc_ingress(const struct sk_buff *skb) { #ifdef CONFIG_NET_CLS_ACT return G_TC_AT(skb->tc_verd) & AT_INGRESS; #else return false; #endif } /* Reset all TX qdiscs greater then index of a device. */ static inline void qdisc_reset_all_tx_gt(struct net_device *dev, unsigned int i) { struct Qdisc *qdisc; for (; i < dev->num_tx_queues; i++) { qdisc = rtnl_dereference(netdev_get_tx_queue(dev, i)->qdisc); if (qdisc) { spin_lock_bh(qdisc_lock(qdisc)); qdisc_reset(qdisc); spin_unlock_bh(qdisc_lock(qdisc)); } } } static inline void qdisc_reset_all_tx(struct net_device *dev) { qdisc_reset_all_tx_gt(dev, 0); } /* Are all TX queues of the device empty? */ static inline bool qdisc_all_tx_empty(const struct net_device *dev) { unsigned int i; rcu_read_lock(); for (i = 0; i < dev->num_tx_queues; i++) { struct netdev_queue *txq = netdev_get_tx_queue(dev, i); const struct Qdisc *q = rcu_dereference(txq->qdisc); if (q->q.qlen) { rcu_read_unlock(); return false; } } rcu_read_unlock(); return true; } /* Are any of the TX qdiscs changing? */ static inline bool qdisc_tx_changing(const struct net_device *dev) { unsigned int i; for (i = 0; i < dev->num_tx_queues; i++) { struct netdev_queue *txq = netdev_get_tx_queue(dev, i); if (rcu_access_pointer(txq->qdisc) != txq->qdisc_sleeping) return true; } return false; } /* Is the device using the noop qdisc on all queues? */ static inline bool qdisc_tx_is_noop(const struct net_device *dev) { unsigned int i; for (i = 0; i < dev->num_tx_queues; i++) { struct netdev_queue *txq = netdev_get_tx_queue(dev, i); if (rcu_access_pointer(txq->qdisc) != &noop_qdisc) return false; } return true; } static inline unsigned int qdisc_pkt_len(const struct sk_buff *skb) { return qdisc_skb_cb(skb)->pkt_len; } /* additional qdisc xmit flags (NET_XMIT_MASK in linux/netdevice.h) */ enum net_xmit_qdisc_t { __NET_XMIT_STOLEN = 0x00010000, __NET_XMIT_BYPASS = 0x00020000, }; #ifdef CONFIG_NET_CLS_ACT #define net_xmit_drop_count(e) ((e) & __NET_XMIT_STOLEN ? 0 : 1) #else #define net_xmit_drop_count(e) (1) #endif static inline void qdisc_calculate_pkt_len(struct sk_buff *skb, const struct Qdisc *sch) { #ifdef CONFIG_NET_SCHED struct qdisc_size_table *stab = rcu_dereference_bh(sch->stab); if (stab) __qdisc_calculate_pkt_len(skb, stab); #endif } static inline int qdisc_enqueue(struct sk_buff *skb, struct Qdisc *sch) { qdisc_calculate_pkt_len(skb, sch); return sch->enqueue(skb, sch); } static inline bool qdisc_is_percpu_stats(const struct Qdisc *q) { return q->flags & TCQ_F_CPUSTATS; } static inline void bstats_update(struct gnet_stats_basic_packed *bstats, const struct sk_buff *skb) { bstats->bytes += qdisc_pkt_len(skb); bstats->packets += skb_is_gso(skb) ? skb_shinfo(skb)->gso_segs : 1; } static inline void bstats_cpu_update(struct gnet_stats_basic_cpu *bstats, const struct sk_buff *skb) { u64_stats_update_begin(&bstats->syncp); bstats_update(&bstats->bstats, skb); u64_stats_update_end(&bstats->syncp); } static inline void qdisc_bstats_cpu_update(struct Qdisc *sch, const struct sk_buff *skb) { bstats_cpu_update(this_cpu_ptr(sch->cpu_bstats), skb); } static inline void qdisc_bstats_update(struct Qdisc *sch, const struct sk_buff *skb) { bstats_update(&sch->bstats, skb); } static inline void qdisc_qstats_backlog_dec(struct Qdisc *sch, const struct sk_buff *skb) { sch->qstats.backlog -= qdisc_pkt_len(skb); } static inline void qdisc_qstats_backlog_inc(struct Qdisc *sch, const struct sk_buff *skb) { sch->qstats.backlog += qdisc_pkt_len(skb); } static inline void __qdisc_qstats_drop(struct Qdisc *sch, int count) { sch->qstats.drops += count; } static inline void qstats_drop_inc(struct gnet_stats_queue *qstats) { qstats->drops++; } static inline void qstats_overlimit_inc(struct gnet_stats_queue *qstats) { qstats->overlimits++; } static inline void qdisc_qstats_drop(struct Qdisc *sch) { qstats_drop_inc(&sch->qstats); } static inline void qdisc_qstats_cpu_drop(struct Qdisc *sch) { qstats_drop_inc(this_cpu_ptr(sch->cpu_qstats)); } static inline void qdisc_qstats_overlimit(struct Qdisc *sch) { sch->qstats.overlimits++; } static inline int __qdisc_enqueue_tail(struct sk_buff *skb, struct Qdisc *sch, struct sk_buff_head *list) { __skb_queue_tail(list, skb); qdisc_qstats_backlog_inc(sch, skb); return NET_XMIT_SUCCESS; } static inline int qdisc_enqueue_tail(struct sk_buff *skb, struct Qdisc *sch) { return __qdisc_enqueue_tail(skb, sch, &sch->q); } static inline struct sk_buff *__qdisc_dequeue_head(struct Qdisc *sch, struct sk_buff_head *list) { struct sk_buff *skb = __skb_dequeue(list); if (likely(skb != NULL)) { qdisc_qstats_backlog_dec(sch, skb); qdisc_bstats_update(sch, skb); } return skb; } static inline struct sk_buff *qdisc_dequeue_head(struct Qdisc *sch) { return __qdisc_dequeue_head(sch, &sch->q); } static inline unsigned int __qdisc_queue_drop_head(struct Qdisc *sch, struct sk_buff_head *list) { struct sk_buff *skb = __skb_dequeue(list); if (likely(skb != NULL)) { unsigned int len = qdisc_pkt_len(skb); qdisc_qstats_backlog_dec(sch, skb); kfree_skb(skb); return len; } return 0; } static inline unsigned int qdisc_queue_drop_head(struct Qdisc *sch) { return __qdisc_queue_drop_head(sch, &sch->q); } static inline struct sk_buff *__qdisc_dequeue_tail(struct Qdisc *sch, struct sk_buff_head *list) { struct sk_buff *skb = __skb_dequeue_tail(list); if (likely(skb != NULL)) qdisc_qstats_backlog_dec(sch, skb); return skb; } static inline struct sk_buff *qdisc_dequeue_tail(struct Qdisc *sch) { return __qdisc_dequeue_tail(sch, &sch->q); } static inline struct sk_buff *qdisc_peek_head(struct Qdisc *sch) { return skb_peek(&sch->q); } /* generic pseudo peek method for non-work-conserving qdisc */ static inline struct sk_buff *qdisc_peek_dequeued(struct Qdisc *sch) { /* we can reuse ->gso_skb because peek isn't called for root qdiscs */ if (!sch->gso_skb) { sch->gso_skb = sch->dequeue(sch); if (sch->gso_skb) /* it's still part of the queue */ sch->q.qlen++; } return sch->gso_skb; } /* use instead of qdisc->dequeue() for all qdiscs queried with ->peek() */ static inline struct sk_buff *qdisc_dequeue_peeked(struct Qdisc *sch) { struct sk_buff *skb = sch->gso_skb; if (skb) { sch->gso_skb = NULL; sch->q.qlen--; } else { skb = sch->dequeue(sch); } return skb; } static inline void __qdisc_reset_queue(struct Qdisc *sch, struct sk_buff_head *list) { /* * We do not know the backlog in bytes of this list, it * is up to the caller to correct it */ __skb_queue_purge(list); } static inline void qdisc_reset_queue(struct Qdisc *sch) { __qdisc_reset_queue(sch, &sch->q); sch->qstats.backlog = 0; } static inline unsigned int __qdisc_queue_drop(struct Qdisc *sch, struct sk_buff_head *list) { struct sk_buff *skb = __qdisc_dequeue_tail(sch, list); if (likely(skb != NULL)) { unsigned int len = qdisc_pkt_len(skb); kfree_skb(skb); return len; } return 0; } static inline unsigned int qdisc_queue_drop(struct Qdisc *sch) { return __qdisc_queue_drop(sch, &sch->q); } static inline int qdisc_drop(struct sk_buff *skb, struct Qdisc *sch) { kfree_skb(skb); qdisc_qstats_drop(sch); return NET_XMIT_DROP; } static inline int qdisc_reshape_fail(struct sk_buff *skb, struct Qdisc *sch) { qdisc_qstats_drop(sch); #ifdef CONFIG_NET_CLS_ACT if (sch->reshape_fail == NULL || sch->reshape_fail(skb, sch)) goto drop; return NET_XMIT_SUCCESS; drop: #endif kfree_skb(skb); return NET_XMIT_DROP; } /* Length to Time (L2T) lookup in a qdisc_rate_table, to determine how long it will take to send a packet given its size. */ static inline u32 qdisc_l2t(struct qdisc_rate_table* rtab, unsigned int pktlen) { int slot = pktlen + rtab->rate.cell_align + rtab->rate.overhead; if (slot < 0) slot = 0; slot >>= rtab->rate.cell_log; if (slot > 255) return rtab->data[255]*(slot >> 8) + rtab->data[slot & 0xFF]; return rtab->data[slot]; } struct psched_ratecfg { u64 rate_bytes_ps; /* bytes per second */ u32 mult; u16 overhead; u8 linklayer; u8 shift; }; static inline u64 psched_l2t_ns(const struct psched_ratecfg *r, unsigned int len) { len += r->overhead; if (unlikely(r->linklayer == TC_LINKLAYER_ATM)) return ((u64)(DIV_ROUND_UP(len,48)*53) * r->mult) >> r->shift; return ((u64)len * r->mult) >> r->shift; } void psched_ratecfg_precompute(struct psched_ratecfg *r, const struct tc_ratespec *conf, u64 rate64); static inline void psched_ratecfg_getrate(struct tc_ratespec *res, const struct psched_ratecfg *r) { memset(res, 0, sizeof(*res)); /* legacy struct tc_ratespec has a 32bit @rate field * Qdisc using 64bit rate should add new attributes * in order to maintain compatibility. */ res->rate = min_t(u64, r->rate_bytes_ps, ~0U); res->overhead = r->overhead; res->linklayer = (r->linklayer & TC_LINKLAYER_MASK); } #endif
How to download Skia ==================== Install gclient and git ----------------------- Follow the instructions on http://www.chromium.org/developers/how-tos/install-depot-tools to download chromium's depot_tools (which includes gclient ). depot_tools will also install git on your system, if it wasn't installed already. Configure git ------------- $ git config --global user.name "Your Name" $ git config --global user.email you@example.com Download your tree ------------------ $ mkdir skia $ cd skia $ gclient config --name . --unmanaged https://skia.googlesource.com/skia.git $ gclient sync $ git checkout master At this point, you have everything you need to build and use Skia! If you want to make changes, and possibly contribute them back to the Skia project, read on... Making changes -------------- First create a branch for your changes: $ git checkout --track origin/master -b my_feature master After making your changes, create a commit $ git add [file1] [file2] ... $ git commit If your branch gets out of date, you will need to update it: $ git pull --rebase $ gclient sync Uploading changes for review ---------------------------- $ git cl upload You may have to enter a Google Account username and password to authenticate yourself to codereview.chromium.org. A free gmail account will do fine, or any other type of Google account. It does not have to match the email address you configured using git config --global user.email above, but it can. The command output should include a URL (similar to https://codereview.chromium.org/111893004/ ) indicating where your changelist can be reviewed. Once your change has received an LGTM ("looks good to me"), you can check the "Commit" box on the codereview page and it will be committed on your behalf. Once your commit has gone in, you should delete the branch containing your change: $ git checkout master $ git branch -D my_feature
/* sdb - MIT - Copyright 2011-2015 - pancake */ #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include "sdb.h" #define MODE_ZERO '0' #define MODE_JSON 'j' #define MODE_DFLT 0 static int save = 0; static Sdb *s = NULL; static ut32 options = SDB_OPTION_FS | SDB_OPTION_NOSTAMP; static void terminate(int sig UNUSED) { if (!s) return; if (save && !sdb_sync (s)) { sdb_free (s); s = NULL; exit (1); } sdb_free (s); exit (0); } #define BS 128 #define USE_SLURPIN 1 static char *stdin_slurp(int *sz) { int blocksize = BS; static int bufsize = BS; static char *next = NULL; static int nextlen = 0; int len, rr, rr2; char *buf, *tmp; #if USE_SLURPIN if (!sz) { /* this is faster but have limits */ /* must optimize the code below before reomving this */ /* run test/add10k.sh script to benchmark */ static char buf[96096]; // MAGIC NUMBERS CO. memset (buf, 0, sizeof (buf)); if (!fgets (buf, sizeof (buf)-1, stdin)) return NULL; if (feof (stdin)) return NULL; buf[strlen (buf)-1] = 0; return strdup (buf); } #endif buf = calloc (BS+1, 1); if (buf == NULL) { return NULL; } len = 0; for (;;) { if (next) { free (buf); buf = next; bufsize = nextlen + blocksize; //len = nextlen; rr = nextlen; rr2 = read (0, buf+nextlen, blocksize); if (rr2 >0) { rr += rr2; bufsize += rr2; } next = NULL; nextlen = 0; } else { rr = read (0, buf+len, blocksize); } if (rr <1) { // EOF buf[len] = 0; next = NULL; break; } len += rr; //buf[len] = 0; #if !USE_SLURPIN if (!sz) { char *nl = strchr (buf, '\n'); if (nl) { *nl++ = 0; int nlen = (nl-buf); nextlen = len-nlen; //bufsize-nlen; if (nextlen>0) { next = malloc (nextlen+blocksize+1); if (!next) { eprintf ("Cannot malloc %d\n", nextlen); break; } memcpy (next, nl, nextlen); if (!*next) { next = NULL; } else { // continue; } } else { next = NULL; nextlen = 0; //strlen (next);; } break; } } #endif bufsize += blocksize; tmp = realloc (buf, bufsize+1); if (!tmp) { bufsize -= blocksize; break; } buf = tmp; } if (sz) { *sz = len; } //eprintf ("LEN %d (%s)\n", len, buf); if (len<1) { free (buf); buf = NULL; return NULL; } buf[len] = 0; return buf; } #if USE_MMAN static void synchronize(int sig UNUSED) { // TODO: must be in sdb_sync() or wat? Sdb *n; sdb_sync (s); n = sdb_new (s->path, s->name, s->lock); if (n) { sdb_config (n, options); sdb_free (s); s = n; } } #endif static int sdb_grep (const char *db, int fmt, const char *grep) { char *k, *v; const char *comma = ""; Sdb *s = sdb_new (NULL, db, 0); if (!s) return 1; sdb_config (s, options); sdb_dump_begin (s); if (fmt==MODE_JSON) printf ("{"); while (sdb_dump_dupnext (s, &k, &v, NULL)) { if (!strstr (k, grep) && !strstr (v, grep)) { continue; } switch (fmt) { case MODE_JSON: if (!strcmp (v, "true") || !strcmp (v, "false")) { printf ("%s\"%s\":%s", comma, k, v); } else if (sdb_isnum (v)) { printf ("%s\"%s\":%llu", comma, k, sdb_atoi (v)); } else if (*v=='{' || *v=='[') { printf ("%s\"%s\":%s", comma, k, v); } else printf ("%s\"%s\":\"%s\"", comma, k, v); comma = ","; break; case MODE_ZERO: printf ("%s=%s", k, v); fwrite ("", 1,1, stdout); break; default: printf ("%s=%s\n", k, v); break; } #if 0 if (qf && strchr (v, SDB_RS)) { for (p=v; *p; p++) if (*p==SDB_RS) *p = ','; printf ("[]%s=%s\n", k, v); } else { printf ("%s=%s\n", k, v); } #endif free (k); free (v); } switch (fmt) { case MODE_ZERO: fflush (stdout); write (1, "", 1); break; case MODE_JSON: printf ("}\n"); break; } sdb_free (s); return 0; } static int sdb_dump (const char *db, int fmt) { char *k, *v; const char *comma = ""; Sdb *s = sdb_new (NULL, db, 0); if (!s) return 1; sdb_config (s, options); sdb_dump_begin (s); if (fmt==MODE_JSON) printf ("{"); while (sdb_dump_dupnext (s, &k, &v, NULL)) { switch (fmt) { case MODE_JSON: if (!strcmp (v, "true") || !strcmp (v, "false")) { printf ("%s\"%s\":%s", comma, k, v); } else if (sdb_isnum (v)) { printf ("%s\"%s\":%llu", comma, k, sdb_atoi (v)); } else if (*v=='{' || *v=='[') { printf ("%s\"%s\":%s", comma, k, v); } else printf ("%s\"%s\":\"%s\"", comma, k, v); comma = ","; break; case MODE_ZERO: printf ("%s=%s", k, v); fwrite ("", 1,1, stdout); break; default: printf ("%s=%s\n", k, v); break; } #if 0 if (qf && strchr (v, SDB_RS)) { for (p=v; *p; p++) if (*p==SDB_RS) *p = ','; printf ("[]%s=%s\n", k, v); } else { printf ("%s=%s\n", k, v); } #endif free (k); free (v); } switch (fmt) { case MODE_ZERO: fflush (stdout); write (1, "", 1); break; case MODE_JSON: printf ("}\n"); break; } sdb_free (s); return 0; } static int insertkeys(Sdb *s, const char **args, int nargs, int mode) { int must_save = 0; if (args && nargs>0) { int i; for (i=0; i<nargs; i++) { switch (mode) { case '-': must_save |= sdb_query (s, args[i]); break; case '=': if (strchr (args[i], '=')) { char *v, *kv = (char *)strdup (args[i]); v = strchr (kv, '='); if (v) { *v++ = 0; sdb_disk_insert (s, kv, v); } free (kv); } break; } } } return must_save; } static int createdb(const char *f, const char **args, int nargs) { char *line, *eq; s = sdb_new (NULL, f, 0); if (!s || !sdb_disk_create (s)) { eprintf ("Cannot create database\n"); return 1; } insertkeys (s, args, nargs, '='); sdb_config (s, options); for (;(line = stdin_slurp (NULL));) { if ((eq = strchr (line, '='))) { *eq++ = 0; sdb_disk_insert (s, line, eq); } free (line); } sdb_disk_finish (s); return 0; } static int showusage(int o) { printf ("usage: sdb [-0cdehjJv|-D A B] [-|db] " "[.file]|[-=]|[-+][(idx)key[:json|=value] ..]\n"); if (o==2) { printf (" -0 terminate results with \\x00\n" " -c count the number of keys database\n" " -d decode base64 from stdin\n" " -D diff two databases\n" " -e encode stdin as base64\n" " -h show this help\n" " -j output in json\n" " -J enable journaling\n" " -v show version information\n"); return 0; } return o; } static int showversion(void) { printf ("sdb "SDB_VERSION"\n"); fflush (stdout); return 0; } static int jsonIndent() { int len; char *in; char *out; in = stdin_slurp (&len); if (!in) return 0; out = sdb_json_indent (in); if (!out) { free (in); return 1; } puts (out); free (out); free (in); return 0; } static int base64encode() { int len; ut8* in; char *out; in = (ut8*)stdin_slurp (&len); if (!in) { return 0; } out = sdb_encode (in, len); if (!out) { free (in); return 1; } puts (out); free (out); free (in); return 0; } static int base64decode() { int len, ret = 1; char *in; ut8 *out; in = (char*)stdin_slurp (&len); if (in) { out = sdb_decode (in, &len); if (out) { if (len>=0) { write (1, out, len); ret = 0; } free (out); } free (in); } return ret; } static int dbdiff (const char *a, const char *b) { int n = 0; char *k, *v; const char *v2; Sdb *A = sdb_new (NULL, a, 0); Sdb *B = sdb_new (NULL, b, 0); sdb_dump_begin (A); while (sdb_dump_dupnext (A, &k, &v, NULL)) { v2 = sdb_const_get (B, k, 0); if (!v2) { printf ("%s=\n", k); n = 1; } } sdb_dump_begin (B); while (sdb_dump_dupnext (B, &k, &v, NULL)) { if (!v || !*v) continue; v2 = sdb_const_get (A, k, 0); if (!v2 || strcmp (v, v2)) { printf ("%s=%s\n", k, v2); n = 1; } } sdb_free (A); sdb_free (B); free (k); free (v); return n; } int showcount (const char *db) { ut32 d; s = sdb_new (NULL, db, 0); if (sdb_stats (s, &d, NULL)) { printf ("%d\n", d); } // TODO: show version, timestamp information sdb_free (s); return 0; } int main(int argc, const char **argv) { char *line; const char *arg, *grep = NULL; int i, ret, fmt = MODE_DFLT; int db0 = 1, argi = 1; int interactive = 0; /* terminate flags */ if (argc<2) { return showusage (1); } arg = argv[1]; if (arg[0] == '-') {// && arg[1] && arg[2]==0) { switch (arg[1]) { case 0: /* no-op */ break; case '0': fmt = MODE_ZERO; db0++; argi++; if (db0>=argc) { return showusage(1); } break; case 'g': db0+=2; if (db0>=argc) { return showusage(1); } grep = argv[2]; argi+=2; break; case 'J': options |= SDB_OPTION_JOURNAL; db0++; argi++; if (db0>=argc) { return showusage(1); } break; case 'c': return (argc<3)? showusage (1) : showcount (argv[2]); case 'v': return showversion (); case 'h': return showusage (2); case 'e': return base64encode (); case 'd': return base64decode (); case 'D': if (argc == 4) return dbdiff (argv[2], argv[3]); return showusage (0); case 'j': if (argc>2) return sdb_dump (argv[db0+1], MODE_JSON); return jsonIndent(); default: eprintf ("Invalid flag %s\n", arg); break; } } /* sdb - */ if (argi == 1 && !strcmp (argv[argi], "-")) { /* no database */ argv[argi] = ""; if (argc == db0+1) { interactive = 1; /* if no argument passed */ argv[argi] = "-"; argc++; argi++; } } /* sdb dbname */ if (argc-1 == db0) { if (grep) { return sdb_grep (argv[db0], fmt, grep); } else { return sdb_dump (argv[db0], fmt); } } #if USE_MMAN signal (SIGINT, terminate); signal (SIGHUP, synchronize); #endif ret = 0; if (interactive || !strcmp (argv[db0+1], "-")) { if ((s = sdb_new (NULL, argv[db0], 0))) { sdb_config (s, options); int kvs = db0+2; if (kvs < argc) { save |= insertkeys (s, argv+argi+2, argc-kvs, '-'); } for (;(line = stdin_slurp (NULL));) { save |= sdb_query (s, line); if (fmt) { fflush (stdout); write (1, "", 1); } free (line); } } } else if (!strcmp (argv[db0+1], "=")) { ret = createdb (argv[db0], argv+db0+2, argc-(db0+2)); } else { s = sdb_new (NULL, argv[db0], 0); if (!s) return 1; sdb_config (s, options); for (i=db0+1; i<argc; i++) { save |= sdb_query (s, argv[i]); if (fmt) { fflush (stdout); write (1, "", 1); } } } terminate (0); return ret; }
body { padding: 3.5; } body { padding: 3.5; } body { padding: 10; padding: 0; }
<!DOCTYPE html> <html> <!-- Copyright 2010 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> Closure Unit Tests - goog.proto2 - message.js </title> <script src="../base.js"> </script> <script> goog.require('goog.proto2.MessageTest'); </script> </head> <body> </body> </html>
// Copyright (C) 2014-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/>. // // { dg-options "-std=gnu++11" } // { dg-do run { xfail *-*-* } } #include <debug/forward_list> #include <testsuite_allocator.h> void test01() { bool test __attribute__((unused)) = true; typedef __gnu_test::uneq_allocator<int> alloc_type; typedef __gnu_debug::forward_list<int, alloc_type> test_type; test_type v1(alloc_type(1)); v1.push_front(0); auto it = v1.begin(); test_type v2(std::move(v1), alloc_type(2)); VERIFY( it == v2.begin() ); // Error, it is singular } int main() { test01(); return 0; }
/* * (C) Copyright 2007 Michal Simek * * Michal SIMEK <monstr@monstr.eu> * * See file CREDITS for list of people who contributed to this * project. * * 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. * * 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 <common.h> #include <asm/microblaze_timer.h> #include <asm/microblaze_intc.h> volatile int timestamp = 0; void reset_timer (void) { timestamp = 0; } #ifdef CONFIG_SYS_TIMER_0 ulong get_timer (ulong base) { return (timestamp - base); } #else ulong get_timer (ulong base) { return (timestamp++ - base); } #endif void set_timer (ulong t) { timestamp = t; } #ifdef CONFIG_SYS_INTC_0 #ifdef CONFIG_SYS_TIMER_0 microblaze_timer_t *tmr = (microblaze_timer_t *) (CONFIG_SYS_TIMER_0_ADDR); void timer_isr (void *arg) { timestamp++; tmr->control = tmr->control | TIMER_INTERRUPT; } void timer_init (void) { tmr->loadreg = CONFIG_SYS_TIMER_0_PRELOAD; tmr->control = TIMER_INTERRUPT | TIMER_RESET; tmr->control = TIMER_ENABLE | TIMER_ENABLE_INTR | TIMER_RELOAD | TIMER_DOWN_COUNT; reset_timer (); install_interrupt_handler (CONFIG_SYS_TIMER_0_IRQ, timer_isr, (void *)tmr); } #endif #endif
// { dg-options "-std=gnu++11" } // { dg-require-cstdint "" } // // 2012-01-28 Edward M. Smith-Rowland <3dw4rd@verizon.net> // // Copyright (C) 2012-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/>. // Class template rice_distribution // 26.5.1.6 Random number distribution requirements [rand.req.dist] #include <ext/random> #include <sstream> #include <testsuite_hooks.h> void test01() { bool test __attribute__((unused)) = true; std::stringstream str; __gnu_cxx::rice_distribution<double> u(1.5, 3.0), v; std::minstd_rand0 rng; u(rng); // advance str << u; str >> v; VERIFY( u == v ); } int main() { test01(); return 0; }
<html> <head> <title>Docs for page Callback.php</title> <link rel="stylesheet" type="text/css" href="../media/style.css"> </head> <body> <table border="0" cellspacing="0" cellpadding="0" height="48" width="100%"> <tr> <td class="header_top">phpQuery</td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> <tr> <td class="header_menu"> [ <a href="../classtrees_phpQuery.html" class="menu">class tree: phpQuery</a> ] [ <a href="../elementindex_phpQuery.html" class="menu">index: phpQuery</a> ] [ <a href="../elementindex.html" class="menu">all elements</a> ] </td> </tr> <tr><td class="header_line"><img src="../media/empty.png" width="1" height="1" border="0" alt="" /></td></tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="200" class="menu"> <div id="todolist"> <p><a href="../todolist.html">Todo List</a></p> </div> <b>Packages:</b><br /> <a href="../li_phpQuery.html">phpQuery</a><br /> <br /><br /> <b>Files:</b><br /> <div class="package"> <a href="../phpQuery/_Callback.php.html"> Callback.php </a><br> <a href="../phpQuery/_DOMDocumentWrapper.php.html"> DOMDocumentWrapper.php </a><br> <a href="../phpQuery/_DOMEvent.php.html"> DOMEvent.php </a><br> <a href="../phpQuery/_phpQuery.php.html"> phpQuery.php </a><br> <a href="../phpQuery/_phpQueryEvents.php.html"> phpQueryEvents.php </a><br> <a href="../phpQuery/_phpQueryObject.php.html"> phpQueryObject.php </a><br> </div><br /> <b>Classes:</b><br /> <div class="package"> <a href="../phpQuery/Callback.html">Callback</a><br /> <a href="../phpQuery/CallbackParam.html">CallbackParam</a><br /> <a href="../phpQuery/CallbackReference.html">CallbackReference</a><br /> <a href="../phpQuery/DOMDocumentWrapper.html">DOMDocumentWrapper</a><br /> <a href="../phpQuery/DOMEvent.html">DOMEvent</a><br /> <a href="../phpQuery/phpQuery.html">phpQuery</a><br /> <a href="../phpQuery/phpQueryEvents.html">phpQueryEvents</a><br /> <a href="../phpQuery/phpQueryObject.html">phpQueryObject</a><br /> <a href="../phpQuery/phpQueryPlugins.html">phpQueryPlugins</a><br /> </div> </td> <td> <table cellpadding="10" cellspacing="0" width="100%" border="0"><tr><td valign="top"> <h1>Procedural File: Callback.php</h1> Source Location: /Callback.php<br /><br /> <br> <br> <div class="contents"> <h2>Classes:</h2> <dt><a href="../phpQuery/Callback.html">Callback</a></dt> <dd>Callback class implementing ParamStructures, pattern similar to Currying.</dd> <dt><a href="../phpQuery/CallbackReference.html">CallbackReference</a></dt> <dd>Callback class implementing ParamStructures, pattern similar to Currying.</dd> <dt><a href="../phpQuery/CallbackParam.html">CallbackParam</a></dt> <dd></dd> </div><br /><br /> <h2>Page Details:</h2> <br /><br /> <br /><br /> <br /><br /> <br /> <div class="credit"> <hr /> Documentation generated on Tue, 18 Nov 2008 19:39:23 +0100 by <a href="http://www.phpdoc.org">phpDocumentor 1.4.2</a> </div> </td></tr></table> </td> </tr> </table> </body> </html>
/** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission and of our proprietary license can be found at and * in the LICENSE file you have received along with this program. * * 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. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @package CanceledOrder * @subpackage Store * @version $Id$ * @author shopware AG */ /** * Shopware Store - canceled baskets' articles */ //{block name="backend/canceled_order/store/articles"} Ext.define('Shopware.apps.CanceledOrder.store.Articles', { extend: 'Ext.data.Store', // Do not load data, when not explicitly requested autoLoad: false, model : 'Shopware.apps.CanceledOrder.model.Articles', remoteFilter: true, remoteSort: true, /** * Configure the data communication * @object */ proxy: { type: 'ajax', /** * Configure the url mapping * @object */ api: { read: '{url controller=CanceledOrder action="getArticle"}' }, /** * Configure the data reader * @object */ reader: { type: 'json', root: 'data', totalProperty:'total' } } }); //{/block}
/** * \file * * Copyright (c) 2012-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #ifndef _SAM4SD32C_PIO_ #define _SAM4SD32C_PIO_ #define PIO_PA0 (1u << 0) /**< \brief Pin Controlled by PA0 */ #define PIO_PA1 (1u << 1) /**< \brief Pin Controlled by PA1 */ #define PIO_PA2 (1u << 2) /**< \brief Pin Controlled by PA2 */ #define PIO_PA3 (1u << 3) /**< \brief Pin Controlled by PA3 */ #define PIO_PA4 (1u << 4) /**< \brief Pin Controlled by PA4 */ #define PIO_PA5 (1u << 5) /**< \brief Pin Controlled by PA5 */ #define PIO_PA6 (1u << 6) /**< \brief Pin Controlled by PA6 */ #define PIO_PA7 (1u << 7) /**< \brief Pin Controlled by PA7 */ #define PIO_PA8 (1u << 8) /**< \brief Pin Controlled by PA8 */ #define PIO_PA9 (1u << 9) /**< \brief Pin Controlled by PA9 */ #define PIO_PA10 (1u << 10) /**< \brief Pin Controlled by PA10 */ #define PIO_PA11 (1u << 11) /**< \brief Pin Controlled by PA11 */ #define PIO_PA12 (1u << 12) /**< \brief Pin Controlled by PA12 */ #define PIO_PA13 (1u << 13) /**< \brief Pin Controlled by PA13 */ #define PIO_PA14 (1u << 14) /**< \brief Pin Controlled by PA14 */ #define PIO_PA15 (1u << 15) /**< \brief Pin Controlled by PA15 */ #define PIO_PA16 (1u << 16) /**< \brief Pin Controlled by PA16 */ #define PIO_PA17 (1u << 17) /**< \brief Pin Controlled by PA17 */ #define PIO_PA18 (1u << 18) /**< \brief Pin Controlled by PA18 */ #define PIO_PA19 (1u << 19) /**< \brief Pin Controlled by PA19 */ #define PIO_PA20 (1u << 20) /**< \brief Pin Controlled by PA20 */ #define PIO_PA21 (1u << 21) /**< \brief Pin Controlled by PA21 */ #define PIO_PA22 (1u << 22) /**< \brief Pin Controlled by PA22 */ #define PIO_PA23 (1u << 23) /**< \brief Pin Controlled by PA23 */ #define PIO_PA24 (1u << 24) /**< \brief Pin Controlled by PA24 */ #define PIO_PA25 (1u << 25) /**< \brief Pin Controlled by PA25 */ #define PIO_PA26 (1u << 26) /**< \brief Pin Controlled by PA26 */ #define PIO_PA27 (1u << 27) /**< \brief Pin Controlled by PA27 */ #define PIO_PA28 (1u << 28) /**< \brief Pin Controlled by PA28 */ #define PIO_PA29 (1u << 29) /**< \brief Pin Controlled by PA29 */ #define PIO_PA30 (1u << 30) /**< \brief Pin Controlled by PA30 */ #define PIO_PA31 (1u << 31) /**< \brief Pin Controlled by PA31 */ #define PIO_PB0 (1u << 0) /**< \brief Pin Controlled by PB0 */ #define PIO_PB1 (1u << 1) /**< \brief Pin Controlled by PB1 */ #define PIO_PB2 (1u << 2) /**< \brief Pin Controlled by PB2 */ #define PIO_PB3 (1u << 3) /**< \brief Pin Controlled by PB3 */ #define PIO_PB4 (1u << 4) /**< \brief Pin Controlled by PB4 */ #define PIO_PB5 (1u << 5) /**< \brief Pin Controlled by PB5 */ #define PIO_PB6 (1u << 6) /**< \brief Pin Controlled by PB6 */ #define PIO_PB7 (1u << 7) /**< \brief Pin Controlled by PB7 */ #define PIO_PB8 (1u << 8) /**< \brief Pin Controlled by PB8 */ #define PIO_PB9 (1u << 9) /**< \brief Pin Controlled by PB9 */ #define PIO_PB10 (1u << 10) /**< \brief Pin Controlled by PB10 */ #define PIO_PB11 (1u << 11) /**< \brief Pin Controlled by PB11 */ #define PIO_PB12 (1u << 12) /**< \brief Pin Controlled by PB12 */ #define PIO_PB13 (1u << 13) /**< \brief Pin Controlled by PB13 */ #define PIO_PB14 (1u << 14) /**< \brief Pin Controlled by PB14 */ #define PIO_PC0 (1u << 0) /**< \brief Pin Controlled by PC0 */ #define PIO_PC1 (1u << 1) /**< \brief Pin Controlled by PC1 */ #define PIO_PC2 (1u << 2) /**< \brief Pin Controlled by PC2 */ #define PIO_PC3 (1u << 3) /**< \brief Pin Controlled by PC3 */ #define PIO_PC4 (1u << 4) /**< \brief Pin Controlled by PC4 */ #define PIO_PC5 (1u << 5) /**< \brief Pin Controlled by PC5 */ #define PIO_PC6 (1u << 6) /**< \brief Pin Controlled by PC6 */ #define PIO_PC7 (1u << 7) /**< \brief Pin Controlled by PC7 */ #define PIO_PC8 (1u << 8) /**< \brief Pin Controlled by PC8 */ #define PIO_PC9 (1u << 9) /**< \brief Pin Controlled by PC9 */ #define PIO_PC10 (1u << 10) /**< \brief Pin Controlled by PC10 */ #define PIO_PC11 (1u << 11) /**< \brief Pin Controlled by PC11 */ #define PIO_PC12 (1u << 12) /**< \brief Pin Controlled by PC12 */ #define PIO_PC13 (1u << 13) /**< \brief Pin Controlled by PC13 */ #define PIO_PC14 (1u << 14) /**< \brief Pin Controlled by PC14 */ #define PIO_PC15 (1u << 15) /**< \brief Pin Controlled by PC15 */ #define PIO_PC16 (1u << 16) /**< \brief Pin Controlled by PC16 */ #define PIO_PC17 (1u << 17) /**< \brief Pin Controlled by PC17 */ #define PIO_PC18 (1u << 18) /**< \brief Pin Controlled by PC18 */ #define PIO_PC19 (1u << 19) /**< \brief Pin Controlled by PC19 */ #define PIO_PC20 (1u << 20) /**< \brief Pin Controlled by PC20 */ #define PIO_PC21 (1u << 21) /**< \brief Pin Controlled by PC21 */ #define PIO_PC22 (1u << 22) /**< \brief Pin Controlled by PC22 */ #define PIO_PC23 (1u << 23) /**< \brief Pin Controlled by PC23 */ #define PIO_PC24 (1u << 24) /**< \brief Pin Controlled by PC24 */ #define PIO_PC25 (1u << 25) /**< \brief Pin Controlled by PC25 */ #define PIO_PC26 (1u << 26) /**< \brief Pin Controlled by PC26 */ #define PIO_PC27 (1u << 27) /**< \brief Pin Controlled by PC27 */ #define PIO_PC28 (1u << 28) /**< \brief Pin Controlled by PC28 */ #define PIO_PC29 (1u << 29) /**< \brief Pin Controlled by PC29 */ #define PIO_PC30 (1u << 30) /**< \brief Pin Controlled by PC30 */ #define PIO_PC31 (1u << 31) /**< \brief Pin Controlled by PC31 */ /* ========== Pio definition for ADC peripheral ========== */ #define PIO_PA17X1_AD0 (1u << 17) /**< \brief Adc signal: AD0 */ #define PIO_PA18X1_AD1 (1u << 18) /**< \brief Adc signal: AD1 */ #define PIO_PC13X1_AD10 (1u << 13) /**< \brief Adc signal: AD10 */ #define PIO_PC15X1_AD11 (1u << 15) /**< \brief Adc signal: AD11 */ #define PIO_PC12X1_AD12 (1u << 12) /**< \brief Adc signal: AD12 */ #define PIO_PC29X1_AD13 (1u << 29) /**< \brief Adc signal: AD13 */ #define PIO_PC30X1_AD14 (1u << 30) /**< \brief Adc signal: AD14 */ #define PIO_PA19X1_AD2 (1u << 19) /**< \brief Adc signal: AD2/WKUP9 */ #define PIO_PA19X1_WKUP9 (1u << 19) /**< \brief Adc signal: AD2/WKUP9 */ #define PIO_PA20X1_AD3 (1u << 20) /**< \brief Adc signal: AD3/WKUP10 */ #define PIO_PA20X1_WKUP10 (1u << 20) /**< \brief Adc signal: AD3/WKUP10 */ #define PIO_PB0X1_AD4 (1u << 0) /**< \brief Adc signal: AD4/RTCOUT0 */ #define PIO_PB0X1_RTCOUT0 (1u << 0) /**< \brief Adc signal: AD4/RTCOUT0 */ #define PIO_PB1X1_AD5 (1u << 1) /**< \brief Adc signal: AD5/RTCOUT1 */ #define PIO_PB1X1_RTCOUT1 (1u << 1) /**< \brief Adc signal: AD5/RTCOUT1 */ #define PIO_PB2X1_AD6 (1u << 2) /**< \brief Adc signal: AD6/WKUP12 */ #define PIO_PB2X1_WKUP12 (1u << 2) /**< \brief Adc signal: AD6/WKUP12 */ #define PIO_PB3X1_AD7 (1u << 3) /**< \brief Adc signal: AD7 */ #define PIO_PA21X1_AD8 (1u << 21) /**< \brief Adc signal: AD8 */ #define PIO_PA22X1_AD9 (1u << 22) /**< \brief Adc signal: AD9 */ #define PIO_PA8B_ADTRG (1u << 8) /**< \brief Adc signal: ADTRG */ /* ========== Pio definition for DACC peripheral ========== */ #define PIO_PB13X1_DAC0 (1u << 13) /**< \brief Dacc signal: DAC0 */ #define PIO_PB14X1_DAC1 (1u << 14) /**< \brief Dacc signal: DAC1 */ #define PIO_PA2C_DATRG (1u << 2) /**< \brief Dacc signal: DATRG */ /* ========== Pio definition for EBI peripheral ========== */ #define PIO_PC18A_A0 (1u << 18) /**< \brief Ebi signal: A0 */ #define PIO_PC19A_A1 (1u << 19) /**< \brief Ebi signal: A1 */ #define PIO_PC28A_A10 (1u << 28) /**< \brief Ebi signal: A10 */ #define PIO_PC29A_A11 (1u << 29) /**< \brief Ebi signal: A11 */ #define PIO_PC30A_A12 (1u << 30) /**< \brief Ebi signal: A12 */ #define PIO_PC31A_A13 (1u << 31) /**< \brief Ebi signal: A13 */ #define PIO_PA18C_A14 (1u << 18) /**< \brief Ebi signal: A14 */ #define PIO_PA19C_A15 (1u << 19) /**< \brief Ebi signal: A15 */ #define PIO_PA20C_A16 (1u << 20) /**< \brief Ebi signal: A16 */ #define PIO_PA0C_A17 (1u << 0) /**< \brief Ebi signal: A17 */ #define PIO_PA1C_A18 (1u << 1) /**< \brief Ebi signal: A18 */ #define PIO_PA23C_A19 (1u << 23) /**< \brief Ebi signal: A19 */ #define PIO_PC20A_A2 (1u << 20) /**< \brief Ebi signal: A2 */ #define PIO_PA24C_A20 (1u << 24) /**< \brief Ebi signal: A20 */ #define PIO_PC16A_A21 (1u << 16) /**< \brief Ebi signal: A21/NANDALE */ #define PIO_PC16A_NANDALE (1u << 16) /**< \brief Ebi signal: A21/NANDALE */ #define PIO_PC17A_A22 (1u << 17) /**< \brief Ebi signal: A22/NANDCLE */ #define PIO_PC17A_NANDCLE (1u << 17) /**< \brief Ebi signal: A22/NANDCLE */ #define PIO_PA25C_A23 (1u << 25) /**< \brief Ebi signal: A23 */ #define PIO_PC21A_A3 (1u << 21) /**< \brief Ebi signal: A3 */ #define PIO_PC22A_A4 (1u << 22) /**< \brief Ebi signal: A4 */ #define PIO_PC23A_A5 (1u << 23) /**< \brief Ebi signal: A5 */ #define PIO_PC24A_A6 (1u << 24) /**< \brief Ebi signal: A6 */ #define PIO_PC25A_A7 (1u << 25) /**< \brief Ebi signal: A7 */ #define PIO_PC26A_A8 (1u << 26) /**< \brief Ebi signal: A8 */ #define PIO_PC27A_A9 (1u << 27) /**< \brief Ebi signal: A9 */ #define PIO_PC0A_D0 (1u << 0) /**< \brief Ebi signal: D0 */ #define PIO_PC1A_D1 (1u << 1) /**< \brief Ebi signal: D1 */ #define PIO_PC2A_D2 (1u << 2) /**< \brief Ebi signal: D2 */ #define PIO_PC3A_D3 (1u << 3) /**< \brief Ebi signal: D3 */ #define PIO_PC4A_D4 (1u << 4) /**< \brief Ebi signal: D4 */ #define PIO_PC5A_D5 (1u << 5) /**< \brief Ebi signal: D5 */ #define PIO_PC6A_D6 (1u << 6) /**< \brief Ebi signal: D6 */ #define PIO_PC7A_D7 (1u << 7) /**< \brief Ebi signal: D7 */ #define PIO_PC9A_NANDOE (1u << 9) /**< \brief Ebi signal: NANDOE */ #define PIO_PC10A_NANDWE (1u << 10) /**< \brief Ebi signal: NANDWE */ #define PIO_PC14A_NCS0 (1u << 14) /**< \brief Ebi signal: NCS0 */ #define PIO_PC15A_NCS1 (1u << 15) /**< \brief Ebi signal: NCS1 */ #define PIO_PA22C_NCS2 (1u << 22) /**< \brief Ebi signal: NCS2 */ #define PIO_PC12A_NCS3 (1u << 12) /**< \brief Ebi signal: NCS3 */ #define PIO_PC11A_NRD (1u << 11) /**< \brief Ebi signal: NRD */ #define PIO_PC13A_NWAIT (1u << 13) /**< \brief Ebi signal: NWAIT */ #define PIO_PC8A_NWE (1u << 8) /**< \brief Ebi signal: NWE */ /* ========== Pio definition for HSMCI peripheral ========== */ #define PIO_PA28C_MCCDA (1u << 28) /**< \brief Hsmci signal: MCCDA */ #define PIO_PA29C_MCCK (1u << 29) /**< \brief Hsmci signal: MCCK */ #define PIO_PA30C_MCDA0 (1u << 30) /**< \brief Hsmci signal: MCDA0 */ #define PIO_PA31C_MCDA1 (1u << 31) /**< \brief Hsmci signal: MCDA1 */ #define PIO_PA26C_MCDA2 (1u << 26) /**< \brief Hsmci signal: MCDA2 */ #define PIO_PA27C_MCDA3 (1u << 27) /**< \brief Hsmci signal: MCDA3 */ /* ========== Pio definition for PIOA peripheral ========== */ #define PIO_PA24D_PIODC0 (1u << 24) /**< \brief Pioa signal: PIODC0 */ #define PIO_PA25D_PIODC1 (1u << 25) /**< \brief Pioa signal: PIODC1 */ #define PIO_PA26D_PIODC2 (1u << 26) /**< \brief Pioa signal: PIODC2 */ #define PIO_PA27D_PIODC3 (1u << 27) /**< \brief Pioa signal: PIODC3 */ #define PIO_PA28D_PIODC4 (1u << 28) /**< \brief Pioa signal: PIODC4 */ #define PIO_PA29D_PIODC5 (1u << 29) /**< \brief Pioa signal: PIODC5 */ #define PIO_PA30D_PIODC6 (1u << 30) /**< \brief Pioa signal: PIODC6 */ #define PIO_PA31D_PIODC7 (1u << 31) /**< \brief Pioa signal: PIODC7 */ #define PIO_PA23D_PIODCCLK (1u << 23) /**< \brief Pioa signal: PIODCCLK */ #define PIO_PA15D_PIODCEN1 (1u << 15) /**< \brief Pioa signal: PIODCEN1 */ #define PIO_PA16D_PIODCEN2 (1u << 16) /**< \brief Pioa signal: PIODCEN2 */ /* ========== Pio definition for PMC peripheral ========== */ #define PIO_PA6B_PCK0 (1u << 6) /**< \brief Pmc signal: PCK0 */ #define PIO_PB13B_PCK0 (1u << 13) /**< \brief Pmc signal: PCK0 */ #define PIO_PA17B_PCK1 (1u << 17) /**< \brief Pmc signal: PCK1 */ #define PIO_PA21B_PCK1 (1u << 21) /**< \brief Pmc signal: PCK1 */ #define PIO_PA18B_PCK2 (1u << 18) /**< \brief Pmc signal: PCK2 */ #define PIO_PA31B_PCK2 (1u << 31) /**< \brief Pmc signal: PCK2 */ #define PIO_PB3B_PCK2 (1u << 3) /**< \brief Pmc signal: PCK2 */ /* ========== Pio definition for PWM peripheral ========== */ #define PIO_PA9C_PWMFI0 (1u << 9) /**< \brief Pwm signal: PWMFI0 */ #define PIO_PA10C_PWMFI1 (1u << 10) /**< \brief Pwm signal: PWMFI1 */ #define PIO_PA18D_PWMFI2 (1u << 18) /**< \brief Pwm signal: PWMFI2 */ #define PIO_PA0A_PWMH0 (1u << 0) /**< \brief Pwm signal: PWMH0 */ #define PIO_PA11B_PWMH0 (1u << 11) /**< \brief Pwm signal: PWMH0 */ #define PIO_PA23B_PWMH0 (1u << 23) /**< \brief Pwm signal: PWMH0 */ #define PIO_PB0A_PWMH0 (1u << 0) /**< \brief Pwm signal: PWMH0 */ #define PIO_PC18B_PWMH0 (1u << 18) /**< \brief Pwm signal: PWMH0 */ #define PIO_PA1A_PWMH1 (1u << 1) /**< \brief Pwm signal: PWMH1 */ #define PIO_PA12B_PWMH1 (1u << 12) /**< \brief Pwm signal: PWMH1 */ #define PIO_PA24B_PWMH1 (1u << 24) /**< \brief Pwm signal: PWMH1 */ #define PIO_PB1A_PWMH1 (1u << 1) /**< \brief Pwm signal: PWMH1 */ #define PIO_PC19B_PWMH1 (1u << 19) /**< \brief Pwm signal: PWMH1 */ #define PIO_PA2A_PWMH2 (1u << 2) /**< \brief Pwm signal: PWMH2 */ #define PIO_PA13B_PWMH2 (1u << 13) /**< \brief Pwm signal: PWMH2 */ #define PIO_PA25B_PWMH2 (1u << 25) /**< \brief Pwm signal: PWMH2 */ #define PIO_PB4B_PWMH2 (1u << 4) /**< \brief Pwm signal: PWMH2 */ #define PIO_PC20B_PWMH2 (1u << 20) /**< \brief Pwm signal: PWMH2 */ #define PIO_PA7B_PWMH3 (1u << 7) /**< \brief Pwm signal: PWMH3 */ #define PIO_PA14B_PWMH3 (1u << 14) /**< \brief Pwm signal: PWMH3 */ #define PIO_PA17C_PWMH3 (1u << 17) /**< \brief Pwm signal: PWMH3 */ #define PIO_PB14B_PWMH3 (1u << 14) /**< \brief Pwm signal: PWMH3 */ #define PIO_PC21B_PWMH3 (1u << 21) /**< \brief Pwm signal: PWMH3 */ #define PIO_PA19B_PWML0 (1u << 19) /**< \brief Pwm signal: PWML0 */ #define PIO_PB5B_PWML0 (1u << 5) /**< \brief Pwm signal: PWML0 */ #define PIO_PC0B_PWML0 (1u << 0) /**< \brief Pwm signal: PWML0 */ #define PIO_PC13B_PWML0 (1u << 13) /**< \brief Pwm signal: PWML0 */ #define PIO_PA20B_PWML1 (1u << 20) /**< \brief Pwm signal: PWML1 */ #define PIO_PB12A_PWML1 (1u << 12) /**< \brief Pwm signal: PWML1 */ #define PIO_PC1B_PWML1 (1u << 1) /**< \brief Pwm signal: PWML1 */ #define PIO_PC15B_PWML1 (1u << 15) /**< \brief Pwm signal: PWML1 */ #define PIO_PA16C_PWML2 (1u << 16) /**< \brief Pwm signal: PWML2 */ #define PIO_PA30A_PWML2 (1u << 30) /**< \brief Pwm signal: PWML2 */ #define PIO_PB13A_PWML2 (1u << 13) /**< \brief Pwm signal: PWML2 */ #define PIO_PC2B_PWML2 (1u << 2) /**< \brief Pwm signal: PWML2 */ #define PIO_PA15C_PWML3 (1u << 15) /**< \brief Pwm signal: PWML3 */ #define PIO_PC3B_PWML3 (1u << 3) /**< \brief Pwm signal: PWML3 */ #define PIO_PC22B_PWML3 (1u << 22) /**< \brief Pwm signal: PWML3 */ /* ========== Pio definition for SPI peripheral ========== */ #define PIO_PA12A_MISO (1u << 12) /**< \brief Spi signal: MISO */ #define PIO_PA13A_MOSI (1u << 13) /**< \brief Spi signal: MOSI */ #define PIO_PA11A_NPCS0 (1u << 11) /**< \brief Spi signal: NPCS0 */ #define PIO_PA9B_NPCS1 (1u << 9) /**< \brief Spi signal: NPCS1 */ #define PIO_PA31A_NPCS1 (1u << 31) /**< \brief Spi signal: NPCS1 */ #define PIO_PB14A_NPCS1 (1u << 14) /**< \brief Spi signal: NPCS1 */ #define PIO_PC4B_NPCS1 (1u << 4) /**< \brief Spi signal: NPCS1 */ #define PIO_PA10B_NPCS2 (1u << 10) /**< \brief Spi signal: NPCS2 */ #define PIO_PA30B_NPCS2 (1u << 30) /**< \brief Spi signal: NPCS2 */ #define PIO_PB2B_NPCS2 (1u << 2) /**< \brief Spi signal: NPCS2 */ #define PIO_PA3B_NPCS3 (1u << 3) /**< \brief Spi signal: NPCS3 */ #define PIO_PA5B_NPCS3 (1u << 5) /**< \brief Spi signal: NPCS3 */ #define PIO_PA22B_NPCS3 (1u << 22) /**< \brief Spi signal: NPCS3 */ #define PIO_PA14A_SPCK (1u << 14) /**< \brief Spi signal: SPCK */ /* ========== Pio definition for SSC peripheral ========== */ #define PIO_PA18A_RD (1u << 18) /**< \brief Ssc signal: RD */ #define PIO_PA20A_RF (1u << 20) /**< \brief Ssc signal: RF */ #define PIO_PA19A_RK (1u << 19) /**< \brief Ssc signal: RK */ #define PIO_PA17A_TD (1u << 17) /**< \brief Ssc signal: TD */ #define PIO_PA15A_TF (1u << 15) /**< \brief Ssc signal: TF */ #define PIO_PA16A_TK (1u << 16) /**< \brief Ssc signal: TK */ /* ========== Pio definition for TC0 peripheral ========== */ #define PIO_PA4B_TCLK0 (1u << 4) /**< \brief Tc0 signal: TCLK0 */ #define PIO_PA28B_TCLK1 (1u << 28) /**< \brief Tc0 signal: TCLK1 */ #define PIO_PA29B_TCLK2 (1u << 29) /**< \brief Tc0 signal: TCLK2 */ #define PIO_PA0B_TIOA0 (1u << 0) /**< \brief Tc0 signal: TIOA0 */ #define PIO_PA15B_TIOA1 (1u << 15) /**< \brief Tc0 signal: TIOA1 */ #define PIO_PA26B_TIOA2 (1u << 26) /**< \brief Tc0 signal: TIOA2 */ #define PIO_PA1B_TIOB0 (1u << 1) /**< \brief Tc0 signal: TIOB0 */ #define PIO_PA16B_TIOB1 (1u << 16) /**< \brief Tc0 signal: TIOB1 */ #define PIO_PA27B_TIOB2 (1u << 27) /**< \brief Tc0 signal: TIOB2 */ /* ========== Pio definition for TC1 peripheral ========== */ #define PIO_PC25B_TCLK3 (1u << 25) /**< \brief Tc1 signal: TCLK3 */ #define PIO_PC28B_TCLK4 (1u << 28) /**< \brief Tc1 signal: TCLK4 */ #define PIO_PC31B_TCLK5 (1u << 31) /**< \brief Tc1 signal: TCLK5 */ #define PIO_PC23B_TIOA3 (1u << 23) /**< \brief Tc1 signal: TIOA3 */ #define PIO_PC26B_TIOA4 (1u << 26) /**< \brief Tc1 signal: TIOA4 */ #define PIO_PC29B_TIOA5 (1u << 29) /**< \brief Tc1 signal: TIOA5 */ #define PIO_PC24B_TIOB3 (1u << 24) /**< \brief Tc1 signal: TIOB3 */ #define PIO_PC27B_TIOB4 (1u << 27) /**< \brief Tc1 signal: TIOB4 */ #define PIO_PC30B_TIOB5 (1u << 30) /**< \brief Tc1 signal: TIOB5 */ /* ========== Pio definition for TWI0 peripheral ========== */ #define PIO_PA4A_TWCK0 (1u << 4) /**< \brief Twi0 signal: TWCK0 */ #define PIO_PA3A_TWD0 (1u << 3) /**< \brief Twi0 signal: TWD0 */ /* ========== Pio definition for TWI1 peripheral ========== */ #define PIO_PB5A_TWCK1 (1u << 5) /**< \brief Twi1 signal: TWCK1 */ #define PIO_PB4A_TWD1 (1u << 4) /**< \brief Twi1 signal: TWD1 */ /* ========== Pio definition for UART0 peripheral ========== */ #define PIO_PA9A_URXD0 (1u << 9) /**< \brief Uart0 signal: URXD0 */ #define PIO_PA10A_UTXD0 (1u << 10) /**< \brief Uart0 signal: UTXD0 */ /* ========== Pio definition for UART1 peripheral ========== */ #define PIO_PB2A_URXD1 (1u << 2) /**< \brief Uart1 signal: URXD1 */ #define PIO_PB3A_UTXD1 (1u << 3) /**< \brief Uart1 signal: UTXD1 */ /* ========== Pio definition for USART0 peripheral ========== */ #define PIO_PA8A_CTS0 (1u << 8) /**< \brief Usart0 signal: CTS0 */ #define PIO_PA7A_RTS0 (1u << 7) /**< \brief Usart0 signal: RTS0 */ #define PIO_PA5A_RXD0 (1u << 5) /**< \brief Usart0 signal: RXD0 */ #define PIO_PA2B_SCK0 (1u << 2) /**< \brief Usart0 signal: SCK0 */ #define PIO_PA6A_TXD0 (1u << 6) /**< \brief Usart0 signal: TXD0 */ /* ========== Pio definition for USART1 peripheral ========== */ #define PIO_PA25A_CTS1 (1u << 25) /**< \brief Usart1 signal: CTS1 */ #define PIO_PA26A_DCD1 (1u << 26) /**< \brief Usart1 signal: DCD1 */ #define PIO_PA28A_DSR1 (1u << 28) /**< \brief Usart1 signal: DSR1 */ #define PIO_PA27A_DTR1 (1u << 27) /**< \brief Usart1 signal: DTR1 */ #define PIO_PA29A_RI1 (1u << 29) /**< \brief Usart1 signal: RI1 */ #define PIO_PA24A_RTS1 (1u << 24) /**< \brief Usart1 signal: RTS1 */ #define PIO_PA21A_RXD1 (1u << 21) /**< \brief Usart1 signal: RXD1 */ #define PIO_PA23A_SCK1 (1u << 23) /**< \brief Usart1 signal: SCK1 */ #define PIO_PA22A_TXD1 (1u << 22) /**< \brief Usart1 signal: TXD1 */ /* ========== Pio indexes ========== */ #define PIO_PA0_IDX 0 #define PIO_PA1_IDX 1 #define PIO_PA2_IDX 2 #define PIO_PA3_IDX 3 #define PIO_PA4_IDX 4 #define PIO_PA5_IDX 5 #define PIO_PA6_IDX 6 #define PIO_PA7_IDX 7 #define PIO_PA8_IDX 8 #define PIO_PA9_IDX 9 #define PIO_PA10_IDX 10 #define PIO_PA11_IDX 11 #define PIO_PA12_IDX 12 #define PIO_PA13_IDX 13 #define PIO_PA14_IDX 14 #define PIO_PA15_IDX 15 #define PIO_PA16_IDX 16 #define PIO_PA17_IDX 17 #define PIO_PA18_IDX 18 #define PIO_PA19_IDX 19 #define PIO_PA20_IDX 20 #define PIO_PA21_IDX 21 #define PIO_PA22_IDX 22 #define PIO_PA23_IDX 23 #define PIO_PA24_IDX 24 #define PIO_PA25_IDX 25 #define PIO_PA26_IDX 26 #define PIO_PA27_IDX 27 #define PIO_PA28_IDX 28 #define PIO_PA29_IDX 29 #define PIO_PA30_IDX 30 #define PIO_PA31_IDX 31 #define PIO_PB0_IDX 32 #define PIO_PB1_IDX 33 #define PIO_PB2_IDX 34 #define PIO_PB3_IDX 35 #define PIO_PB4_IDX 36 #define PIO_PB5_IDX 37 #define PIO_PB6_IDX 38 #define PIO_PB7_IDX 39 #define PIO_PB8_IDX 40 #define PIO_PB9_IDX 41 #define PIO_PB10_IDX 42 #define PIO_PB11_IDX 43 #define PIO_PB12_IDX 44 #define PIO_PB13_IDX 45 #define PIO_PB14_IDX 46 #define PIO_PC0_IDX 64 #define PIO_PC1_IDX 65 #define PIO_PC2_IDX 66 #define PIO_PC3_IDX 67 #define PIO_PC4_IDX 68 #define PIO_PC5_IDX 69 #define PIO_PC6_IDX 70 #define PIO_PC7_IDX 71 #define PIO_PC8_IDX 72 #define PIO_PC9_IDX 73 #define PIO_PC10_IDX 74 #define PIO_PC11_IDX 75 #define PIO_PC12_IDX 76 #define PIO_PC13_IDX 77 #define PIO_PC14_IDX 78 #define PIO_PC15_IDX 79 #define PIO_PC16_IDX 80 #define PIO_PC17_IDX 81 #define PIO_PC18_IDX 82 #define PIO_PC19_IDX 83 #define PIO_PC20_IDX 84 #define PIO_PC21_IDX 85 #define PIO_PC22_IDX 86 #define PIO_PC23_IDX 87 #define PIO_PC24_IDX 88 #define PIO_PC25_IDX 89 #define PIO_PC26_IDX 90 #define PIO_PC27_IDX 91 #define PIO_PC28_IDX 92 #define PIO_PC29_IDX 93 #define PIO_PC30_IDX 94 #define PIO_PC31_IDX 95 #endif /* _SAM4SD32C_PIO_ */
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>direction/unicode-bidi: element as directional character with unicode-bidi unset, ltr</title> <link rel="author" title="Richard Ishida" href='mailto:ishida@w3.org'/> <link rel="help" href='http://www.w3.org/TR/css-writing-modes-3/#text-direction'/> <link rel="match" href='reference/bidi-normal-006.html'/> <meta name="assert" content='If direction is set but unicode-bidi is not set on an inline element, that element will NOT interact with the surrounding text like a strong or neutral directional character.'/> <style type="text/css"> .test span { direction: ltr; } /* the following styles are not part of the test */ .test, .ref { font-size: 150%; border: 1px solid orange; margin: 10px; width: 10em; padding: 5px; clear: both; } input { margin: 5px; } @font-face { font-family: 'ezra_silregular'; src: url('support/sileot-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } .test, .ref { font-family: ezra_silregular, serif; } </style> </head> <body> <p class="instructions" dir="ltr">Test passes if the two boxes are identical.</p> <!--Notes: Key to entities used below: &#x5d0; ... &#x5d5; - The first six Hebrew letters (strongly RTL). &#x202d; - The LRO (left-to-right-override) formatting character. &#x202c; - The PDF (pop directional formatting) formatting character; closes LRO. --> <div class="test"><div dir="ltr">&#x5d0; > <span>b > c</span> > &#x5d3;</div> <div dir="ltr"> &#x5d0; > <span>&#x5d1; > &#x5d2;</span> > &#x5d3;</div> </div> <div class="ref"><div dir="ltr">&#x202d;&#x5d0; &gt; b &gt; c &gt; &#x5d3;&#x202c;</div> <div dir="ltr">&#x202d;&#x5d3; &lt; &#x5d2; &lt; &#x5d1; &lt; &#x5d0;&#x202c;</div> </div> </body></html>
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\ResourceBundle\DependencyInjection\Driver; use PhpSpec\ObjectBehavior; use Sylius\Bundle\ResourceBundle\SyliusResourceBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; /** * @author Arnaud Langlade <aRn0D.dev@gmail.com> */ class DatabaseDriverFactorySpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DatabaseDriverFactory'); } function it_should_create_a_orm_driver_by_default(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default') ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrineORMDriver'); } function it_should_create_a_odm_driver(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default', SyliusResourceBundle::DRIVER_DOCTRINE_MONGODB_ODM) ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrineODMDriver'); } function it_should_create_a_phpcr_driver(ContainerBuilder $container) { $this::get($container, 'prefix', 'resource', 'default', SyliusResourceBundle::DRIVER_DOCTRINE_PHPCR_ODM) ->shouldhaveType('Sylius\Bundle\ResourceBundle\DependencyInjection\Driver\DoctrinePHPCRDriver'); } }
export = function tsd(gulp, plugins) { return plugins.shell.task([ 'tsd reinstall --clean', 'tsd link', 'tsd rebundle' ]); };
// Scintilla source code edit control /** @file KeyWords.h ** Colourise for particular languages. **/ // Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. typedef void (*LexerFunction)(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler); /** * A LexerModule is responsible for lexing and folding a particular language. * The class maintains a list of LexerModules which can be searched to find a * module appropriate to a particular language. */ class LexerModule { protected: const LexerModule *next; int language; LexerFunction fnLexer; LexerFunction fnFolder; const char * const * wordListDescriptions; int styleBits; static const LexerModule *base; static int nextLanguage; public: const char *languageName; LexerModule(int language_, LexerFunction fnLexer_, const char *languageName_=0, LexerFunction fnFolder_=0, const char * const wordListDescriptions_[] = NULL, int styleBits_=5); virtual ~LexerModule() { } int GetLanguage() const { return language; } // -1 is returned if no WordList information is available int GetNumWordLists() const; const char *GetWordListDescription(int index) const; int GetStyleBitsNeeded() const; virtual void Lex(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) const; virtual void Fold(unsigned int startPos, int lengthDoc, int initStyle, WordList *keywordlists[], Accessor &styler) const; static const LexerModule *Find(int language); static const LexerModule *Find(const char *languageName); }; /** * Check if a character is a space. * This is ASCII specific but is safe with chars >= 0x80. */ inline bool isspacechar(unsigned char ch) { return (ch == ' ') || ((ch >= 0x09) && (ch <= 0x0d)); } inline bool iswordchar(char ch) { return isascii(ch) && (isalnum(ch) || ch == '.' || ch == '_'); } inline bool iswordstart(char ch) { return isascii(ch) && (isalnum(ch) || ch == '_'); } inline bool isoperator(char ch) { if (isascii(ch) && isalnum(ch)) return false; // '.' left out as it is used to make up numbers if (ch == '%' || ch == '^' || ch == '&' || ch == '*' || ch == '(' || ch == ')' || ch == '-' || ch == '+' || ch == '=' || ch == '|' || ch == '{' || ch == '}' || ch == '[' || ch == ']' || ch == ':' || ch == ';' || ch == '<' || ch == '>' || ch == ',' || ch == '/' || ch == '?' || ch == '!' || ch == '.' || ch == '~') return true; return false; }
FactoryGirl.define do factory :user do sequence :name do |n| "User #{ n }" end sequence :email do |n| "user#{ n }@user.com" end end end
(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(require,module,exports){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; if (0 == arguments.length) { this._callbacks = {}; return this; } var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks['$' + event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; },{}],2:[function(require,module,exports){ /*! * domready (c) Dustin Diaz 2012 - License MIT */ !function (name, definition) { if (typeof module != 'undefined') module.exports = definition() else if (typeof define == 'function' && typeof define.amd == 'object') {} else this[name] = definition() }('domready', function (ready) { var fns = [], fn, f = false , doc = document , testEl = doc.documentElement , hack = testEl.doScroll , domContentLoaded = 'DOMContentLoaded' , addEventListener = 'addEventListener' , onreadystatechange = 'onreadystatechange' , readyState = 'readyState' , loadedRgx = hack ? /^loaded|^c/ : /^loaded|c/ , loaded = loadedRgx.test(doc[readyState]) function flush(f) { loaded = 1 while (f = fns.shift()) f() } doc[addEventListener] && doc[addEventListener](domContentLoaded, fn = function () { doc.removeEventListener(domContentLoaded, fn, f) flush() }, f) hack && doc.attachEvent(onreadystatechange, fn = function () { if (/^c/.test(doc[readyState])) { doc.detachEvent(onreadystatechange, fn) flush() } }) return (ready = hack ? function (fn) { self != top ? loaded ? fn() : fns.push(fn) : function () { try { testEl.doScroll('left') } catch (e) { return setTimeout(function() { ready(fn) }, 50) } fn() }() } : function (fn) { loaded ? fn() : fns.push(fn) }) }) },{}],3:[function(require,module,exports){ (function (global){ /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function () { var isLoader = typeof define === "function" && define.amd; var objectTypes = { "function": true, "object": true }; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; var root = objectTypes[typeof window] && window || this, freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { root = freeGlobal; } function runInContext(context, exports) { context || (context = root["Object"]()); exports || (exports = root["Object"]()); var Number = context["Number"] || root["Number"], String = context["String"] || root["String"], Object = context["Object"] || root["Object"], Date = context["Date"] || root["Date"], SyntaxError = context["SyntaxError"] || root["SyntaxError"], TypeError = context["TypeError"] || root["TypeError"], Math = context["Math"] || root["Math"], nativeJSON = context["JSON"] || root["JSON"]; if (typeof nativeJSON == "object" && nativeJSON) { exports.stringify = nativeJSON.stringify; exports.parse = nativeJSON.parse; } var objectProto = Object.prototype, getClass = objectProto.toString, isProperty, forEach, undef; var isExtended = new Date(-3509827334573292); try { isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; } catch (exception) {} function has(name) { if (has[name] !== undef) { return has[name]; } var isSupported; if (name == "bug-string-char-index") { isSupported = "a"[0] != "a"; } else if (name == "json") { isSupported = has("json-stringify") && has("json-parse"); } else { var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; if (name == "json-stringify") { var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; if (stringifySupported) { (value = function () { return 1; }).toJSON = value; try { stringifySupported = stringify(0) === "0" && stringify(new Number()) === "0" && stringify(new String()) == '""' && stringify(getClass) === undef && stringify(undef) === undef && stringify() === undef && stringify(value) === "1" && stringify([value]) == "[1]" && stringify([undef]) == "[null]" && stringify(null) == "null" && stringify([undef, getClass, null]) == "[null,null,null]" && stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && stringify(null, value) === "1" && stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; } catch (exception) { stringifySupported = false; } } isSupported = stringifySupported; } if (name == "json-parse") { var parse = exports.parse; if (typeof parse == "function") { try { if (parse("0") === 0 && !parse(false)) { value = parse(serialized); var parseSupported = value["a"].length == 5 && value["a"][0] === 1; if (parseSupported) { try { parseSupported = !parse('"\t"'); } catch (exception) {} if (parseSupported) { try { parseSupported = parse("01") !== 1; } catch (exception) {} } if (parseSupported) { try { parseSupported = parse("1.") !== 1; } catch (exception) {} } } } } catch (exception) { parseSupported = false; } } isSupported = parseSupported; } } return has[name] = !!isSupported; } if (!has("json")) { var functionClass = "[object Function]", dateClass = "[object Date]", numberClass = "[object Number]", stringClass = "[object String]", arrayClass = "[object Array]", booleanClass = "[object Boolean]"; var charIndexBuggy = has("bug-string-char-index"); if (!isExtended) { var floor = Math.floor; var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; var getDay = function (year, month) { return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); }; } if (!(isProperty = objectProto.hasOwnProperty)) { isProperty = function (property) { var members = {}, constructor; if ((members.__proto__ = null, members.__proto__ = { "toString": 1 }, members).toString != getClass) { isProperty = function (property) { var original = this.__proto__, result = property in (this.__proto__ = null, this); this.__proto__ = original; return result; }; } else { constructor = members.constructor; isProperty = function (property) { var parent = (this.constructor || constructor).prototype; return property in this && !(property in parent && this[property] === parent[property]); }; } members = null; return isProperty.call(this, property); }; } forEach = function (object, callback) { var size = 0, Properties, members, property; (Properties = function () { this.valueOf = 0; }).prototype.valueOf = 0; members = new Properties(); for (property in members) { if (isProperty.call(members, property)) { size++; } } Properties = members = null; if (!size) { members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, length; var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; for (property in object) { if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { callback(property); } } for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); }; } else if (size == 2) { forEach = function (object, callback) { var members = {}, isFunction = getClass.call(object) == functionClass, property; for (property in object) { if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { callback(property); } } }; } else { forEach = function (object, callback) { var isFunction = getClass.call(object) == functionClass, property, isConstructor; for (property in object) { if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { callback(property); } } if (isConstructor || isProperty.call(object, (property = "constructor"))) { callback(property); } }; } return forEach(object, callback); }; if (!has("json-stringify")) { var Escapes = { 92: "\\\\", 34: '\\"', 8: "\\b", 12: "\\f", 10: "\\n", 13: "\\r", 9: "\\t" }; var leadingZeroes = "000000"; var toPaddedString = function (width, value) { return (leadingZeroes + (value || 0)).slice(-width); }; var unicodePrefix = "\\u00"; var quote = function (value) { var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); for (; index < length; index++) { var charCode = value.charCodeAt(index); switch (charCode) { case 8: case 9: case 10: case 12: case 13: case 34: case 92: result += Escapes[charCode]; break; default: if (charCode < 32) { result += unicodePrefix + toPaddedString(2, charCode.toString(16)); break; } result += useCharIndex ? symbols[index] : value.charAt(index); } } return result + '"'; }; var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; try { value = object[property]; } catch (exception) {} if (typeof value == "object" && value) { className = getClass.call(value); if (className == dateClass && !isProperty.call(value, "toJSON")) { if (value > -1 / 0 && value < 1 / 0) { if (getDay) { date = floor(value / 864e5); for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); date = 1 + date - getDay(year, month); time = (value % 864e5 + 864e5) % 864e5; hours = floor(time / 36e5) % 24; minutes = floor(time / 6e4) % 60; seconds = floor(time / 1e3) % 60; milliseconds = time % 1e3; } else { year = value.getUTCFullYear(); month = value.getUTCMonth(); date = value.getUTCDate(); hours = value.getUTCHours(); minutes = value.getUTCMinutes(); seconds = value.getUTCSeconds(); milliseconds = value.getUTCMilliseconds(); } value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + "." + toPaddedString(3, milliseconds) + "Z"; } else { value = null; } } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { value = value.toJSON(property); } } if (callback) { value = callback.call(object, property, value); } if (value === null) { return "null"; } className = getClass.call(value); if (className == booleanClass) { return "" + value; } else if (className == numberClass) { return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; } else if (className == stringClass) { return quote("" + value); } if (typeof value == "object") { for (length = stack.length; length--;) { if (stack[length] === value) { throw TypeError(); } } stack.push(value); results = []; prefix = indentation; indentation += whitespace; if (className == arrayClass) { for (index = 0, length = value.length; index < length; index++) { element = serialize(index, value, callback, properties, whitespace, indentation, stack); results.push(element === undef ? "null" : element); } result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; } else { forEach(properties || value, function (property) { var element = serialize(property, value, callback, properties, whitespace, indentation, stack); if (element !== undef) { results.push(quote(property) + ":" + (whitespace ? " " : "") + element); } }); result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; } stack.pop(); return result; } }; exports.stringify = function (source, filter, width) { var whitespace, callback, properties, className; if (objectTypes[typeof filter] && filter) { if ((className = getClass.call(filter)) == functionClass) { callback = filter; } else if (className == arrayClass) { properties = {}; for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); } } if (width) { if ((className = getClass.call(width)) == numberClass) { if ((width -= width % 1) > 0) { for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); } } else if (className == stringClass) { whitespace = width.length <= 10 ? width : width.slice(0, 10); } } return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); }; } if (!has("json-parse")) { var fromCharCode = String.fromCharCode; var Unescapes = { 92: "\\", 34: '"', 47: "/", 98: "\b", 116: "\t", 110: "\n", 102: "\f", 114: "\r" }; var Index, Source; var abort = function () { Index = Source = null; throw SyntaxError(); }; var lex = function () { var source = Source, length = source.length, value, begin, position, isSigned, charCode; while (Index < length) { charCode = source.charCodeAt(Index); switch (charCode) { case 9: case 10: case 13: case 32: Index++; break; case 123: case 125: case 91: case 93: case 58: case 44: value = charIndexBuggy ? source.charAt(Index) : source[Index]; Index++; return value; case 34: for (value = "@", Index++; Index < length;) { charCode = source.charCodeAt(Index); if (charCode < 32) { abort(); } else if (charCode == 92) { charCode = source.charCodeAt(++Index); switch (charCode) { case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: value += Unescapes[charCode]; Index++; break; case 117: begin = ++Index; for (position = Index + 4; Index < position; Index++) { charCode = source.charCodeAt(Index); if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { abort(); } } value += fromCharCode("0x" + source.slice(begin, Index)); break; default: abort(); } } else { if (charCode == 34) { break; } charCode = source.charCodeAt(Index); begin = Index; while (charCode >= 32 && charCode != 92 && charCode != 34) { charCode = source.charCodeAt(++Index); } value += source.slice(begin, Index); } } if (source.charCodeAt(Index) == 34) { Index++; return value; } abort(); default: begin = Index; if (charCode == 45) { isSigned = true; charCode = source.charCodeAt(++Index); } if (charCode >= 48 && charCode <= 57) { if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { abort(); } isSigned = false; for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); if (source.charCodeAt(Index) == 46) { position = ++Index; for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } charCode = source.charCodeAt(Index); if (charCode == 101 || charCode == 69) { charCode = source.charCodeAt(++Index); if (charCode == 43 || charCode == 45) { Index++; } for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); if (position == Index) { abort(); } Index = position; } return +source.slice(begin, Index); } if (isSigned) { abort(); } if (source.slice(Index, Index + 4) == "true") { Index += 4; return true; } else if (source.slice(Index, Index + 5) == "false") { Index += 5; return false; } else if (source.slice(Index, Index + 4) == "null") { Index += 4; return null; } abort(); } } return "$"; }; var get = function (value) { var results, hasMembers; if (value == "$") { abort(); } if (typeof value == "string") { if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { return value.slice(1); } if (value == "[") { results = []; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "]") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "]") { abort(); } } else { abort(); } } if (value == ",") { abort(); } results.push(get(value)); } return results; } else if (value == "{") { results = {}; for (;; hasMembers || (hasMembers = true)) { value = lex(); if (value == "}") { break; } if (hasMembers) { if (value == ",") { value = lex(); if (value == "}") { abort(); } } else { abort(); } } if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { abort(); } results[value.slice(1)] = get(lex()); } return results; } abort(); } return value; }; var update = function (source, property, callback) { var element = walk(source, property, callback); if (element === undef) { delete source[property]; } else { source[property] = element; } }; var walk = function (source, property, callback) { var value = source[property], length; if (typeof value == "object" && value) { if (getClass.call(value) == arrayClass) { for (length = value.length; length--;) { update(value, length, callback); } } else { forEach(value, function (property) { update(value, property, callback); }); } } return callback.call(source, property, value); }; exports.parse = function (source, callback) { var result, value; Index = 0; Source = "" + source; result = get(lex()); if (lex() != "$") { abort(); } Index = Source = null; return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; }; } } exports["runInContext"] = runInContext; return exports; } if (freeExports && !isLoader) { runInContext(root, freeExports); } else { var nativeJSON = root.JSON, previousJSON = root["JSON3"], isRestored = false; var JSON3 = runInContext(root, (root["JSON3"] = { "noConflict": function () { if (!isRestored) { isRestored = true; root.JSON = nativeJSON; root["JSON3"] = previousJSON; nativeJSON = previousJSON = null; } return JSON3; } })); root.JSON = { "parse": JSON3.parse, "stringify": JSON3.stringify }; } if (false) { (function(){ return JSON3; }); } }).call(this); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],4:[function(require,module,exports){ /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; },{}],5:[function(require,module,exports){ /** * Copyright (c) 2011-2014 Felix Gnass * Licensed under the MIT license * http://spin.js.org/ * * Example: var opts = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } var target = document.getElementById('foo') var spinner = new Spinner(opts).spin(target) */ ;(function (root, factory) { /* CommonJS */ if (typeof module == 'object' && module.exports) module.exports = factory() /* AMD module */ else if (typeof define == 'function' && define.amd) {} /* Browser global */ else root.Spinner = factory() }(this, function () { "use strict" var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */ , animations = {} /* Animation rules keyed by their name */ , useCssAnimations /* Whether to use CSS animations or setTimeout */ , sheet /* A stylesheet to hold the @keyframe or VML rules. */ /** * Utility function to create elements. If no tag name is given, * a DIV is created. Optionally properties can be passed. */ function createEl (tag, prop) { var el = document.createElement(tag || 'div') , n for (n in prop) el[n] = prop[n] return el } /** * Appends children and returns the parent. */ function ins (parent /* child1, child2, ...*/) { for (var i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]) } return parent } /** * Creates an opacity keyframe animation rule and returns its name. * Since most mobile Webkits have timing issues with animation-delay, * we create separate rules for each line/segment. */ function addAnimation (alpha, trail, i, lines) { var name = ['opacity', trail, ~~(alpha * 100), i, lines].join('-') , start = 0.01 + i/lines * 100 , z = Math.max(1 - (1-alpha) / trail * (100-start), alpha) , prefix = useCssAnimations.substring(0, useCssAnimations.indexOf('Animation')).toLowerCase() , pre = prefix && '-' + prefix + '-' || '' if (!animations[name]) { sheet.insertRule( '@' + pre + 'keyframes ' + name + '{' + '0%{opacity:' + z + '}' + start + '%{opacity:' + alpha + '}' + (start+0.01) + '%{opacity:1}' + (start+trail) % 100 + '%{opacity:' + alpha + '}' + '100%{opacity:' + z + '}' + '}', sheet.cssRules.length) animations[name] = 1 } return name } /** * Tries various vendor prefixes and returns the first supported property. */ function vendor (el, prop) { var s = el.style , pp , i prop = prop.charAt(0).toUpperCase() + prop.slice(1) if (s[prop] !== undefined) return prop for (i = 0; i < prefixes.length; i++) { pp = prefixes[i]+prop if (s[pp] !== undefined) return pp } } /** * Sets multiple style properties at once. */ function css (el, prop) { for (var n in prop) { el.style[vendor(el, n) || n] = prop[n] } return el } /** * Fills in default values. */ function merge (obj) { for (var i = 1; i < arguments.length; i++) { var def = arguments[i] for (var n in def) { if (obj[n] === undefined) obj[n] = def[n] } } return obj } /** * Returns the line color from the given string or array. */ function getColor (color, idx) { return typeof color == 'string' ? color : color[idx % color.length] } var defaults = { lines: 12 , length: 7 , width: 5 , radius: 10 , scale: 1.0 , corners: 1 , color: '#000' , opacity: 1/4 , rotate: 0 , direction: 1 , speed: 1 , trail: 100 , fps: 20 , zIndex: 2e9 , className: 'spinner' , top: '50%' , left: '50%' , shadow: false , hwaccel: false , position: 'absolute' } /** The constructor */ function Spinner (o) { this.opts = merge(o || {}, Spinner.defaults, defaults) } Spinner.defaults = {} merge(Spinner.prototype, { /** * Adds the spinner to the given target element. If this instance is already * spinning, it is automatically removed from its previous target b calling * stop() internally. */ spin: function (target) { this.stop() var self = this , o = self.opts , el = self.el = createEl(null, {className: o.className}) css(el, { position: o.position , width: 0 , zIndex: o.zIndex , left: o.left , top: o.top }) if (target) { target.insertBefore(el, target.firstChild || null) } el.setAttribute('role', 'progressbar') self.lines(el, self.opts) if (!useCssAnimations) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , alpha , fps = o.fps , f = fps / o.speed , ostep = (1 - o.opacity) / (f * o.trail / 100) , astep = f / o.lines ;(function anim () { i++ for (var j = 0; j < o.lines; j++) { alpha = Math.max(1 - (i + (o.lines - j) * astep) % f * ostep, o.opacity) self.opacity(el, j * o.direction + start, alpha, o) } self.timeout = self.el && setTimeout(anim, ~~(1000 / fps)) })() } return self } /** * Stops and removes the Spinner. */ , stop: function () { var el = this.el if (el) { clearTimeout(this.timeout) if (el.parentNode) el.parentNode.removeChild(el) this.el = undefined } return this } /** * Internal method that draws the individual lines. Will be overwritten * in VML fallback mode below. */ , lines: function (el, o) { var i = 0 , start = (o.lines - 1) * (1 - o.direction) / 2 , seg function fill (color, shadow) { return css(createEl(), { position: 'absolute' , width: o.scale * (o.length + o.width) + 'px' , height: o.scale * o.width + 'px' , background: color , boxShadow: shadow , transformOrigin: 'left' , transform: 'rotate(' + ~~(360/o.lines*i + o.rotate) + 'deg) translate(' + o.scale*o.radius + 'px' + ',0)' , borderRadius: (o.corners * o.scale * o.width >> 1) + 'px' }) } for (; i < o.lines; i++) { seg = css(createEl(), { position: 'absolute' , top: 1 + ~(o.scale * o.width / 2) + 'px' , transform: o.hwaccel ? 'translate3d(0,0,0)' : '' , opacity: o.opacity , animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1 / o.speed + 's linear infinite' }) if (o.shadow) ins(seg, css(fill('#000', '0 0 4px #000'), {top: '2px'})) ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)'))) } return el } /** * Internal method that adjusts the opacity of a single line. * Will be overwritten in VML fallback mode below. */ , opacity: function (el, i, val) { if (i < el.childNodes.length) el.childNodes[i].style.opacity = val } }) function initVML () { /* Utility function to create a VML tag */ function vml (tag, attr) { return createEl('<' + tag + ' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">', attr) } sheet.addRule('.spin-vml', 'behavior:url(#default#VML)') Spinner.prototype.lines = function (el, o) { var r = o.scale * (o.length + o.width) , s = o.scale * 2 * r function grp () { return css( vml('group', { coordsize: s + ' ' + s , coordorigin: -r + ' ' + -r }) , { width: s, height: s } ) } var margin = -(o.width + o.length) * o.scale * 2 + 'px' , g = css(grp(), {position: 'absolute', top: margin, left: margin}) , i function seg (i, dx, filter) { ins( g , ins( css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}) , ins( css( vml('roundrect', {arcsize: o.corners}) , { width: r , height: o.scale * o.width , left: o.scale * o.radius , top: -o.scale * o.width >> 1 , filter: filter } ) , vml('fill', {color: getColor(o.color, i), opacity: o.opacity}) , vml('stroke', {opacity: 0}) ) ) ) } if (o.shadow) for (i = 1; i <= o.lines; i++) { seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)') } for (i = 1; i <= o.lines; i++) seg(i) return ins(el, g) } Spinner.prototype.opacity = function (el, i, val, o) { var c = el.firstChild o = o.shadow && o.lines || 0 if (c && i + o < c.childNodes.length) { c = c.childNodes[i + o]; c = c && c.firstChild; c = c && c.firstChild if (c) c.opacity = val } } } if (typeof document !== 'undefined') { sheet = (function () { var el = createEl('style', {type : 'text/css'}) ins(document.getElementsByTagName('head')[0], el) return el.sheet || el.styleSheet }()) var probe = css(createEl('group'), {behavior: 'url(#default#VML)'}) if (!vendor(probe, 'transform') && probe.adj) initVML() else useCssAnimations = vendor(probe, 'animation') } return Spinner })); },{}],6:[function(require,module,exports){ /** * Module dependencies. */ var Emitter = require('emitter'); var reduce = require('reduce'); var requestBase = require('./request-base'); var isObject = require('./is-object'); /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { root = window; } else if (typeof self !== 'undefined') { root = self; } else { root = this; } /** * Noop. */ function noop(){}; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * TODO: future proof, move to compoent land * * @param {Object} obj * @return {Boolean} * @api private */ function isHost(obj) { var str = {}.toString.call(obj); switch (str) { case '[object File]': case '[object Blob]': case '[object FormData]': return true; default: return false; } } /** * Expose `request`. */ var request = module.exports = require('./request').bind(null, Request); /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || 'file:' != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {} } return false; }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function(s) { return s.trim(); } : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (null != obj[key]) { pushEncodedKeyValuePair(pairs, key, obj[key]); } } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (Array.isArray(val)) { return val.forEach(function(v) { pushEncodedKeyValuePair(pairs, key, v); }); } pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var parts; var pair; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; parts = pair.split('='); obj[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]); } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'application/xml', urlencoded: 'application/x-www-form-urlencoded', 'form': 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': serialize, 'application/json': JSON.stringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; lines.pop(); for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { return /[\/+]json\b/.test(mime); } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ function type(str){ return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ function params(str){ return reduce(str.split(/ *; */), function(obj, str){ var parts = str.split(/ *= */) , key = parts.shift() , val = parts.shift(); if (key && val) obj[key] = val; return obj; }, {}); }; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req, options) { options = options || {}; this.req = req; this.xhr = this.req.xhr; this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined') ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; this.setStatusProperties(this.xhr.status); this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this.setHeaderProperties(this.header); this.body = this.req.method != 'HEAD' ? this.parseBody(this.text ? this.text : this.xhr.response) : null; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ Response.prototype.get = function(field){ return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ Response.prototype.setHeaderProperties = function(header){ var ct = this.header['content-type'] || ''; this.type = type(ct); var obj = params(ct); for (var key in obj) this[key] = obj[key]; }; /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype.parseBody = function(str){ var parse = request.parse[this.type]; if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length || str instanceof Object) ? parse(str) : null; }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ Response.prototype.setStatusProperties = function(status){ if (status === 1223) { status = 204; } var type = status / 100 | 0; this.status = this.statusCode = status; this.statusType = type; this.info = 1 == type; this.ok = 2 == type; this.clientError = 4 == type; this.serverError = 5 == type; this.error = (4 == type || 5 == type) ? this.toError() : false; this.accepted = 202 == status; this.noContent = 204 == status; this.badRequest = 400 == status; this.unauthorized = 401 == status; this.notAcceptable = 406 == status; this.notFound = 404 == status; this.forbidden = 403 == status; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function(){ var req = this.req; var method = req.method; var url = req.url; var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')'; var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; this._header = {}; this.on('end', function(){ var err = null; var res = null; try { res = new Response(self); } catch(e) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = e; err.rawResponse = self.xhr && self.xhr.responseText ? self.xhr.responseText : null; err.statusCode = self.xhr && self.xhr.status ? self.xhr.status : null; return self.callback(err); } self.emit('response', res); if (err) { return self.callback(err, res); } if (res.status >= 200 && res.status < 300) { return self.callback(err, res); } var new_err = new Error(res.statusText || 'Unsuccessful HTTP response'); new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); }); } /** * Mixin `Emitter` and `requestBase`. */ Emitter(Request.prototype); for (var key in requestBase) { Request.prototype[key] = requestBase[key]; } /** * Abort the request, and clear potential timeout. * * @return {Request} * @api public */ Request.prototype.abort = function(){ if (this.aborted) return; this.aborted = true; this.xhr.abort(); this.clearTimeout(); this.emit('abort'); return this; }; /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function(type){ this.set('Content-Type', request.types[type] || type); return this; }; /** * Set responseType to `val`. Presently valid responseTypes are 'blob' and * 'arraybuffer'. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ Request.prototype.responseType = function(val){ this._responseType = val; return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function(type){ this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} pass * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function(user, pass, options){ if (!options) { options = { type: 'basic' } } switch (options.type) { case 'basic': var str = btoa(user + ':' + pass); this.set('Authorization', 'Basic ' + str); break; case 'auto': this.username = user; this.password = pass; break; } return this; }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function(val){ if ('string' != typeof val) val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `filename`. * * ``` js * request.post('/upload') * .attach(new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String} filename * @return {Request} for chaining * @api public */ Request.prototype.attach = function(field, file, filename){ this._getFormData().append(field, file, filename || file.name); return this; }; Request.prototype._getFormData = function(){ if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ Request.prototype.send = function(data){ var obj = isObject(data); var type = this._header['content-type']; if (obj && isObject(this._data)) { for (var key in data) { this._data[key] = data[key]; } } else if ('string' == typeof data) { if (!type) this.type('form'); type = this._header['content-type']; if ('application/x-www-form-urlencoded' == type) { this._data = this._data ? this._data + '&' + data : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!obj || isHost(data)) return this; if (!type) this.type('json'); return this; }; /** * @deprecated */ Response.prototype.parse = function serialize(fn){ if (root.console) { console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0"); } this.serialize(fn); return this; }; Response.prototype.serialize = function serialize(fn){ this._parser = fn; return this; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function(err, res){ var fn = this._callback; this.clearTimeout(); fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function(){ var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; /** * Invoke callback with timeout error. * * @api private */ Request.prototype.timeoutError = function(){ var timeout = this._timeout; var err = new Error('timeout of ' + timeout + 'ms exceeded'); err.timeout = timeout; this.callback(err); }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ Request.prototype.withCredentials = function(){ this._withCredentials = true; return this; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function(fn){ var self = this; var xhr = this.xhr = request.getXHR(); var query = this._query.join('&'); var timeout = this._timeout; var data = this._formData || this._data; this._callback = fn || noop; xhr.onreadystatechange = function(){ if (4 != xhr.readyState) return; var status; try { status = xhr.status } catch(e) { status = 0; } if (0 == status) { if (self.timedout) return self.timeoutError(); if (self.aborted) return; return self.crossDomainError(); } self.emit('end'); }; var handleProgress = function(e){ if (e.total > 0) { e.percent = e.loaded / e.total * 100; } e.direction = 'download'; self.emit('progress', e); }; if (this.hasListeners('progress')) { xhr.onprogress = handleProgress; } try { if (xhr.upload && this.hasListeners('progress')) { xhr.upload.onprogress = handleProgress; } } catch(e) { } if (timeout && !this._timer) { this._timer = setTimeout(function(){ self.timedout = true; self.abort(); }, timeout); } if (query) { query = request.serializeObject(query); this.url += ~this.url.indexOf('?') ? '&' + query : '?' + query; } if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } if (this._withCredentials) xhr.withCredentials = true; if ('GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !isHost(data)) { var contentType = this._header['content-type']; var serialize = this._parser || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!serialize && isJSON(contentType)) serialize = request.serialize['application/json']; if (serialize) data = serialize(data); } for (var field in this.header) { if (null == this.header[field]) continue; xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } this.emit('request', this); xhr.send(typeof data !== 'undefined' ? data : null); return this; }; /** * Expose `Request`. */ request.Request = Request; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.get = function(url, data, fn){ var req = request('GET', url); if ('function' == typeof data) fn = data, data = null; if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.head = function(url, data, fn){ var req = request('HEAD', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional callback `fn(res)`. * * @param {String} url * @param {Function} fn * @return {Request} * @api public */ function del(url, fn){ var req = request('DELETE', url); if (fn) req.end(fn); return req; }; request['del'] = del; request['delete'] = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.patch = function(url, data, fn){ var req = request('PATCH', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} data * @param {Function} fn * @return {Request} * @api public */ request.post = function(url, data, fn){ var req = request('POST', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} data or fn * @param {Function} fn * @return {Request} * @api public */ request.put = function(url, data, fn){ var req = request('PUT', url); if ('function' == typeof data) fn = data, data = null; if (data) req.send(data); if (fn) req.end(fn); return req; }; },{"./is-object":7,"./request":9,"./request-base":8,"emitter":1,"reduce":4}],7:[function(require,module,exports){ /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return null != obj && 'object' == typeof obj; } module.exports = isObject; },{}],8:[function(require,module,exports){ /** * Module of mixed-in functions shared between node and client code */ var isObject = require('./is-object'); /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ exports.clearTimeout = function _clearTimeout(){ this._timeout = 0; clearTimeout(this._timer); return this; }; /** * Force given parser * * Sets the body parser no matter type. * * @param {Function} * @api public */ exports.parse = function parse(fn){ this._parser = fn; return this; }; /** * Set timeout to `ms`. * * @param {Number} ms * @return {Request} for chaining * @api public */ exports.timeout = function timeout(ms){ this._timeout = ms; return this; }; /** * Faux promise support * * @param {Function} fulfill * @param {Function} reject * @return {Request} */ exports.then = function then(fulfill, reject) { return this.end(function(err, res) { err ? reject(err) : fulfill(res); }); } /** * Allow for extension */ exports.use = function use(fn) { fn(this); return this; } /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ exports.get = function(field){ return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ exports.getHeader = exports.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ exports.set = function(field, val){ if (isObject(field)) { for (var key in field) { this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = val; this.header[field] = val; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field */ exports.unset = function(field){ delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val` for "multipart/form-data" * request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * ``` * * @param {String} name * @param {String|Blob|File|Buffer|fs.ReadStream} val * @return {Request} for chaining * @api public */ exports.field = function(name, val) { this._getFormData().append(name, val); return this; }; },{"./is-object":7}],9:[function(require,module,exports){ /** * Issue a request: * * Examples: * * request('GET', '/users').end(callback) * request('/users').end(callback) * request('/users', callback) * * @param {String} method * @param {String|Function} url or callback * @return {Request} * @api public */ function request(RequestConstructor, method, url) { if ('function' == typeof url) { return new RequestConstructor('GET', method).end(url); } if (2 == arguments.length) { return new RequestConstructor('GET', method); } return new RequestConstructor(method, url); } module.exports = request; },{}],10:[function(require,module,exports){ var Keen = require("./index"), each = require("./utils/each"); module.exports = function(){ var loaded = window['Keen'] || null, cached = window['_' + 'Keen'] || null, clients, ready; if (loaded && cached) { clients = cached['clients'] || {}, ready = cached['ready'] || []; each(clients, function(client, id){ each(Keen.prototype, function(method, key){ loaded.prototype[key] = method; }); each(["Query", "Request", "Dataset", "Dataviz"], function(name){ loaded[name] = (Keen[name]) ? Keen[name] : function(){}; }); if (client._config) { client.configure.call(client, client._config); } if (client._setGlobalProperties) { each(client._setGlobalProperties, function(fn){ client.setGlobalProperties.apply(client, fn); }); } if (client._addEvent) { each(client._addEvent, function(obj){ client.addEvent.apply(client, obj); }); } var callback = client._on || []; if (client._on) { each(client._on, function(obj){ client.on.apply(client, obj); }); client.trigger('ready'); } each(["_config", "_setGlobalProperties", "_addEvent", "_on"], function(name){ if (client[name]) { client[name] = undefined; try{ delete client[name]; } catch(e){} } }); }); each(ready, function(cb, i){ Keen.once("ready", cb); }); } window['_' + 'Keen'] = undefined; try { delete window['_' + 'Keen'] } catch(e) {} }; },{"./index":18,"./utils/each":31}],11:[function(require,module,exports){ module.exports = function(){ return "undefined" == typeof window ? "server" : "browser"; }; },{}],12:[function(require,module,exports){ var each = require('../utils/each'), json = require('../utils/json-shim'); module.exports = function(params){ var query = []; each(params, function(value, key){ if ('string' !== typeof value) { value = json.stringify(value); } query.push(key + '=' + encodeURIComponent(value)); }); return '?' + query.join('&'); }; },{"../utils/each":31,"../utils/json-shim":34}],13:[function(require,module,exports){ module.exports = function(){ return new Date().getTimezoneOffset() * -60; }; },{}],14:[function(require,module,exports){ module.exports = function(){ if ("undefined" !== typeof window) { if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) { return 2000; } } return 16000; }; },{}],15:[function(require,module,exports){ module.exports = function() { var root = "undefined" == typeof window ? this : window; if (root.XMLHttpRequest && ("file:" != root.location.protocol || !root.ActiveXObject)) { return new XMLHttpRequest; } else { try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} } return false; }; },{}],16:[function(require,module,exports){ module.exports = function(err, res, callback) { var cb = callback || function() {}; if (res && !res.ok) { var is_err = res.body && res.body.error_code; err = new Error(is_err ? res.body.message : 'Unknown error occurred'); err.code = is_err ? res.body.error_code : 'UnknownError'; } if (err) { cb(err, null); } else { cb(null, res.body); } return; }; },{}],17:[function(require,module,exports){ var superagent = require('superagent'); var each = require('../utils/each'), getXHR = require('./get-xhr-object'); module.exports = function(type, opts){ return function(request) { var __super__ = request.constructor.prototype.end; if ( typeof window === 'undefined' ) return; request.requestType = request.requestType || {}; request.requestType['type'] = type; request.requestType['options'] = request.requestType['options'] || { async: true, success: { responseText: '{ "created": true }', status: 201 }, error: { responseText: '{ "error_code": "ERROR", "message": "Request failed" }', status: 404 } }; if (opts) { if ( typeof opts.async === 'boolean' ) { request.requestType['options'].async = opts.async; } if ( opts.success ) { extend(request.requestType['options'].success, opts.success); } if ( opts.error ) { extend(request.requestType['options'].error, opts.error); } } request.end = function(fn){ var self = this, reqType = (this.requestType) ? this.requestType['type'] : 'xhr', query, timeout; if ( ('GET' !== self['method'] || reqType === 'xhr' ) && self.requestType['options'].async ) { __super__.call(self, fn); return; } query = self._query.join('&'); timeout = self._timeout; self._callback = fn || noop; if (timeout && !self._timer) { self._timer = setTimeout(function(){ abortRequest.call(self); }, timeout); } if (query) { query = superagent.serializeObject(query); self.url += ~self.url.indexOf('?') ? '&' + query : '?' + query; } self.emit('request', self); if ( !self.requestType['options'].async ) { sendXhrSync.call(self); } else if ( reqType === 'jsonp' ) { sendJsonp.call(self); } else if ( reqType === 'beacon' ) { sendBeacon.call(self); } return self; }; return request; }; }; function sendXhrSync(){ var xhr = getXHR(); if (xhr) { xhr.open('GET', this.url, false); xhr.send(null); } return this; } function sendJsonp(){ var self = this, timestamp = new Date().getTime(), script = document.createElement('script'), parent = document.getElementsByTagName('head')[0], callbackName = 'keenJSONPCallback', loaded = false; callbackName += timestamp; while (callbackName in window) { callbackName += 'a'; } window[callbackName] = function(response) { if (loaded === true) return; loaded = true; handleSuccess.call(self, response); cleanup(); }; script.src = self.url + '&jsonp=' + callbackName; parent.appendChild(script); script.onreadystatechange = function() { if (loaded === false && self.readyState === 'loaded') { loaded = true; handleError.call(self); cleanup(); } }; script.onerror = function() { if (loaded === false) { loaded = true; handleError.call(self); cleanup(); } }; function cleanup(){ window[callbackName] = undefined; try { delete window[callbackName]; } catch(e){} parent.removeChild(script); } } function sendBeacon(){ var self = this, img = document.createElement('img'), loaded = false; img.onload = function() { loaded = true; if ('naturalHeight' in this) { if (this.naturalHeight + this.naturalWidth === 0) { this.onerror(); return; } } else if (this.width + this.height === 0) { this.onerror(); return; } handleSuccess.call(self); }; img.onerror = function() { loaded = true; handleError.call(self); }; img.src = self.url + '&c=clv1'; } function handleSuccess(res){ var opts = this.requestType['options']['success'], response = ''; xhrShim.call(this, opts); if (res) { try { response = JSON.stringify(res); } catch(e) {} } else { response = opts['responseText']; } this.xhr.responseText = response; this.xhr.status = opts['status']; this.emit('end'); } function handleError(){ var opts = this.requestType['options']['error']; xhrShim.call(this, opts); this.xhr.responseText = opts['responseText']; this.xhr.status = opts['status']; this.emit('end'); } function abortRequest(){ this.aborted = true; this.clearTimeout(); this.emit('abort'); } function xhrShim(opts){ this.xhr = { getAllResponseHeaders: function(){ return ''; }, getResponseHeader: function(){ return 'application/json'; }, responseText: opts['responseText'], status: opts['status'] }; return this; } },{"../utils/each":31,"./get-xhr-object":15,"superagent":6}],18:[function(require,module,exports){ var root = 'undefined' !== typeof window ? window : this; var previous_Keen = root.Keen; var Emitter = require('./utils/emitter-shim'); function Keen(config) { this.configure(config || {}); Keen.trigger('client', this); } Keen.debug = false; Keen.enabled = true; Keen.loaded = true; Keen.version = '3.4.1'; Emitter(Keen); Emitter(Keen.prototype); Keen.prototype.configure = function(cfg){ var config = cfg || {}; if (config['host']) { config['host'].replace(/.*?:\/\//g, ''); } if (config.protocol && config.protocol === 'auto') { config['protocol'] = location.protocol.replace(/:/g, ''); } this.config = { projectId : config.projectId, writeKey : config.writeKey, readKey : config.readKey, masterKey : config.masterKey, requestType : config.requestType || 'jsonp', host : config['host'] || 'api.keen.io/3.0', protocol : config['protocol'] || 'https', globalProperties: null }; if (Keen.debug) { this.on('error', Keen.log); } this.trigger('ready'); }; Keen.prototype.projectId = function(str){ if (!arguments.length) return this.config.projectId; this.config.projectId = (str ? String(str) : null); return this; }; Keen.prototype.masterKey = function(str){ if (!arguments.length) return this.config.masterKey; this.config.masterKey = (str ? String(str) : null); return this; }; Keen.prototype.readKey = function(str){ if (!arguments.length) return this.config.readKey; this.config.readKey = (str ? String(str) : null); return this; }; Keen.prototype.writeKey = function(str){ if (!arguments.length) return this.config.writeKey; this.config.writeKey = (str ? String(str) : null); return this; }; Keen.prototype.url = function(path){ if (!this.projectId()) { this.trigger('error', 'Client is missing projectId property'); return; } return this.config.protocol + '://' + this.config.host + '/projects/' + this.projectId() + path; }; Keen.log = function(message) { if (Keen.debug && typeof console == 'object') { console.log('[Keen IO]', message); } }; Keen.noConflict = function(){ root.Keen = previous_Keen; return Keen; }; Keen.ready = function(fn){ if (Keen.loaded) { fn(); } else { Keen.once('ready', fn); } }; module.exports = Keen; },{"./utils/emitter-shim":32}],19:[function(require,module,exports){ var json = require('../utils/json-shim'); var request = require('superagent'); var Keen = require('../index'); var base64 = require('../utils/base64'), each = require('../utils/each'), getContext = require('../helpers/get-context'), getQueryString = require('../helpers/get-query-string'), getUrlMaxLength = require('../helpers/get-url-max-length'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(collection, payload, callback, async) { var self = this, urlBase = this.url('/events/' + encodeURIComponent(collection)), reqType = this.config.requestType, data = {}, cb = callback, isAsync, getUrl; isAsync = ('boolean' === typeof async) ? async : true; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (!collection || typeof collection !== 'string') { handleValidationError.call(self, 'Collection name must be a string'); return; } if (self.config.globalProperties) { data = self.config.globalProperties(collection); } each(payload, function(value, key){ data[key] = value; }); if ( !getXHR() && 'xhr' === reqType ) { reqType = 'jsonp'; } if ( 'xhr' !== reqType || !isAsync ) { getUrl = prepareGetRequest.call(self, urlBase, data); } if ( getUrl && getContext() === 'browser' ) { request .get(getUrl) .use(requestTypes(reqType, { async: isAsync })) .end(handleResponse); } else if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(handleResponse); } else { self.trigger('error', 'Request not sent: URL length exceeds current browser limit, and XHR (POST) is not supported.'); } function handleResponse(err, res){ responseHandler(err, res, cb); cb = callback = null; } function handleValidationError(msg){ var err = 'Event not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; function prepareGetRequest(url, data){ url += getQueryString({ api_key : this.writeKey(), data : base64.encode( json.stringify(data) ), modified : new Date().getTime() }); return ( url.length < getUrlMaxLength() ) ? url : false; } },{"../helpers/get-context":11,"../helpers/get-query-string":12,"../helpers/get-url-max-length":14,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/base64":29,"../utils/each":31,"../utils/json-shim":34,"superagent":6}],20:[function(require,module,exports){ var Keen = require('../index'); var request = require('superagent'); var each = require('../utils/each'), getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), requestTypes = require('../helpers/superagent-request-types'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(payload, callback) { var self = this, urlBase = this.url('/events'), data = {}, cb = callback; if (!Keen.enabled) { handleValidationError.call(self, 'Keen.enabled = false'); return; } if (!self.projectId()) { handleValidationError.call(self, 'Missing projectId property'); return; } if (!self.writeKey()) { handleValidationError.call(self, 'Missing writeKey property'); return; } if (arguments.length > 2) { handleValidationError.call(self, 'Incorrect arguments provided to #addEvents method'); return; } if (typeof payload !== 'object' || payload instanceof Array) { handleValidationError.call(self, 'Request payload must be an object'); return; } if (self.config.globalProperties) { each(payload, function(events, collection){ each(events, function(body, index){ var base = self.config.globalProperties(collection); each(body, function(value, key){ base[key] = value; }); data[collection].push(base); }); }); } else { data = payload; } if ( getXHR() || getContext() === 'server' ) { request .post(urlBase) .set('Content-Type', 'application/json') .set('Authorization', self.writeKey()) .send(data) .end(function(err, res){ responseHandler(err, res, cb); cb = callback = null; }); } else { self.trigger('error', 'Events not recorded: XHR support is required for batch upload'); } function handleValidationError(msg){ var err = 'Events not recorded: ' + msg; self.trigger('error', err); if (cb) { cb.call(self, err, null); cb = callback = null; } } return; }; },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"../index":18,"../utils/each":31,"superagent":6}],21:[function(require,module,exports){ var request = require('superagent'); var getQueryString = require('../helpers/get-query-string'), handleResponse = require('../helpers/superagent-handle-response'), requestTypes = require('../helpers/superagent-request-types'); module.exports = function(url, params, api_key, callback){ var reqType = this.config.requestType, data = params || {}; if (reqType === 'beacon') { reqType = 'jsonp'; } data['api_key'] = data['api_key'] || api_key; request .get(url+getQueryString(data)) .use(requestTypes(reqType)) .end(function(err, res){ handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/get-query-string":12,"../helpers/superagent-handle-response":16,"../helpers/superagent-request-types":17,"superagent":6}],22:[function(require,module,exports){ var request = require('superagent'); var handleResponse = require('../helpers/superagent-handle-response'); module.exports = function(url, data, api_key, callback){ request .post(url) .set('Content-Type', 'application/json') .set('Authorization', api_key) .send(data || {}) .end(function(err, res) { handleResponse(err, res, callback); callback = null; }); }; },{"../helpers/superagent-handle-response":16,"superagent":6}],23:[function(require,module,exports){ var Request = require("../request"); module.exports = function(query, callback) { var queries = [], cb = callback, request; if (!this.config.projectId || !this.config.projectId.length) { handleConfigError.call(this, 'Missing projectId property'); } if (!this.config.readKey || !this.config.readKey.length) { handleConfigError.call(this, 'Missing readKey property'); } function handleConfigError(msg){ var err = 'Query not sent: ' + msg; this.trigger('error', err); if (cb) { cb.call(this, err, null); cb = callback = null; } } if (query instanceof Array) { queries = query; } else { queries.push(query); } request = new Request(this, queries, cb).refresh(); cb = callback = null; return request; }; },{"../request":27}],24:[function(require,module,exports){ module.exports = function(newGlobalProperties) { if (newGlobalProperties && typeof(newGlobalProperties) == "function") { this.config.globalProperties = newGlobalProperties; } else { this.trigger("error", "Invalid value for global properties: " + newGlobalProperties); } }; },{}],25:[function(require,module,exports){ var addEvent = require("./addEvent"); module.exports = function(jsEvent, eventCollection, payload, timeout, timeoutCallback){ var evt = jsEvent, target = (evt.currentTarget) ? evt.currentTarget : (evt.srcElement || evt.target), timer = timeout || 500, triggered = false, targetAttr = "", callback, win; if (target.getAttribute !== void 0) { targetAttr = target.getAttribute("target"); } else if (target.target) { targetAttr = target.target; } if ((targetAttr == "_blank" || targetAttr == "blank") && !evt.metaKey) { win = window.open("about:blank"); win.document.location = target.href; } if (target.nodeName === "A") { callback = function(){ if(!triggered && !evt.metaKey && (targetAttr !== "_blank" && targetAttr !== "blank")){ triggered = true; window.location = target.href; } }; } else if (target.nodeName === "FORM") { callback = function(){ if(!triggered){ triggered = true; target.submit(); } }; } else { this.trigger("error", "#trackExternalLink method not attached to an <a> or <form> DOM element"); } if (timeoutCallback) { callback = function(){ if(!triggered){ triggered = true; timeoutCallback(); } }; } addEvent.call(this, eventCollection, payload, callback); setTimeout(callback, timer); if (!evt.metaKey) { return false; } }; },{"./addEvent":19}],26:[function(require,module,exports){ var each = require("./utils/each"), extend = require("./utils/extend"), getTimezoneOffset = require("./helpers/get-timezone-offset"), getQueryString = require("./helpers/get-query-string"); var Emitter = require('./utils/emitter-shim'); function Query(){ this.configure.apply(this, arguments); }; Emitter(Query.prototype); Query.prototype.configure = function(analysisType, params) { this.analysis = analysisType; this.params = this.params || {}; this.set(params); if (this.params.timezone === void 0) { this.params.timezone = getTimezoneOffset(); } return this; }; Query.prototype.set = function(attributes) { var self = this; each(attributes, function(v, k){ var key = k, value = v; if (k.match(new RegExp("[A-Z]"))) { key = k.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } self.params[key] = value; if (value instanceof Array) { each(value, function(dv, index){ if (dv instanceof Array == false && typeof dv === "object") { each(dv, function(deepValue, deepKey){ if (deepKey.match(new RegExp("[A-Z]"))) { var _deepKey = deepKey.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); delete self.params[key][index][deepKey]; self.params[key][index][_deepKey] = deepValue; } }); } }); } }); return self; }; Query.prototype.get = function(attribute) { var key = attribute; if (key.match(new RegExp("[A-Z]"))) { key = key.replace(/([A-Z])/g, function($1) { return "_"+$1.toLowerCase(); }); } if (this.params) { return this.params[key] || null; } }; Query.prototype.addFilter = function(property, operator, value) { this.params.filters = this.params.filters || []; this.params.filters.push({ "property_name": property, "operator": operator, "property_value": value }); return this; }; module.exports = Query; },{"./helpers/get-query-string":12,"./helpers/get-timezone-offset":13,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33}],27:[function(require,module,exports){ var each = require('./utils/each'), extend = require('./utils/extend'), sendQuery = require('./utils/sendQuery'), sendSavedQuery = require('./utils/sendSavedQuery'); var Emitter = require('./utils/emitter-shim'); var Keen = require('./'); var Query = require('./query'); function Request(client, queries, callback){ var cb = callback; this.config = { timeout: 300 * 1000 }; this.configure(client, queries, cb); cb = callback = null; }; Emitter(Request.prototype); Request.prototype.configure = function(client, queries, callback){ var cb = callback; extend(this, { 'client' : client, 'queries' : queries, 'data' : {}, 'callback' : cb }); cb = callback = null; return this; }; Request.prototype.timeout = function(ms){ if (!arguments.length) return this.config.timeout; this.config.timeout = (!isNaN(parseInt(ms)) ? parseInt(ms) : null); return this; }; Request.prototype.refresh = function(){ var self = this, completions = 0, response = [], errored = false; var handleResponse = function(err, res, index){ if (errored) { return; } if (err) { self.trigger('error', err); if (self.callback) { self.callback(err, null); } errored = true; return; } response[index] = res; completions++; if (completions == self.queries.length && !errored) { self.data = (self.queries.length == 1) ? response[0] : response; self.trigger('complete', null, self.data); if (self.callback) { self.callback(null, self.data); } } }; each(self.queries, function(query, index){ var cbSequencer = function(err, res){ handleResponse(err, res, index); }; var path = '/queries'; if (typeof query === 'string') { path += '/saved/' + query + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else if (query instanceof Query) { path += '/' + query.analysis; if (query.analysis === 'saved') { path += '/' + query.params.query_name + '/result'; sendSavedQuery.call(self, path, {}, cbSequencer); } else { sendQuery.call(self, path, query.params, cbSequencer); } } else { var res = { statusText: 'Bad Request', responseText: { message: 'Error: Query ' + (+index+1) + ' of ' + self.queries.length + ' for project ' + self.client.projectId() + ' is not a valid request' } }; self.trigger('error', res.responseText.message); if (self.callback) { self.callback(res.responseText.message, null); } } }); return this; }; module.exports = Request; },{"./":18,"./query":26,"./utils/each":31,"./utils/emitter-shim":32,"./utils/extend":33,"./utils/sendQuery":36,"./utils/sendSavedQuery":37}],28:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('./helpers/superagent-handle-response'); function savedQueries() { var _this = this; this.all = function(callback) { var url = _this.url('/queries/saved'); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.get = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .get(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.update = function(queryName, body, callback) { var url = _this.url('/queries/saved/' + queryName); request .put(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .send(body || {}) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; this.create = this.update; this.destroy = function(queryName, callback) { var url = _this.url('/queries/saved/' + queryName); request .del(url) .set('Content-Type', 'application/json') .set('Authorization', _this.masterKey()) .end(handleResponse); function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } }; return this; } module.exports = savedQueries; },{"./helpers/superagent-handle-response":16,"superagent":6}],29:[function(require,module,exports){ module.exports = { map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", encode: function (n) { "use strict"; var o = "", i = 0, m = this.map, i1, i2, i3, e1, e2, e3, e4; n = this.utf8.encode(n); while (i < n.length) { i1 = n.charCodeAt(i++); i2 = n.charCodeAt(i++); i3 = n.charCodeAt(i++); e1 = (i1 >> 2); e2 = (((i1 & 3) << 4) | (i2 >> 4)); e3 = (isNaN(i2) ? 64 : ((i2 & 15) << 2) | (i3 >> 6)); e4 = (isNaN(i2) || isNaN(i3)) ? 64 : i3 & 63; o = o + m.charAt(e1) + m.charAt(e2) + m.charAt(e3) + m.charAt(e4); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, m = this.map, cc = String.fromCharCode, e1, e2, e3, e4, c1, c2, c3; n = n.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < n.length) { e1 = m.indexOf(n.charAt(i++)); e2 = m.indexOf(n.charAt(i++)); e3 = m.indexOf(n.charAt(i++)); e4 = m.indexOf(n.charAt(i++)); c1 = (e1 << 2) | (e2 >> 4); c2 = ((e2 & 15) << 4) | (e3 >> 2); c3 = ((e3 & 3) << 6) | e4; o = o + (cc(c1) + ((e3 != 64) ? cc(c2) : "")) + (((e4 != 64) ? cc(c3) : "")); } return this.utf8.decode(o); }, utf8: { encode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c; while (i < n.length) { c = n.charCodeAt(i++); o = o + ((c < 128) ? cc(c) : ((c > 127) && (c < 2048)) ? (cc((c >> 6) | 192) + cc((c & 63) | 128)) : (cc((c >> 12) | 224) + cc(((c >> 6) & 63) | 128) + cc((c & 63) | 128))); } return o; }, decode: function (n) { "use strict"; var o = "", i = 0, cc = String.fromCharCode, c2, c; while (i < n.length) { c = n.charCodeAt(i); o = o + ((c < 128) ? [cc(c), i++][0] : ((c > 191) && (c < 224)) ? [cc(((c & 31) << 6) | ((c2 = n.charCodeAt(i + 1)) & 63)), (i += 2)][0] : [cc(((c & 15) << 12) | (((c2 = n.charCodeAt(i + 1)) & 63) << 6) | ((c3 = n.charCodeAt(i + 2)) & 63)), (i += 3)][0]); } return o; } } }; },{}],30:[function(require,module,exports){ var json = require('./json-shim'); module.exports = function(target) { return json.parse( json.stringify( target ) ); }; },{"./json-shim":34}],31:[function(require,module,exports){ module.exports = function(o, cb, s){ var n; if (!o){ return 0; } s = !s ? o : s; if (o instanceof Array){ for (n=0; n<o.length; n++) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } else { for (n in o){ if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false){ return 0; } } } } return 1; }; },{}],32:[function(require,module,exports){ var Emitter = require('component-emitter'); Emitter.prototype.trigger = Emitter.prototype.emit; module.exports = Emitter; },{"component-emitter":1}],33:[function(require,module,exports){ module.exports = function(target){ for (var i = 1; i < arguments.length; i++) { for (var prop in arguments[i]){ target[prop] = arguments[i][prop]; } } return target; }; },{}],34:[function(require,module,exports){ module.exports = ('undefined' !== typeof window && window.JSON) ? window.JSON : require("json3"); },{"json3":3}],35:[function(require,module,exports){ function parseParams(str){ var urlParams = {}, match, pl = /\+/g, search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = str.split("?")[1]; while (!!(match=search.exec(query))) { urlParams[decode(match[1])] = decode(match[2]); } return urlParams; }; module.exports = parseParams; },{}],36:[function(require,module,exports){ var request = require('superagent'); var getContext = require('../helpers/get-context'), getXHR = require('../helpers/get-xhr-object'), responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var url = this.client.url(path); if (!this.client.projectId()) { this.client.trigger('error', 'Query not sent: Missing projectId property'); return; } if (!this.client.readKey()) { this.client.trigger('error', 'Query not sent: Missing readKey property'); return; } if (getContext() === 'server' || getXHR()) { request .post(url) .set('Content-Type', 'application/json') .set('Authorization', this.client.readKey()) .timeout(this.timeout()) .send(params || {}) .end(handleResponse); } function handleResponse(err, res){ responseHandler(err, res, callback); callback = null; } return; } },{"../helpers/get-context":11,"../helpers/get-xhr-object":15,"../helpers/superagent-handle-response":16,"superagent":6}],37:[function(require,module,exports){ var request = require('superagent'); var responseHandler = require('../helpers/superagent-handle-response'); module.exports = function(path, params, callback){ var key; if (this.client.readKey()) { key = this.client.readKey(); } else if (this.client.masterKey()) { key = this.client.masterKey(); } request .get(this.client.url(path)) .set('Content-Type', 'application/json') .set('Authorization', key) .timeout(this.timeout()) .send() .end(function(err, res) { responseHandler(err, res, callback); callback = null; }); return; } },{"../helpers/superagent-handle-response":16,"superagent":6}],38:[function(require,module,exports){ var clone = require("../core/utils/clone"), each = require("../core/utils/each"), flatten = require("./utils/flatten"), parse = require("./utils/parse"); var Emitter = require('../core/utils/emitter-shim'); function Dataset(){ this.data = { input: {}, output: [['Index']] }; this.meta = { schema: {}, method: undefined }; this.parser = undefined; if (arguments.length > 0) { this.parse.apply(this, arguments); } } Dataset.defaults = { delimeter: " -> " }; Emitter(Dataset); Emitter(Dataset.prototype); Dataset.parser = require('./utils/parsers')(Dataset); Dataset.prototype.input = function(obj){ if (!arguments.length) return this["data"]["input"]; this["data"]["input"] = (obj ? clone(obj) : null); return this; }; Dataset.prototype.output = function(arr){ if (!arguments.length) return this["data"].output; this["data"].output = (arr instanceof Array ? arr : null); return this; } Dataset.prototype.method = function(str){ if (!arguments.length) return this.meta["method"]; this.meta["method"] = (str ? String(str) : null); return this; }; Dataset.prototype.schema = function(obj){ if (!arguments.length) return this.meta.schema; this.meta.schema = (obj ? obj : null); return this; }; Dataset.prototype.parse = function(raw, schema){ var options; if (raw) this.input(raw); if (schema) this.schema(schema); this.output([[]]); if (this.meta.schema.select) { this.method("select"); options = extend({ records: "", select: true }, this.schema()); _select.call(this, _optHash(options)); } else if (this.meta.schema.unpack) { this.method("unpack"); options = extend({ records: "", unpack: { index: false, value: false, label: false } }, this.schema()); _unpack.call(this, _optHash(options)); } return this; }; function _select(cfg){ var self = this, options = cfg || {}, target_set = [], unique_keys = []; var root, records_target; if (options.records === "" || !options.records) { root = [self.input()]; } else { records_target = options.records.split(Dataset.defaults.delimeter); root = parse.apply(self, [self.input()].concat(records_target))[0]; } each(options.select, function(prop){ target_set.push(prop.path.split(Dataset.defaults.delimeter)); }); if (target_set.length == 0) { each(root, function(record, interval){ var flat = flatten(record); for (var key in flat) { if (flat.hasOwnProperty(key) && unique_keys.indexOf(key) == -1) { unique_keys.push(key); target_set.push([key]); } } }); } var test = [[]]; each(target_set, function(props, i){ if (target_set.length == 1) { test[0].push('label', 'value'); } else { test[0].push(props.join(".")); } }); each(root, function(record, i){ var flat = flatten(record); if (target_set.length == 1) { test.push([target_set.join("."), flat[target_set.join(".")]]); } else { test.push([]); each(target_set, function(t, j){ var target = t.join("."); test[i+1].push(flat[target]); }); } }); self.output(test); self.format(options.select); return self; } function _unpack(options){ var self = this, discovered_labels = []; var value_set = (options.unpack.value) ? options.unpack.value.path.split(Dataset.defaults.delimeter) : false, label_set = (options.unpack.label) ? options.unpack.label.path.split(Dataset.defaults.delimeter) : false, index_set = (options.unpack.index) ? options.unpack.index.path.split(Dataset.defaults.delimeter) : false; var value_desc = (value_set[value_set.length-1] !== "") ? value_set[value_set.length-1] : "Value", label_desc = (label_set[label_set.length-1] !== "") ? label_set[label_set.length-1] : "Label", index_desc = (index_set[index_set.length-1] !== "") ? index_set[index_set.length-1] : "Index"; var root = (function(){ var root; if (options.records == "") { root = [self.input()]; } else { root = parse.apply(self, [self.input()].concat(options.records.split(Dataset.defaults.delimeter))); } return root[0]; })(); if (root instanceof Array == false) { root = [root]; } each(root, function(record, interval){ var labels = (label_set) ? parse.apply(self, [record].concat(label_set)) : []; if (labels) { discovered_labels = labels; } }); each(root, function(record, interval){ var plucked_value = (value_set) ? parse.apply(self, [record].concat(value_set)) : false, plucked_index = (index_set) ? parse.apply(self, [record].concat(index_set)) : false; if (plucked_index) { each(plucked_index, function(){ self.data.output.push([]); }); } else { self.data.output.push([]); } if (plucked_index) { if (interval == 0) { self.data.output[0].push(index_desc); if (discovered_labels.length > 0) { each(discovered_labels, function(value, i){ self.data.output[0].push(value); }); } else { self.data.output[0].push(value_desc); } } if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_index[i-1]); } }); } } else { self.data.output[interval+1].push(plucked_index[0]); } } if (!plucked_index && discovered_labels.length > 0) { if (interval == 0) { self.data.output[0].push(label_desc); self.data.output[0].push(value_desc); } self.data.output[interval+1].push(discovered_labels[0]); } if (!plucked_index && discovered_labels.length == 0) { self.data.output[0].push(''); } if (plucked_value) { if (root.length < self.data.output.length-1) { if (interval == 0) { each(self.data.output, function(row, i){ if (i > 0) { self.data.output[i].push(plucked_value[i-1]); } }); } } else { each(plucked_value, function(value){ self.data.output[interval+1].push(value); }); } } else { each(self.data.output[0], function(cell, i){ var offset = (plucked_index) ? 0 : -1; if (i > offset) { self.data.output[interval+1].push(null); } }) } }); self.format(options.unpack); return this; } function _optHash(options){ each(options.unpack, function(value, key, object){ if (value && is(value, 'string')) { options.unpack[key] = { path: options.unpack[key] }; } }); return options; } function is(o, t){ o = typeof(o); if (!t){ return o != 'undefined'; } return o == t; } function extend(o, e){ each(e, function(v, n){ if (is(o[n], 'object') && is(v, 'object')){ o[n] = extend(o[n], v); } else if (v !== null) { o[n] = v; } }); return o; } module.exports = Dataset; },{"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"./utils/flatten":51,"./utils/parse":52,"./utils/parsers":53}],39:[function(require,module,exports){ var extend = require("../core/utils/extend"), Dataset = require("./dataset"); extend(Dataset.prototype, require("./lib/append")); extend(Dataset.prototype, require("./lib/delete")); extend(Dataset.prototype, require("./lib/filter")); extend(Dataset.prototype, require("./lib/insert")); extend(Dataset.prototype, require("./lib/select")); extend(Dataset.prototype, require("./lib/set")); extend(Dataset.prototype, require("./lib/sort")); extend(Dataset.prototype, require("./lib/update")); extend(Dataset.prototype, require("./lib/analyses")); extend(Dataset.prototype, { "format": require("./lib/format") }); module.exports = Dataset; },{"../core/utils/extend":33,"./dataset":38,"./lib/analyses":40,"./lib/append":41,"./lib/delete":42,"./lib/filter":43,"./lib/format":44,"./lib/insert":45,"./lib/select":46,"./lib/set":47,"./lib/sort":48,"./lib/update":49}],40:[function(require,module,exports){ var each = require("../../core/utils/each"), arr = ["Average", "Maximum", "Minimum", "Sum"], output = {}; output["average"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0, avg = null; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum / set.length; }; output["maximum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.max.apply(Math, nums); }; output["minimum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), nums = []; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { nums.push(parseFloat(val)); } }); return Math.min.apply(Math, nums); }; output["sum"] = function(arr, start, end){ var set = arr.slice(start||0, (end ? end+1 : arr.length)), sum = 0; each(set, function(val, i){ if (typeof val === "number" && !isNaN(parseFloat(val))) { sum += parseFloat(val); } }); return sum; }; each(arr, function(v,i){ output["getColumn"+v] = output["getRow"+v] = function(arr){ return this[v.toLowerCase()](arr, 1); }; }); output["getColumnLabel"] = output["getRowIndex"] = function(arr){ return arr[0]; }; module.exports = output; },{"../../core/utils/each":31}],41:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); module.exports = { "appendColumn": appendColumn, "appendRow": appendRow }; function appendColumn(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].push(label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].push(cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].push(label); each(input, function(value, i){ self.data.output[i+1][self.data.output[0].length-1] = value; }); } return self; } function appendRow(str, input){ var self = this, args = Array.prototype.slice.call(arguments, 2), label = (str !== undefined) ? str : null, newRow = []; newRow.push(label); if (typeof input === "function") { each(self.data.output[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.push(newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.push( newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50}],42:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "deleteColumn": deleteColumn, "deleteRow": deleteRow }; function deleteColumn(q){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { each(self.data.output, function(row, i){ self.data.output[i].splice(index, 1); }); } return self; } function deleteRow(q){ var index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { this.data.output.splice(index, 1); } return this; } },{"../../core/utils/each":31}],43:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "filterColumns": filterColumns, "filterRows": filterRows }; function filterColumns(fn){ var self = this, clone = new Array(); each(self.data.output, function(row, i){ clone.push([]); }); each(self.data.output[0], function(col, i){ var selectedColumn = self.selectColumn(i); if (i == 0 || fn.call(self, selectedColumn, i)) { each(selectedColumn, function(cell, ri){ clone[ri].push(cell); }); } }); self.output(clone); return self; } function filterRows(fn){ var self = this, clone = []; each(self.output(), function(row, i){ if (i == 0 || fn.call(self, row, i)) { clone.push(row); } }); self.output(clone); return self; } },{"../../core/utils/each":31}],44:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(options){ var self = this; if (this.method() === 'select') { each(self.output(), function(row, i){ if (i == 0) { each(row, function(cell, j){ if (options[j] && options[j].label) { self.data.output[i][j] = options[j].label; } }); } else { each(row, function(cell, j){ self.data.output[i][j] = _applyFormat(self.data.output[i][j], options[j]); }); } }); } if (this.method() === 'unpack') { if (options.index) { each(self.output(), function(row, i){ if (i == 0) { if (options.index.label) { self.data.output[i][0] = options.index.label; } } else { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.index); } }); } if (options.label) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i == 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.label); } }); }); } else { each(self.output(), function(row, i){ if (i > 0) { self.data.output[i][0] = _applyFormat(self.data.output[i][0], options.label); } }); } } if (options.value) { if (options.index) { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0 && j > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } else { each(self.output(), function(row, i){ each(row, function(cell, j){ if (i > 0) { self.data.output[i][j] = _applyFormat(self.data.output[i][j], options.value); } }); }); } } } return self; }; function _applyFormat(value, opts){ var output = value, options = opts || {}; if (options.replace) { each(options.replace, function(val, key){ if (output == key || String(output) == String(key) || parseFloat(output) == parseFloat(key)) { output = val; } }); } if (options.type && options.type == 'date') { if (options.format && moment && moment(value).isValid()) { output = moment(output).format(options.format); } else { output = new Date(output); } } if (options.type && options.type == 'string') { output = String(output); } if (options.type && options.type == 'number' && !isNaN(parseFloat(output))) { output = parseFloat(output); } return output; } },{"../../core/utils/each":31}],45:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "insertColumn": insertColumn, "insertRow": insertRow }; function insertColumn(index, str, input){ var self = this, label; label = (str !== undefined) ? str : null; if (typeof input === "function") { self.data.output[0].splice(index, 0, label); each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row, i); if (typeof cell === "undefined") { cell = null; } self.data.output[i].splice(index, 0, cell); } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } self.data.output[0].splice(index, 0, label); each(input, function(value, i){ self.data.output[i+1].splice(index, 0, value); }); } return self; } function insertRow(index, str, input){ var self = this, label, newRow = []; label = (str !== undefined) ? str : null; newRow.push(label); if (typeof input === "function") { each(self.output()[0], function(label, i){ var col, cell; if (i > 0) { col = self.selectColumn(i); cell = input.call(self, col, i); if (typeof cell === "undefined") { cell = null; } newRow.push(cell); } }); self.data.output.splice(index, 0, newRow); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } self.data.output.splice(index, 0, newRow.concat(input) ); } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],46:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "selectColumn": selectColumn, "selectRow": selectRow }; function selectColumn(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[0][index]) { each(this.data.output, function(row, i){ result.push(row[index]); }); } return result; } function selectRow(q){ var result = new Array(), index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1 && 'undefined' !== typeof this.data.output[index]) { result = this.data.output[index]; } return result; } },{"../../core/utils/each":31}],47:[function(require,module,exports){ var each = require("../../core/utils/each"); var append = require('./append'); var select = require('./select'); module.exports = { "set": set }; function set(coords, value){ if (arguments.length < 2 || coords.length < 2) { throw Error('Incorrect arguments provided for #set method'); } var colIndex = 'number' === typeof coords[0] ? coords[0] : this.data.output[0].indexOf(coords[0]), rowIndex = 'number' === typeof coords[1] ? coords[1] : select.selectColumn.call(this, 0).indexOf(coords[1]); var colResult = select.selectColumn.call(this, coords[0]), rowResult = select.selectRow.call(this, coords[1]); if (colResult.length < 1) { append.appendColumn.call(this, coords[0]); colIndex = this.data.output[0].length-1; } if (rowResult.length < 1) { append.appendRow.call(this, coords[1]); rowIndex = this.data.output.length-1; } this.data.output[ rowIndex ][ colIndex ] = value; return this; } },{"../../core/utils/each":31,"./append":41,"./select":46}],48:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = { "sortColumns": sortColumns, "sortRows": sortRows }; function sortColumns(str, comp){ var self = this, head = this.output()[0].slice(1), cols = [], clone = [], fn = comp || this.getColumnLabel; each(head, function(cell, i){ cols.push(self.selectColumn(i+1).slice(0)); }); cols.sort(function(a,b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); each(cols, function(col, i){ self .deleteColumn(i+1) .insertColumn(i+1, col[0], col.slice(1)); }); return self; } function sortRows(str, comp){ var self = this, head = this.output().slice(0,1), body = this.output().slice(1), fn = comp || this.getRowIndex; body.sort(function(a, b){ var op = fn.call(self, a) > fn.call(self, b); if (op) { return (str === "asc" ? 1 : -1); } else if (!op) { return (str === "asc" ? -1 : 1); } else { return 0; } }); self.output(head.concat(body)); return self; } },{"../../core/utils/each":31}],49:[function(require,module,exports){ var each = require("../../core/utils/each"); var createNullList = require('../utils/create-null-list'); var append = require('./append'); var appendRow = append.appendRow, appendColumn = append.appendColumn; module.exports = { "updateColumn": updateColumn, "updateRow": updateRow }; function updateColumn(q, input){ var self = this, index = (typeof q === 'number') ? q : this.data.output[0].indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output(), function(row, i){ var cell; if (i > 0) { cell = input.call(self, row[index], i, row); if (typeof cell !== "undefined") { self.data.output[i][index] = cell; } } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.output().length - 1) { input = input.concat( createNullList(self.output().length - 1 - input.length) ); } else { each(input, function(value, i){ if (self.data.output.length -1 < input.length) { appendRow.call(self, String( self.data.output.length )); } }); } each(input, function(value, i){ self.data.output[i+1][index] = value; }); } } return self; } function updateRow(q, input){ var self = this, index = (typeof q === 'number') ? q : this.selectColumn(0).indexOf(q); if (index > -1) { if (typeof input === "function") { each(self.output()[index], function(value, i){ var col = self.selectColumn(i), cell = input.call(self, value, i, col); if (typeof cell !== "undefined") { self.data.output[index][i] = cell; } }); } else if (!input || input instanceof Array) { input = input || []; if (input.length <= self.data.output[0].length - 1) { input = input.concat( createNullList( self.data.output[0].length - 1 - input.length ) ); } else { each(input, function(value, i){ if (self.data.output[0].length -1 < input.length) { appendColumn.call(self, String( self.data.output[0].length )); } }); } each(input, function(value, i){ self.data.output[index][i+1] = value; }); } } return self; } },{"../../core/utils/each":31,"../utils/create-null-list":50,"./append":41}],50:[function(require,module,exports){ module.exports = function(len){ var list = new Array(); for (i = 0; i < len; i++) { list.push(null); } return list; }; },{}],51:[function(require,module,exports){ module.exports = flatten; function flatten(ob) { var toReturn = {}; for (var i in ob) { if (!ob.hasOwnProperty(i)) continue; if ((typeof ob[i]) == 'object' && ob[i] !== null) { var flatObject = flatten(ob[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; toReturn[i + '.' + x] = flatObject[x]; } } else { toReturn[i] = ob[i]; } } return toReturn; } },{}],52:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function() { var result = []; var loop = function() { var root = arguments[0]; var args = Array.prototype.slice.call(arguments, 1); var target = args.pop(); if (args.length === 0) { if (root instanceof Array) { args = root; } else if (typeof root === 'object') { args.push(root); } } each(args, function(el){ if (target == "") { if (typeof el == "number" || el == null) { return result.push(el); } } if (el[target] || el[target] === 0 || el[target] !== void 0) { if (el[target] === null) { return result.push(null); } else { return result.push(el[target]); } } else if (root[el]){ if (root[el] instanceof Array) { each(root[el], function(n, i) { var splinter = [root[el]].concat(root[el][i]).concat(args.slice(1)).concat(target); return loop.apply(this, splinter); }); } else { if (root[el][target]) { return result.push(root[el][target]); } else { return loop.apply(this, [root[el]].concat(args.splice(1)).concat(target)); } } } else if (typeof root === 'object' && root instanceof Array === false && !root[target]) { throw new Error("Target property does not exist", target); } else { return loop.apply(this, [el].concat(args.splice(1)).concat(target)); } return; }); if (result.length > 0) { return result; } }; return loop.apply(this, arguments); } },{"../../core/utils/each":31}],53:[function(require,module,exports){ var Dataset; /* injected */ var each = require('../../core/utils/each'), flatten = require('./flatten'); var parsers = { 'metric': parseMetric, 'interval': parseInterval, 'grouped-metric': parseGroupedMetric, 'grouped-interval': parseGroupedInterval, 'double-grouped-metric': parseDoubleGroupedMetric, 'double-grouped-interval': parseDoubleGroupedInterval, 'funnel': parseFunnel, 'list': parseList, 'extraction': parseExtraction }; module.exports = initialize; function initialize(lib){ Dataset = lib; return function(name){ var options = Array.prototype.slice.call(arguments, 1); if (!parsers[name]) { throw 'Requested parser does not exist'; } else { return parsers[name].apply(this, options); } }; } function parseMetric(){ return function(res){ var dataset = new Dataset(); dataset.data.input = res; dataset.parser = { name: 'metric' }; return dataset.set(['Value', 'Result'], res.result); } } function parseInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; dataset.set(['Result', index], record.value); }); dataset.data.input = res; dataset.parser = 'interval'; dataset.parser = { name: 'interval', options: options }; return dataset; } } function parseGroupedMetric(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var label; each(record, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set(['Result', String(record[label])], record.result); }); dataset.data.input = res; dataset.parser = { name: 'grouped-metric' }; return dataset; } } function parseGroupedInterval(){ var options = Array.prototype.slice.call(arguments); return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[0] && options[0] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; if (record.value.length) { each(record.value, function(group, j){ var label; each(group, function(value, key){ if (key !== 'result') { label = key; } }); dataset.set([ String(group[label]) || '', index ], group.result); }); } else { dataset.appendRow(index); } }); dataset.data.input = res; dataset.parser = { name: 'grouped-interval', options: options }; return dataset; } } function parseDoubleGroupedMetric(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ dataset.set([ 'Result', record[options[0][0]] + ' ' + record[options[0][1]] ], record.result); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-metric', options: options }; return dataset; } } function parseDoubleGroupedInterval(){ var options = Array.prototype.slice.call(arguments); if (!options[0]) throw 'Requested parser requires a sequential list (array) of properties to target as a second argument'; return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ var index = options[1] && options[1] === 'timeframe.end' ? record.timeframe.end : record.timeframe.start; each(record['value'], function(value, j){ var label = String(value[options[0][0]]) + ' ' + String(value[options[0][1]]); dataset.set([ label, index ], value.result); }); }); dataset.data.input = res; dataset.parser = { name: 'double-grouped-interval', options: options }; return dataset; } } function parseFunnel(){ return function(res){ var dataset = new Dataset(); dataset.appendColumn('Step Value'); each(res.result, function(value, i){ dataset.appendRow(res.steps[i].event_collection, [ value ]); }); dataset.data.input = res; dataset.parser = { name: 'funnel' }; return dataset; } } function parseList(){ return function(res){ var dataset = new Dataset(); each(res.result, function(value, i){ dataset.set( [ 'Value', i+1 ], value ); }); dataset.data.input = res; dataset.parser = { name: 'list' }; return dataset; } } function parseExtraction(){ return function(res){ var dataset = new Dataset(); each(res.result, function(record, i){ each(flatten(record), function(value, key){ dataset.set([key, i+1], value); }); }); dataset.deleteColumn(0); dataset.data.input = res; dataset.parser = { name: 'extraction' }; return dataset; } } },{"../../core/utils/each":31,"./flatten":51}],54:[function(require,module,exports){ /*! * ---------------------- * C3.js Adapter * ---------------------- */ var Dataviz = require('../dataviz'), each = require('../../core/utils/each'), extend = require('../../core/utils/extend'); getSetupTemplate = require('./c3/get-setup-template') module.exports = function(){ var dataTypes = { 'singular' : ['gauge'], 'categorical' : ['donut', 'pie'], 'cat-interval' : ['area-step', 'step', 'bar', 'area', 'area-spline', 'spline', 'line'], 'cat-ordinal' : ['bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], 'chronological' : ['area', 'area-spline', 'spline', 'line', 'bar', 'step', 'area-step'], 'cat-chronological' : ['line', 'spline', 'area', 'area-spline', 'bar', 'step', 'area-step'] }; var charts = {}; each(['gauge', 'donut', 'pie', 'bar', 'area', 'area-spline', 'spline', 'line', 'step', 'area-step'], function(type, index){ charts[type] = { render: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } this.view._artifacts['c3'] = c3.generate(getSetupTemplate.call(this, type)); this.update(); }, update: function(){ var self = this, cols = []; if (type === 'gauge') { self.view._artifacts['c3'].load({ columns: [ [self.title(), self.data()[1][1]] ] }) } else if (type === 'pie' || type === 'donut') { self.view._artifacts['c3'].load({ columns: self.dataset.data.output.slice(1) }); } else { if (this.dataType().indexOf('chron') > -1) { cols.push(self.dataset.selectColumn(0)); cols[0][0] = 'x'; } each(self.data()[0], function(c, i){ if (i > 0) { cols.push(self.dataset.selectColumn(i)); } }); if (self.stacked()) { self.view._artifacts['c3'].groups([self.labels()]); } self.view._artifacts['c3'].load({ columns: cols }); } }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts['c3']) { this.view._artifacts['c3'].destroy(); this.view._artifacts['c3'] = null; } } Dataviz.register('c3', charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"./c3/get-setup-template":55}],55:[function(require,module,exports){ var extend = require('../../../core/utils/extend'); var clone = require('../../../core/utils/clone'); module.exports = function (type) { var chartOptions = clone(this.chartOptions()); var setup = extend({ axis: {}, color: {}, data: {}, size: {} }, chartOptions); setup.bindto = this.el(); setup.color.pattern = this.colors(); setup.data.columns = []; setup.size.height = this.height(); setup.size.width = this.width(); setup['data']['type'] = type; if (type === 'gauge') {} else if (type === 'pie' || type === 'donut') { setup[type] = { title: this.title() }; } else { if (this.dataType().indexOf('chron') > -1) { setup['data']['x'] = 'x'; setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'timeseries'; setup['axis']['x']['tick'] = setup['axis']['x']['tick'] || { format: this.dateFormat() || getDateFormatDefault(this.data()[1][0], this.data()[2][0]) }; } else { if (this.dataType() === 'cat-ordinal') { setup['axis']['x'] = setup['axis']['x'] || {}; setup['axis']['x']['type'] = 'category'; setup['axis']['x']['categories'] = setup['axis']['x']['categories'] || this.labels() } } if (this.title()) { setup['axis']['y'] = { label: this.title() }; } } return setup; } function getDateFormatDefault(a, b){ var d = Math.abs(new Date(a).getTime() - new Date(b).getTime()); var months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ]; if (d >= 2419200000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getFullYear(); }; } else if (d >= 86400000) { return function(ms){ var date = new Date(ms); return months[date.getMonth()] + ' ' + date.getDate(); }; } else if (d >= 3600000) { return '%I:%M %p'; } else { return '%I:%M:%S %p'; } } },{"../../../core/utils/clone":30,"../../../core/utils/extend":33}],56:[function(require,module,exports){ /*! * ---------------------- * Chart.js Adapter * ---------------------- */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"); module.exports = function(){ if (typeof Chart !== "undefined") { Chart.defaults.global.responsive = true; } var dataTypes = { "categorical" : ["doughnut", "pie", "polar-area", "radar"], "cat-interval" : ["bar", "line"], "cat-ordinal" : ["bar", "line"], "chronological" : ["line", "bar"], "cat-chronological" : ["line", "bar"] }; var ChartNameMap = { "radar": "Radar", "polar-area": "PolarArea", "pie": "Pie", "doughnut": "Doughnut", "line": "Line", "bar": "Bar" }; var dataTransformers = { 'doughnut': getCategoricalData, 'pie': getCategoricalData, 'polar-area': getCategoricalData, 'radar': getSeriesData, 'line': getSeriesData, 'bar': getSeriesData }; function getCategoricalData(){ var self = this, result = []; each(self.dataset.selectColumn(0).slice(1), function(label, i){ result.push({ value: self.dataset.selectColumn(1).slice(1)[i], color: self.colors()[+i], hightlight: self.colors()[+i+9], label: label }); }); return result; } function getSeriesData(){ var self = this, labels, result = { labels: [], datasets: [] }; labels = this.dataset.selectColumn(0).slice(1); each(labels, function(l,i){ if (l instanceof Date) { result.labels.push((l.getMonth()+1) + "-" + l.getDate() + "-" + l.getFullYear()); } else { result.labels.push(l); } }) each(self.dataset.selectRow(0).slice(1), function(label, i){ var hex = { r: hexToR(self.colors()[i]), g: hexToG(self.colors()[i]), b: hexToB(self.colors()[i]) }; result.datasets.push({ label: label, fillColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",0.2)", strokeColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointColor : "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", pointStrokeColor: "#fff", pointHighlightFill: "#fff", pointHighlightStroke: "rgba(" + hex.r + "," + hex.g + "," + hex.b + ",1)", data: self.dataset.selectColumn(+i+1).slice(1) }); }); return result; } var charts = {}; each(["doughnut", "pie", "polar-area", "radar", "bar", "line"], function(type, index){ charts[type] = { initialize: function(){ if (this.data()[0].length === 1 || this.data().length === 1) { this.error('No data to display'); return; } if (this.el().nodeName.toLowerCase() !== "canvas") { var canvas = document.createElement('canvas'); this.el().innerHTML = ""; this.el().appendChild(canvas); this.view._artifacts["ctx"] = canvas.getContext("2d"); } else { this.view._artifacts["ctx"] = this.el().getContext("2d"); } if (this.height()) { this.view._artifacts["ctx"].canvas.height = this.height(); this.view._artifacts["ctx"].canvas.style.height = String(this.height() + "px"); } if (this.width()) { this.view._artifacts["ctx"].canvas.width = this.width(); this.view._artifacts["ctx"].canvas.style.width = String(this.width() + "px"); } return this; }, render: function(){ if(_isEmptyOutput(this.dataset)) { this.error("No data to display"); return; } var method = ChartNameMap[type], opts = extend({}, this.chartOptions()), data = dataTransformers[type].call(this); if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); } this.view._artifacts["chartjs"] = new Chart(this.view._artifacts["ctx"])[method](data, opts); return this; }, destroy: function(){ _selfDestruct.call(this); } }; }); function _selfDestruct(){ if (this.view._artifacts["chartjs"]) { this.view._artifacts["chartjs"].destroy(); this.view._artifacts["chartjs"] = null; } } function _isEmptyOutput(dataset) { var flattened = dataset.output().reduce(function(a, b) { return a.concat(b) }); return flattened.length === 0 } function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)} function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)} function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)} function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h} Dataviz.register("chartjs", charts, { capabilities: dataTypes }); }; },{"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],57:[function(require,module,exports){ /*! * ---------------------- * Google Charts Adapter * ---------------------- */ /* TODO: [ ] Build a more robust DataTable transformer [ ] ^Expose date parser for google charts tooltips (#70) [ ] ^Allow custom tooltips (#147) */ var Dataviz = require("../dataviz"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), Keen = require("../../core"); module.exports = function(){ Keen.loaded = false; var errorMapping = { "Data column(s) for axis #0 cannot be of type string": "No results to visualize" }; var chartTypes = ['AreaChart', 'BarChart', 'ColumnChart', 'LineChart', 'PieChart', 'Table']; var chartMap = {}; var dataTypes = { 'categorical': ['piechart', 'barchart', 'columnchart', 'table'], 'cat-interval': ['columnchart', 'barchart', 'table'], 'cat-ordinal': ['barchart', 'columnchart', 'areachart', 'linechart', 'table'], 'chronological': ['areachart', 'linechart', 'table'], 'cat-chronological': ['linechart', 'columnchart', 'barchart', 'areachart'], 'nominal': ['table'], 'extraction': ['table'] }; each(chartTypes, function (type) { var name = type.toLowerCase(); chartMap[name] = { initialize: function(){ }, render: function(){ if(typeof google === "undefined") { this.error("The Google Charts library could not be loaded."); return; } var self = this; if (self.view._artifacts['googlechart']) { this.destroy(); } self.view._artifacts['googlechart'] = self.view._artifacts['googlechart'] || new google.visualization[type](self.el()); google.visualization.events.addListener(self.view._artifacts['googlechart'], 'error', function(stack){ _handleErrors.call(self, stack); }); this.update(); }, update: function(){ var options = _getDefaultAttributes.call(this, type); extend(options, this.chartOptions(), this.attributes()); options['isStacked'] = (this.stacked() || options['isStacked']); this.view._artifacts['datatable'] = google.visualization.arrayToDataTable(this.data()); if (options.dateFormat) { if (typeof options.dateFormat === 'function') { options.dateFormat(this.view._artifacts['datatable']); } else if (typeof options.dateFormat === 'string') { new google.visualization.DateFormat({ pattern: options.dateFormat }).format(this.view._artifacts['datatable'], 0); } } if (this.view._artifacts['googlechart']) { this.view._artifacts['googlechart'].draw(this.view._artifacts['datatable'], options); } }, destroy: function(){ if (this.view._artifacts['googlechart']) { google.visualization.events.removeAllListeners(this.view._artifacts['googlechart']); this.view._artifacts['googlechart'].clearChart(); this.view._artifacts['googlechart'] = null; this.view._artifacts['datatable'] = null; } } }; }); Dataviz.register('google', chartMap, { capabilities: dataTypes, dependencies: [{ type: 'script', url: 'https://www.google.com/jsapi', cb: function(done) { if (typeof google === 'undefined'){ this.trigger("error", "Problem loading Google Charts library. Please contact us!"); done(); } else { google.load('visualization', '1.1', { packages: ['corechart', 'table'], callback: function(){ done(); } }); } } }] }); function _handleErrors(stack){ var message = errorMapping[stack['message']] || stack['message'] || 'An error occurred'; this.error(message); } function _getDefaultAttributes(type){ var output = {}; switch (type.toLowerCase()) { case "areachart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "barchart": output.hAxis = { viewWindow: { min: 0 } }; output.vAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.vAxis.format = this.dateFormat(); } break; case "columnchart": output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "linechart": output.lineWidth = 2; output.hAxis = { baselineColor: 'transparent', gridlines: { color: 'transparent' } }; output.vAxis = { viewWindow: { min: 0 } }; if (this.dataType() === "chronological" || this.dataType() === "cat-ordinal") { output.legend = "none"; output.chartArea = { width: "85%" }; } if (this.dateFormat() && typeof this.dateFormat() === 'string') { output.hAxis.format = this.dateFormat(); } break; case "piechart": output.sliceVisibilityThreshold = 0.01; break; case "table": break; } return output; } }; },{"../../core":18,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59}],58:[function(require,module,exports){ /*! * ---------------------- * Keen IO Adapter * ---------------------- */ var Keen = require("../../core"), Dataviz = require("../dataviz"); var clone = require("../../core/utils/clone"), each = require("../../core/utils/each"), extend = require("../../core/utils/extend"), prettyNumber = require("../utils/prettyNumber"); module.exports = function(){ var Metric, Error, Spinner; Keen.Error = { defaults: { backgroundColor : "", borderRadius : "4px", color : "#ccc", display : "block", fontFamily : "Helvetica Neue, Helvetica, Arial, sans-serif", fontSize : "21px", fontWeight : "light", textAlign : "center" } }; Keen.Spinner.defaults = { height: 138, lines: 10, length: 8, width: 3, radius: 10, corners: 1, rotate: 0, direction: 1, color: '#4d4d4d', speed: 1.67, trail: 60, shadow: false, hwaccel: false, className: 'keen-spinner', zIndex: 2e9, top: '50%', left: '50%' }; var dataTypes = { 'singular': ['metric'] }; Metric = { initialize: function(){ var css = document.createElement("style"), bgDefault = "#49c5b1"; css.id = "keen-widgets"; css.type = "text/css"; css.innerHTML = "\ .keen-metric { \n background: " + bgDefault + "; \n border-radius: 4px; \n color: #fff; \n font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; \n padding: 10px 0; \n text-align: center; \n} \ .keen-metric-value { \n display: block; \n font-size: 84px; \n font-weight: 700; \n line-height: 84px; \n} \ .keen-metric-title { \n display: block; \n font-size: 24px; \n font-weight: 200; \n}"; if (!document.getElementById(css.id)) { document.body.appendChild(css); } }, render: function(){ var bgColor = (this.colors().length == 1) ? this.colors()[0] : "#49c5b1", title = this.title() || "Result", value = (this.data()[1] && this.data()[1][1]) ? this.data()[1][1] : 0, width = this.width(), opts = this.chartOptions() || {}, prefix = "", suffix = ""; var styles = { 'width': (width) ? width + 'px' : 'auto' }; var formattedNum = value; if ( typeof opts.prettyNumber === 'undefined' || opts.prettyNumber == true ) { if ( !isNaN(parseInt(value)) ) { formattedNum = prettyNumber(value); } } if (opts['prefix']) { prefix = '<span class="keen-metric-prefix">' + opts['prefix'] + '</span>'; } if (opts['suffix']) { suffix = '<span class="keen-metric-suffix">' + opts['suffix'] + '</span>'; } this.el().innerHTML = '' + '<div class="keen-widget keen-metric" style="background-color: ' + bgColor + '; width:' + styles.width + ';" title="' + value + '">' + '<span class="keen-metric-value">' + prefix + formattedNum + suffix + '</span>' + '<span class="keen-metric-title">' + title + '</span>' + '</div>'; } }; Error = { initialize: function(){}, render: function(text, style){ var err, msg; var defaultStyle = clone(Keen.Error.defaults); var currentStyle = extend(defaultStyle, style); err = document.createElement("div"); err.className = "keen-error"; each(currentStyle, function(value, key){ err.style[key] = value; }); err.style.height = String(this.height() + "px"); err.style.paddingTop = (this.height() / 2 - 15) + "px"; err.style.width = String(this.width() + "px"); msg = document.createElement("span"); msg.innerHTML = text || "Yikes! An error occurred!"; err.appendChild(msg); this.el().innerHTML = ""; this.el().appendChild(err); }, destroy: function(){ this.el().innerHTML = ""; } }; Spinner = { initialize: function(){}, render: function(){ var spinner = document.createElement("div"); var height = this.height() || Keen.Spinner.defaults.height; spinner.className = "keen-loading"; spinner.style.height = String(height + "px"); spinner.style.position = "relative"; spinner.style.width = String(this.width() + "px"); this.el().innerHTML = ""; this.el().appendChild(spinner); this.view._artifacts.spinner = new Keen.Spinner(Keen.Spinner.defaults).spin(spinner); }, destroy: function(){ this.view._artifacts.spinner.stop(); this.view._artifacts.spinner = null; } }; Keen.Dataviz.register('keen-io', { 'metric': Metric, 'error': Error, 'spinner': Spinner }, { capabilities: dataTypes }); }; },{"../../core":18,"../../core/utils/clone":30,"../../core/utils/each":31,"../../core/utils/extend":33,"../dataviz":59,"../utils/prettyNumber":98}],59:[function(require,module,exports){ var clone = require('../core/utils/clone'), each = require('../core/utils/each'), extend = require('../core/utils/extend'), loadScript = require('./utils/loadScript'), loadStyle = require('./utils/loadStyle'); var Keen = require('../core'); var Emitter = require('../core/utils/emitter-shim'); var Dataset = require('../dataset'); function Dataviz(){ this.dataset = new Dataset(); this.view = { _prepared: false, _initialized: false, _rendered: false, _artifacts: { /* state bin */ }, adapter: { library: undefined, chartOptions: {}, chartType: undefined, defaultChartType: undefined, dataType: undefined }, attributes: clone(Dataviz.defaults), defaults: clone(Dataviz.defaults), el: undefined, loader: { library: 'keen-io', chartType: 'spinner' } }; Dataviz.visuals.push(this); }; extend(Dataviz, { dataTypeMap: { 'singular': { library: 'keen-io', chartType: 'metric' }, 'categorical': { library: 'google', chartType: 'piechart' }, 'cat-interval': { library: 'google', chartType: 'columnchart' }, 'cat-ordinal': { library: 'google', chartType: 'barchart' }, 'chronological': { library: 'google', chartType: 'areachart' }, 'cat-chronological': { library: 'google', chartType: 'linechart' }, 'extraction': { library: 'google', chartType: 'table' }, 'nominal': { library: 'google', chartType: 'table' } }, defaults: { colors: [ /* teal red yellow purple orange mint blue green lavender */ '#00bbde', '#fe6672', '#eeb058', '#8a8ad6', '#ff855c', '#00cfbb', '#5a9eed', '#73d483', '#c879bb', '#0099b6', '#d74d58', '#cb9141', '#6b6bb6', '#d86945', '#00aa99', '#4281c9', '#57b566', '#ac5c9e', '#27cceb', '#ff818b', '#f6bf71', '#9b9be1', '#ff9b79', '#26dfcd', '#73aff4', '#87e096', '#d88bcb' ], indexBy: 'timeframe.start', stacked: false }, dependencies: { loading: 0, loaded: 0, urls: {} }, libraries: {}, visuals: [] }); Emitter(Dataviz); Emitter(Dataviz.prototype); Dataviz.register = function(name, methods, config){ var self = this; var loadHandler = function(st) { st.loaded++; if(st.loaded === st.loading) { Keen.loaded = true; Keen.trigger('ready'); } }; Dataviz.libraries[name] = Dataviz.libraries[name] || {}; each(methods, function(method, key){ Dataviz.libraries[name][key] = method; }); if (config && config.capabilities) { Dataviz.libraries[name]._defaults = Dataviz.libraries[name]._defaults || {}; each(config.capabilities, function(typeSet, key){ Dataviz.libraries[name]._defaults[key] = typeSet; }); } if (config && config.dependencies) { each(config.dependencies, function (dependency, index, collection) { var status = Dataviz.dependencies; if(!status.urls[dependency.url]) { status.urls[dependency.url] = true; status.loading++; var method = dependency.type === 'script' ? loadScript : loadStyle; method(dependency.url, function() { if(dependency.cb) { dependency.cb.call(self, function() { loadHandler(status); }); } else { loadHandler(status); } }); } }); } }; Dataviz.find = function(target){ if (!arguments.length) return Dataviz.visuals; var el = target.nodeName ? target : document.querySelector(target), match; each(Dataviz.visuals, function(visual){ if (el == visual.el()){ match = visual; return false; } }); if (match) return match; }; module.exports = Dataviz; },{"../core":18,"../core/utils/clone":30,"../core/utils/each":31,"../core/utils/emitter-shim":32,"../core/utils/extend":33,"../dataset":39,"./utils/loadScript":96,"./utils/loadStyle":97}],60:[function(require,module,exports){ var clone = require("../../core/utils/clone"), extend = require("../../core/utils/extend"), Dataviz = require("../dataviz"), Request = require("../../core/request"); module.exports = function(query, el, cfg) { var DEFAULTS = clone(Dataviz.defaults), visual = new Dataviz(), request = new Request(this, [query]), config = cfg || {}; visual .attributes(extend(DEFAULTS, config)) .el(el) .prepare(); request.refresh(); request.on("complete", function(){ visual .parseRequest(this) .call(function(){ if (config.labels) { this.labels(config.labels); } }) .render(); }); request.on("error", function(res){ visual.error(res.message); }); return visual; }; },{"../../core/request":27,"../../core/utils/clone":30,"../../core/utils/extend":33,"../dataviz":59}],61:[function(require,module,exports){ var Dataviz = require("../dataviz"), extend = require("../../core/utils/extend") module.exports = function(){ var map = extend({}, Dataviz.dataTypeMap), dataType = this.dataType(), library = this.library(), chartType = this.chartType() || this.defaultChartType(); if (!library && map[dataType]) { library = map[dataType].library; } if (library && !chartType && dataType) { chartType = Dataviz.libraries[library]._defaults[dataType][0]; } if (library && !chartType && map[dataType]) { chartType = map[dataType].chartType; } if (library && chartType && Dataviz.libraries[library][chartType]) { return Dataviz.libraries[library][chartType]; } else { return {}; } }; },{"../../core/utils/extend":33,"../dataviz":59}],62:[function(require,module,exports){ module.exports = function(req){ var analysis = req.queries[0].analysis.replace("_", " "), collection = req.queries[0].get('event_collection'), output; output = analysis.replace( /\b./g, function(a){ return a.toUpperCase(); }); if (collection) { output += ' - ' + collection; } return output; }; },{}],63:[function(require,module,exports){ module.exports = function(query){ var isInterval = typeof query.params.interval === "string", isGroupBy = typeof query.params.group_by === "string", is2xGroupBy = query.params.group_by instanceof Array, dataType; if (!isGroupBy && !isInterval) { dataType = 'singular'; } if (isGroupBy && !isInterval) { dataType = 'categorical'; } if (isInterval && !isGroupBy) { dataType = 'chronological'; } if (isInterval && isGroupBy) { dataType = 'cat-chronological'; } if (!isInterval && is2xGroupBy) { dataType = 'categorical'; } if (isInterval && is2xGroupBy) { dataType = 'cat-chronological'; } if (query.analysis === "funnel") { dataType = 'cat-ordinal'; } if (query.analysis === "extraction") { dataType = 'extraction'; } if (query.analysis === "select_unique") { dataType = 'nominal'; } return dataType; }; },{}],64:[function(require,module,exports){ var extend = require('../core/utils/extend'), Dataviz = require('./dataviz'); extend(Dataviz.prototype, { 'adapter' : require('./lib/adapter'), 'attributes' : require('./lib/attributes'), 'call' : require('./lib/call'), 'chartOptions' : require('./lib/chartOptions'), 'chartType' : require('./lib/chartType'), 'colorMapping' : require('./lib/colorMapping'), 'colors' : require('./lib/colors'), 'data' : require('./lib/data'), 'dataType' : require('./lib/dataType'), 'dateFormat' : require('./lib/dateFormat'), 'defaultChartType' : require('./lib/defaultChartType'), 'el' : require('./lib/el'), 'height' : require('./lib/height'), 'indexBy' : require('./lib/indexBy'), 'labelMapping' : require('./lib/labelMapping'), 'labels' : require('./lib/labels'), 'library' : require('./lib/library'), 'parseRawData' : require('./lib/parseRawData'), 'parseRequest' : require('./lib/parseRequest'), 'prepare' : require('./lib/prepare'), 'sortGroups' : require('./lib/sortGroups'), 'sortIntervals' : require('./lib/sortIntervals'), 'stacked' : require('./lib/stacked'), 'title' : require('./lib/title'), 'width' : require('./lib/width') }); extend(Dataviz.prototype, { 'destroy' : require('./lib/actions/destroy'), 'error' : require('./lib/actions/error'), 'initialize' : require('./lib/actions/initialize'), 'render' : require('./lib/actions/render'), 'update' : require('./lib/actions/update') }); module.exports = Dataviz; },{"../core/utils/extend":33,"./dataviz":59,"./lib/actions/destroy":65,"./lib/actions/error":66,"./lib/actions/initialize":67,"./lib/actions/render":68,"./lib/actions/update":69,"./lib/adapter":70,"./lib/attributes":71,"./lib/call":72,"./lib/chartOptions":73,"./lib/chartType":74,"./lib/colorMapping":75,"./lib/colors":76,"./lib/data":77,"./lib/dataType":78,"./lib/dateFormat":79,"./lib/defaultChartType":80,"./lib/el":81,"./lib/height":82,"./lib/indexBy":83,"./lib/labelMapping":84,"./lib/labels":85,"./lib/library":86,"./lib/parseRawData":87,"./lib/parseRequest":88,"./lib/prepare":89,"./lib/sortGroups":90,"./lib/sortIntervals":91,"./lib/stacked":92,"./lib/title":93,"./lib/width":94}],65:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"); module.exports = function(){ var actions = getAdapterActions.call(this); if (actions.destroy) { actions.destroy.apply(this, arguments); } if (this.el()) { this.el().innerHTML = ""; } this.view._prepared = false; this.view._initialized = false; this.view._rendered = false; this.view._artifacts = {}; return this; }; },{"../../helpers/getAdapterActions":61}],66:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); if (this.el()) { if (actions['error']) { actions['error'].apply(this, arguments); } else { Dataviz.libraries['keen-io']['error'].render.apply(this, arguments); } } else { this.emit('error', 'No DOM element provided'); } return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],67:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), Dataviz = require("../../dataviz"); module.exports = function(){ var actions = getAdapterActions.call(this); var loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (this.view._prepared) { if (loader.destroy) loader.destroy.apply(this, arguments); } else { if (this.el()) this.el().innerHTML = ""; } if (actions.initialize) { actions.initialize.apply(this, arguments); } else { this.error('Incorrect chartType'); this.emit('error', 'Incorrect chartType'); } this.view._initialized = true; return this; }; },{"../../dataviz":59,"../../helpers/getAdapterActions":61}],68:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (!this.view._initialized) { this.initialize(); } if (this.el() && actions.render) { actions.render.apply(this, arguments); this.view._rendered = true; } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],69:[function(require,module,exports){ var getAdapterActions = require("../../helpers/getAdapterActions"), applyTransforms = require("../../utils/applyTransforms"); module.exports = function(){ var actions = getAdapterActions.call(this); applyTransforms.call(this); if (actions.update) { actions.update.apply(this, arguments); } else if (actions.render) { this.render(); } return this; }; },{"../../helpers/getAdapterActions":61,"../../utils/applyTransforms":95}],70:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view.adapter; var self = this; each(obj, function(prop, key){ self.view.adapter[key] = (prop ? prop : null); }); return this; }; },{"../../core/utils/each":31}],71:[function(require,module,exports){ var each = require("../../core/utils/each"); var chartOptions = require("./chartOptions") chartType = require("./chartType"), library = require("./library"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"]; var self = this; each(obj, function(prop, key){ if (key === "library") { library.call(self, prop); } else if (key === "chartType") { chartType.call(self, prop); } else if (key === "chartOptions") { chartOptions.call(self, prop); } else { self.view["attributes"][key] = prop; } }); return this; }; },{"../../core/utils/each":31,"./chartOptions":73,"./chartType":74,"./library":86}],72:[function(require,module,exports){ module.exports = function(fn){ fn.call(this); return this; }; },{}],73:[function(require,module,exports){ var extend = require('../../core/utils/extend'); module.exports = function(obj){ if (!arguments.length) return this.view.adapter.chartOptions; if (typeof obj === 'object' && obj !== null) { extend(this.view.adapter.chartOptions, obj); } else { this.view.adapter.chartOptions = {}; } return this; }; },{"../../core/utils/extend":33}],74:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.chartType; this.view.adapter.chartType = (str ? String(str) : null); return this; }; },{}],75:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].colorMapping; this.view["attributes"].colorMapping = (obj ? obj : null); colorMapping.call(this); return this; }; function colorMapping(){ var self = this, schema = this.dataset.schema, data = this.dataset.output(), colorSet = this.view.defaults.colors.slice(), colorMap = this.colorMapping(), dt = this.dataType() || ""; if (colorMap) { if (dt.indexOf("chronological") > -1 || (schema.unpack && data[0].length > 2)) { each(data[0].slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } else { each(self.dataset.selectColumn(0).slice(1), function(label, i){ var color = colorMap[label]; if (color && colorSet[i] !== color) { colorSet.splice(i, 0, color); } }); } self.view.attributes.colors = colorSet; } } },{"../../core/utils/each":31}],76:[function(require,module,exports){ module.exports = function(arr){ if (!arguments.length) return this.view["attributes"].colors; this.view["attributes"].colors = (arr instanceof Array ? arr : null); this.view.defaults.colors = (arr instanceof Array ? arr : null); return this; }; },{}],77:[function(require,module,exports){ var Dataset = require("../../dataset"), Request = require("../../core/request"); module.exports = function(data){ if (!arguments.length) return this.dataset.output(); if (data instanceof Dataset) { this.dataset = data; } else if (data instanceof Request) { this.parseRequest(data); } else { this.parseRawData(data); } return this; }; },{"../../core/request":27,"../../dataset":39}],78:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.dataType; this.view.adapter.dataType = (str ? String(str) : null); return this; }; },{}],79:[function(require,module,exports){ module.exports = function(val){ if (!arguments.length) return this.view.attributes.dateFormat; if (typeof val === 'string' || typeof val === 'function') { this.view.attributes.dateFormat = val; } else { this.view.attributes.dateFormat = undefined; } return this; }; },{}],80:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.defaultChartType; this.view.adapter.defaultChartType = (str ? String(str) : null); return this; }; },{}],81:[function(require,module,exports){ module.exports = function(el){ if (!arguments.length) return this.view.el; this.view.el = el; return this; }; },{}],82:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["height"]; this.view["attributes"]["height"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],83:[function(require,module,exports){ var Dataset = require('../../dataset'), Dataviz = require('../dataviz'), each = require('../../core/utils/each'); module.exports = function(str){ if (!arguments.length) return this.view['attributes'].indexBy; this.view['attributes'].indexBy = (str ? String(str) : Dataviz.defaults.indexBy); indexBy.call(this); return this; }; function indexBy(){ var parser, options; if (this.dataset.output().length > 1 && !isNaN(new Date(this.dataset.output()[1][0]).getTime())) { if (this.dataset.parser && this.dataset.parser.name && this.dataset.parser.options) { if (this.dataset.parser.options.length === 1) { parser = Dataset.parser(this.dataset.parser.name, this.indexBy()); this.dataset.parser.options[0] = this.indexBy(); } else { parser = Dataset.parser(this.dataset.parser.name, this.dataset.parser.options[0], this.indexBy()); this.dataset.parser.options[1] = this.indexBy(); } } else if (this.dataset.output()[0].length === 2) { parser = Dataset.parser('interval', this.indexBy()); this.dataset.parser = { name: 'interval', options: [this.indexBy()] }; } else { parser = Dataset.parser('grouped-interval', this.indexBy()); this.dataset.parser = { name: 'grouped-interval', options: [this.indexBy()] }; } this.dataset = parser(this.dataset.input()); this.dataset.updateColumn(0, function(value){ return (typeof value === 'string') ? new Date(value) : value; }); } } },{"../../core/utils/each":31,"../../dataset":39,"../dataviz":59}],84:[function(require,module,exports){ var each = require("../../core/utils/each"); module.exports = function(obj){ if (!arguments.length) return this.view["attributes"].labelMapping; this.view["attributes"].labelMapping = (obj ? obj : null); applyLabelMapping.call(this); return this; }; function applyLabelMapping(){ var self = this, labelMap = this.labelMapping(), dt = this.dataType() || ""; if (labelMap) { if (dt.indexOf("chronological") > -1 || (self.dataset.output()[0].length > 2)) { each(self.dataset.output()[0], function(c, i){ if (i > 0) { self.dataset.data.output[0][i] = labelMap[c] || c; } }); } else if (self.dataset.output()[0].length === 2) { self.dataset.updateColumn(0, function(c, i){ return labelMap[c] || c; }); } } } },{"../../core/utils/each":31}],85:[function(require,module,exports){ var each = require('../../core/utils/each'); module.exports = function(arr){ if (!arguments.length) { if (!this.view['attributes'].labels || !this.view['attributes'].labels.length) { return getLabels.call(this); } else { return this.view['attributes'].labels; } } else { this.view['attributes'].labels = (arr instanceof Array ? arr : null); setLabels.call(this); return this; } }; function setLabels(){ var self = this, labelSet = this.labels() || null, data = this.dataset.output(), dt = this.dataType() || ''; if (labelSet) { if (dt.indexOf('chronological') > -1 || (data[0].length > 2)) { each(data[0], function(cell,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[0][i] = labelSet[i-1]; } }); } else { each(data, function(row,i){ if (i > 0 && labelSet[i-1]) { self.dataset.data.output[i][0] = labelSet[i-1]; } }); } } } function getLabels(){ var data = this.dataset.output(), dt = this.dataType() || '', labels; if (dt.indexOf('chron') > -1 || (data[0].length > 2)) { labels = this.dataset.selectRow(0).slice(1); } else { labels = this.dataset.selectColumn(0).slice(1); } return labels; } },{"../../core/utils/each":31}],86:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view.adapter.library; this.view.adapter.library = (str ? String(str) : null); return this; }; },{}],87:[function(require,module,exports){ var Dataset = require('../../dataset'); var extend = require('../../core/utils/extend'); module.exports = function(response){ var dataType, indexBy = this.indexBy() ? this.indexBy() : 'timestamp.start', parser, parserArgs = [], query = (typeof response.query !== 'undefined') ? response.query : {}; query = extend({ analysis_type: null, event_collection: null, filters: [], group_by: null, interval: null, timeframe: null, timezone: null }, query); if (query.analysis_type === 'funnel') { dataType = 'cat-ordinal'; parser = 'funnel'; } else if (query.analysis_type === 'extraction'){ dataType = 'extraction'; parser = 'extraction'; } else if (query.analysis_type === 'select_unique') { if (!query.group_by && !query.interval) { dataType = 'nominal'; parser = 'list'; } } else if (query.analysis_type) { if (!query.group_by && !query.interval) { dataType = 'singular'; parser = 'metric'; } else if (query.group_by && !query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'categorical'; parser = 'double-grouped-metric'; parserArgs.push(query.group_by); } else { dataType = 'categorical'; parser = 'grouped-metric'; } } else if (query.interval && !query.group_by) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy); } else if (query.group_by && query.interval) { if (query.group_by instanceof Array && query.group_by.length > 1) { dataType = 'cat-chronological'; parser = 'double-grouped-interval'; parserArgs.push(query.group_by); parserArgs.push(indexBy); } else { dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy); } } } if (!parser) { if (typeof response.result === 'number'){ dataType = 'singular'; parser = 'metric'; } if (response.result instanceof Array && response.result.length > 0){ if (response.result[0].timeframe && (typeof response.result[0].value == 'number' || response.result[0].value == null)) { dataType = 'chronological'; parser = 'interval'; parserArgs.push(indexBy) } if (typeof response.result[0].result == 'number'){ dataType = 'categorical'; parser = 'grouped-metric'; } if (response.result[0].value instanceof Array){ dataType = 'cat-chronological'; parser = 'grouped-interval'; parserArgs.push(indexBy) } if (typeof response.result[0] == 'number' && typeof response.steps !== "undefined"){ dataType = 'cat-ordinal'; parser = 'funnel'; } if ((typeof response.result[0] == 'string' || typeof response.result[0] == 'number') && typeof response.steps === "undefined"){ dataType = 'nominal'; parser = 'list'; } if (dataType === void 0) { dataType = 'extraction'; parser = 'extraction'; } } } if (dataType) { this.dataType(dataType); } this.dataset = Dataset.parser.apply(this, [parser].concat(parserArgs))(response); if (parser.indexOf('interval') > -1) { this.dataset.updateColumn(0, function(value, i){ return new Date(value); }); } return this; }; },{"../../core/utils/extend":33,"../../dataset":39}],88:[function(require,module,exports){ var Query = require('../../core/query'); var dataType = require('./dataType'), extend = require('../../core/utils/extend'), getDefaultTitle = require('../helpers/getDefaultTitle'), getQueryDataType = require('../helpers/getQueryDataType'), parseRawData = require('./parseRawData'), title = require('./title'); module.exports = function(req){ var response = req.data instanceof Array ? req.data[0] : req.data; if (req.queries[0] instanceof Query) { response.query = extend({ analysis_type: req.queries[0].analysis }, req.queries[0].params); dataType.call(this, getQueryDataType(req.queries[0])); this.view.defaults.title = getDefaultTitle.call(this, req); if (!title.call(this)) { title.call(this, this.view.defaults.title); } } parseRawData.call(this, response); return this; }; },{"../../core/query":26,"../../core/utils/extend":33,"../helpers/getDefaultTitle":62,"../helpers/getQueryDataType":63,"./dataType":78,"./parseRawData":87,"./title":93}],89:[function(require,module,exports){ var Dataviz = require("../dataviz"); module.exports = function(){ var loader; if (this.view._rendered) { this.destroy(); } if (this.el()) { this.el().innerHTML = ""; loader = Dataviz.libraries[this.view.loader.library][this.view.loader.chartType]; if (loader.initialize) { loader.initialize.apply(this, arguments); } if (loader.render) { loader.render.apply(this, arguments); } this.view._prepared = true; } return this; }; },{"../dataviz":59}],90:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortGroups; this.view["attributes"].sortGroups = (str ? String(str) : null); runSortGroups.call(this); return this; }; function runSortGroups(){ var dt = this.dataType(); if (!this.sortGroups()) return; if ((dt && dt.indexOf("chronological") > -1) || this.data()[0].length > 2) { this.dataset.sortColumns(this.sortGroups(), this.dataset.getColumnSum); } else if (dt && (dt.indexOf("cat-") > -1 || dt.indexOf("categorical") > -1)) { this.dataset.sortRows(this.sortGroups(), this.dataset.getRowSum); } return; } },{}],91:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"].sortIntervals; this.view["attributes"].sortIntervals = (str ? String(str) : null); runSortIntervals.call(this); return this; }; function runSortIntervals(){ if (!this.sortIntervals()) return; this.dataset.sortRows(this.sortIntervals()); return; } },{}],92:[function(require,module,exports){ module.exports = function(bool){ if (!arguments.length) return this.view['attributes']['stacked']; this.view['attributes']['stacked'] = bool ? true : false; return this; }; },{}],93:[function(require,module,exports){ module.exports = function(str){ if (!arguments.length) return this.view["attributes"]["title"]; this.view["attributes"]["title"] = (str ? String(str) : null); return this; }; },{}],94:[function(require,module,exports){ module.exports = function(num){ if (!arguments.length) return this.view["attributes"]["width"]; this.view["attributes"]["width"] = (!isNaN(parseInt(num)) ? parseInt(num) : null); return this; }; },{}],95:[function(require,module,exports){ module.exports = function(){ if (this.labelMapping()) { this.labelMapping(this.labelMapping()); } if (this.colorMapping()) { this.colorMapping(this.colorMapping()); } if (this.sortGroups()) { this.sortGroups(this.sortGroups()); } if (this.sortIntervals()) { this.sortIntervals(this.sortIntervals()); } }; },{}],96:[function(require,module,exports){ module.exports = function(url, cb) { var doc = document; var handler; var head = doc.head || doc.getElementsByTagName("head"); setTimeout(function () { if ('item' in head) { if (!head[0]) { setTimeout(arguments.callee, 25); return; } head = head[0]; } var script = doc.createElement("script"), scriptdone = false; script.onload = script.onreadystatechange = function () { if ((script.readyState && script.readyState !== "complete" && script.readyState !== "loaded") || scriptdone) { return false; } script.onload = script.onreadystatechange = null; scriptdone = true; cb(); }; script.src = url; head.insertBefore(script, head.firstChild); }, 0); if (doc.readyState === null && doc.addEventListener) { doc.readyState = "loading"; doc.addEventListener("DOMContentLoaded", handler = function () { doc.removeEventListener("DOMContentLoaded", handler, false); doc.readyState = "complete"; }, false); } }; },{}],97:[function(require,module,exports){ module.exports = function(url, cb) { var link = document.createElement('link'); link.setAttribute('rel', 'stylesheet'); link.type = 'text/css'; link.href = url; cb(); document.head.appendChild(link); }; },{}],98:[function(require,module,exports){ module.exports = function(_input) { var input = Number(_input), sciNo = input.toPrecision(3), prefix = "", suffixes = ["", "k", "M", "B", "T"]; if (Number(sciNo) == input && String(input).length <= 4) { return String(input); } if(input >= 1 || input <= -1) { if(input < 0){ input = -input; prefix = "-"; } return prefix + recurse(input, 0); } else { return input.toPrecision(3); } function recurse(input, iteration) { var input = String(input); var split = input.split("."); if(split.length > 1) { input = split[0]; var rhs = split[1]; if (input.length == 2 && rhs.length > 0) { if (rhs.length > 0) { input = input + "." + rhs.charAt(0); } else { input += "0"; } } else if (input.length == 1 && rhs.length > 0) { input = input + "." + rhs.charAt(0); if(rhs.length > 1) { input += rhs.charAt(1); } else { input += "0"; } } } var numNumerals = input.length; if (input.split(".").length > 1) { numNumerals--; } if(numNumerals <= 3) { return String(input) + suffixes[iteration]; } else { return recurse(Number(input) / 1000, iteration + 1); } } }; },{}],99:[function(require,module,exports){ (function (global){ ;(function (f) { if (typeof define === "function" && define.amd) { define("keen", [], function(){ return f(); }); } if (typeof exports === "object" && typeof module !== "undefined") { module.exports = f(); } var g = null; if (typeof window !== "undefined") { g = window; } else if (typeof global !== "undefined") { g = global; } else if (typeof self !== "undefined") { g = self; } if (g) { g.Keen = f(); } })(function() { "use strict"; var Keen = require("./core"), extend = require("./core/utils/extend"); extend(Keen.prototype, { "addEvent" : require("./core/lib/addEvent"), "addEvents" : require("./core/lib/addEvents"), "setGlobalProperties" : require("./core/lib/setGlobalProperties"), "trackExternalLink" : require("./core/lib/trackExternalLink"), "get" : require("./core/lib/get"), "post" : require("./core/lib/post"), "put" : require("./core/lib/post"), "run" : require("./core/lib/run"), "savedQueries" : require("./core/saved-queries"), "draw" : require("./dataviz/extensions/draw") }); Keen.Query = require("./core/query"); Keen.Request = require("./core/request"); Keen.Dataset = require("./dataset"); Keen.Dataviz = require("./dataviz"); Keen.Base64 = require("./core/utils/base64"); Keen.Spinner = require("spin.js"); Keen.utils = { "domready" : require("domready"), "each" : require("./core/utils/each"), "extend" : extend, "parseParams" : require("./core/utils/parseParams"), "prettyNumber" : require("./dataviz/utils/prettyNumber") }; require("./dataviz/adapters/keen-io")(); require("./dataviz/adapters/google")(); require("./dataviz/adapters/c3")(); require("./dataviz/adapters/chartjs")(); if (Keen.loaded) { setTimeout(function(){ Keen.utils.domready(function(){ Keen.emit("ready"); }); }, 0); } require("./core/async")(); module.exports = Keen; return Keen; }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./core":18,"./core/async":10,"./core/lib/addEvent":19,"./core/lib/addEvents":20,"./core/lib/get":21,"./core/lib/post":22,"./core/lib/run":23,"./core/lib/setGlobalProperties":24,"./core/lib/trackExternalLink":25,"./core/query":26,"./core/request":27,"./core/saved-queries":28,"./core/utils/base64":29,"./core/utils/each":31,"./core/utils/extend":33,"./core/utils/parseParams":35,"./dataset":39,"./dataviz":64,"./dataviz/adapters/c3":54,"./dataviz/adapters/chartjs":56,"./dataviz/adapters/google":57,"./dataviz/adapters/keen-io":58,"./dataviz/extensions/draw":60,"./dataviz/utils/prettyNumber":98,"domready":2,"spin.js":5}]},{},[99]);
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @fileOverview Defines the {@link CKEDITOR.lang} object, for the * Latvian language. */ /**#@+ @type String @example */ /** * Constains the dictionary of language entries. * @namespace */ CKEDITOR.lang['lv'] = { /** * The language reading direction. Possible values are "rtl" for * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right * languages (like English). * @default 'ltr' */ dir : 'ltr', /* * Screenreader titles. Please note that screenreaders are not always capable * of reading non-English words. So be careful while translating it. */ editorTitle : 'Rich text editor, %1, press ALT 0 for help.', // MISSING // ARIA descriptions. toolbars : 'Editor toolbars', // MISSING editor : 'Rich Text Editor', // MISSING // Toolbar buttons without dialogs. source : 'HTML kods', newPage : 'Jauna lapa', save : 'Saglabāt', preview : 'Pārskatīt', cut : 'Izgriezt', copy : 'Kopēt', paste : 'Ievietot', print : 'Drukāt', underline : 'Apakšsvītra', bold : 'Treknu šriftu', italic : 'Slīprakstā', selectAll : 'Iezīmēt visu', removeFormat : 'Noņemt stilus', strike : 'Pārsvītrots', subscript : 'Zemrakstā', superscript : 'Augšrakstā', horizontalrule : 'Ievietot horizontālu Atdalītājsvītru', pagebreak : 'Ievietot lapas pārtraukumu', pagebreakAlt : 'Page Break', // MISSING unlink : 'Noņemt hipersaiti', undo : 'Atcelt', redo : 'Atkārtot', // Common messages and labels. common : { browseServer : 'Skatīt servera saturu', url : 'URL', protocol : 'Protokols', upload : 'Augšupielādēt', uploadSubmit : 'Nosūtīt serverim', image : 'Attēls', flash : 'Flash', form : 'Forma', checkbox : 'Atzīmēšanas kastīte', radio : 'Izvēles poga', textField : 'Teksta rinda', textarea : 'Teksta laukums', hiddenField : 'Paslēpta teksta rinda', button : 'Poga', select : 'Iezīmēšanas lauks', imageButton : 'Attēlpoga', notSet : '<nav iestatīts>', id : 'Id', name : 'Nosaukums', langDir : 'Valodas lasīšanas virziens', langDirLtr : 'No kreisās uz labo (LTR)', langDirRtl : 'No labās uz kreiso (RTL)', langCode : 'Valodas kods', longDescr : 'Gara apraksta Hipersaite', cssClass : 'Stilu saraksta klases', advisoryTitle : 'Konsultatīvs virsraksts', cssStyle : 'Stils', ok : 'Darīts!', cancel : 'Atcelt', close : 'Close', // MISSING preview : 'Preview', // MISSING generalTab : 'General', // MISSING advancedTab : 'Izvērstais', validateNumberFailed : 'This value is not a number.', // MISSING confirmNewPage : 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING confirmCancel : 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING options : 'Options', // MISSING target : 'Target', // MISSING targetNew : 'New Window (_blank)', // MISSING targetTop : 'Topmost Window (_top)', // MISSING targetSelf : 'Same Window (_self)', // MISSING targetParent : 'Parent Window (_parent)', // MISSING langDirLTR : 'Left to Right (LTR)', // MISSING langDirRTL : 'Right to Left (RTL)', // MISSING styles : 'Style', // MISSING cssClasses : 'Stylesheet Classes', // MISSING width : 'Platums', height : 'Augstums', align : 'Nolīdzināt', alignLeft : 'Pa kreisi', alignRight : 'Pa labi', alignCenter : 'Centrēti', alignTop : 'Augšā', alignMiddle : 'Vertikāli centrēts', alignBottom : 'Apakšā', invalidHeight : 'Height must be a number.', // MISSING invalidWidth : 'Width must be a number.', // MISSING invalidCssLength : 'Value specified for the "%1" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).', // MISSING invalidHtmlLength : 'Value specified for the "%1" field must be a positive number with or without a valid HTML measurement unit (px or %).', // MISSING // Put the voice-only part of the label in the span. unavailable : '%1<span class="cke_accessibility">, unavailable</span>' // MISSING }, contextmenu : { options : 'Context Menu Options' // MISSING }, // Special char dialog. specialChar : { toolbar : 'Ievietot speciālo simbolu', title : 'Ievietot īpašu simbolu', options : 'Special Character Options' // MISSING }, // Link dialog. link : { toolbar : 'Ievietot/Labot hipersaiti', other : '<cits>', menu : 'Labot hipersaiti', title : 'Hipersaite', info : 'Hipersaites informācija', target : 'Mērķis', upload : 'Augšupielādēt', advanced : 'Izvērstais', type : 'Hipersaites tips', toUrl : 'URL', // MISSING toAnchor : 'Iezīme šajā lapā', toEmail : 'E-pasts', targetFrame : '<ietvars>', targetPopup : '<uznirstošā logā>', targetFrameName : 'Mērķa ietvara nosaukums', targetPopupName : 'Uznirstošā loga nosaukums', popupFeatures : 'Uznirstošā loga nosaukums īpašības', popupResizable : 'Resizable', // MISSING popupStatusBar : 'Statusa josla', popupLocationBar: 'Atrašanās vietas josla', popupToolbar : 'Rīku josla', popupMenuBar : 'Izvēlnes josla', popupFullScreen : 'Pilnā ekrānā (IE)', popupScrollBars : 'Ritjoslas', popupDependent : 'Atkarīgs (Netscape)', popupLeft : 'Kreisā koordināte', popupTop : 'Augšējā koordināte', id : 'Id', // MISSING langDir : 'Valodas lasīšanas virziens', langDirLTR : 'No kreisās uz labo (LTR)', langDirRTL : 'No labās uz kreiso (RTL)', acccessKey : 'Pieejas kods', name : 'Nosaukums', langCode : 'Valodas lasīšanas virziens', tabIndex : 'Ciļņu indekss', advisoryTitle : 'Konsultatīvs virsraksts', advisoryContentType : 'Konsultatīvs satura tips', cssClasses : 'Stilu saraksta klases', charset : 'Pievienotā resursa kodu tabula', styles : 'Stils', rel : 'Relationship', // MISSING selectAnchor : 'Izvēlēties iezīmi', anchorName : 'Pēc iezīmes nosaukuma', anchorId : 'Pēc elementa ID', emailAddress : 'E-pasta adrese', emailSubject : 'Ziņas tēma', emailBody : 'Ziņas saturs', noAnchors : '(Šajā dokumentā nav iezīmju)', noUrl : 'Lūdzu norādi hipersaiti', noEmail : 'Lūdzu norādi e-pasta adresi' }, // Anchor dialog anchor : { toolbar : 'Ievietot/Labot iezīmi', menu : 'Iezīmes īpašības', title : 'Iezīmes īpašības', name : 'Iezīmes nosaukums', errorName : 'Lūdzu norādiet iezīmes nosaukumu', remove : 'Remove Anchor' // MISSING }, // List style dialog list: { numberedTitle : 'Numbered List Properties', // MISSING bulletedTitle : 'Bulleted List Properties', // MISSING type : 'Type', // MISSING start : 'Start', // MISSING validateStartNumber :'List start number must be a whole number.', // MISSING circle : 'Circle', // MISSING disc : 'Disc', // MISSING square : 'Square', // MISSING none : 'None', // MISSING notset : '<not set>', // MISSING armenian : 'Armenian numbering', // MISSING georgian : 'Georgian numbering (an, ban, gan, etc.)', // MISSING lowerRoman : 'Lower Roman (i, ii, iii, iv, v, etc.)', // MISSING upperRoman : 'Upper Roman (I, II, III, IV, V, etc.)', // MISSING lowerAlpha : 'Lower Alpha (a, b, c, d, e, etc.)', // MISSING upperAlpha : 'Upper Alpha (A, B, C, D, E, etc.)', // MISSING lowerGreek : 'Lower Greek (alpha, beta, gamma, etc.)', // MISSING decimal : 'Decimal (1, 2, 3, etc.)', // MISSING decimalLeadingZero : 'Decimal leading zero (01, 02, 03, etc.)' // MISSING }, // Find And Replace Dialog findAndReplace : { title : 'Find and Replace', // MISSING find : 'Meklēt', replace : 'Nomainīt', findWhat : 'Meklēt:', replaceWith : 'Nomainīt uz:', notFoundMsg : 'Norādītā frāze netika atrasta.', matchCase : 'Reģistrjūtīgs', matchWord : 'Jāsakrīt pilnībā', matchCyclic : 'Match cyclic', // MISSING replaceAll : 'Aizvietot visu', replaceSuccessMsg : '%1 occurrence(s) replaced.' // MISSING }, // Table Dialog table : { toolbar : 'Tabula', title : 'Tabulas īpašības', menu : 'Tabulas īpašības', deleteTable : 'Dzēst tabulu', rows : 'Rindas', columns : 'Kolonnas', border : 'Rāmja izmērs', widthPx : 'pikseļos', widthPc : 'procentuāli', widthUnit : 'width unit', // MISSING cellSpace : 'Rūtiņu atstatums', cellPad : 'Rūtiņu nobīde', caption : 'Leģenda', summary : 'Anotācija', headers : 'Headers', // MISSING headersNone : 'None', // MISSING headersColumn : 'First column', // MISSING headersRow : 'First Row', // MISSING headersBoth : 'Both', // MISSING invalidRows : 'Number of rows must be a number greater than 0.', // MISSING invalidCols : 'Number of columns must be a number greater than 0.', // MISSING invalidBorder : 'Border size must be a number.', // MISSING invalidWidth : 'Table width must be a number.', // MISSING invalidHeight : 'Table height must be a number.', // MISSING invalidCellSpacing : 'Cell spacing must be a positive number.', // MISSING invalidCellPadding : 'Cell padding must be a positive number.', // MISSING cell : { menu : 'Šūna', insertBefore : 'Insert Cell Before', // MISSING insertAfter : 'Insert Cell After', // MISSING deleteCell : 'Dzēst rūtiņas', merge : 'Apvienot rūtiņas', mergeRight : 'Merge Right', // MISSING mergeDown : 'Merge Down', // MISSING splitHorizontal : 'Split Cell Horizontally', // MISSING splitVertical : 'Split Cell Vertically', // MISSING title : 'Cell Properties', // MISSING cellType : 'Cell Type', // MISSING rowSpan : 'Rows Span', // MISSING colSpan : 'Columns Span', // MISSING wordWrap : 'Word Wrap', // MISSING hAlign : 'Horizontal Alignment', // MISSING vAlign : 'Vertical Alignment', // MISSING alignBaseline : 'Baseline', // MISSING bgColor : 'Background Color', // MISSING borderColor : 'Border Color', // MISSING data : 'Data', // MISSING header : 'Header', // MISSING yes : 'Yes', // MISSING no : 'No', // MISSING invalidWidth : 'Cell width must be a number.', // MISSING invalidHeight : 'Cell height must be a number.', // MISSING invalidRowSpan : 'Rows span must be a whole number.', // MISSING invalidColSpan : 'Columns span must be a whole number.', // MISSING chooseColor : 'Choose' // MISSING }, row : { menu : 'Rinda', insertBefore : 'Insert Row Before', // MISSING insertAfter : 'Insert Row After', // MISSING deleteRow : 'Dzēst rindas' }, column : { menu : 'Kolonna', insertBefore : 'Insert Column Before', // MISSING insertAfter : 'Insert Column After', // MISSING deleteColumn : 'Dzēst kolonnas' } }, // Button Dialog. button : { title : 'Pogas īpašības', text : 'Teksts (vērtība)', type : 'Tips', typeBtn : 'Button', // MISSING typeSbm : 'Submit', // MISSING typeRst : 'Reset' // MISSING }, // Checkbox and Radio Button Dialogs. checkboxAndRadio : { checkboxTitle : 'Atzīmēšanas kastītes īpašības', radioTitle : 'Izvēles poga īpašības', value : 'Vērtība', selected : 'Iezīmēts' }, // Form Dialog. form : { title : 'Formas īpašības', menu : 'Formas īpašības', action : 'Darbība', method : 'Metode', encoding : 'Encoding' // MISSING }, // Select Field Dialog. select : { title : 'Iezīmēšanas lauka īpašības', selectInfo : 'Informācija', opAvail : 'Pieejamās iespējas', value : 'Vērtība', size : 'Izmērs', lines : 'rindas', chkMulti : 'Atļaut vairākus iezīmējumus', opText : 'Teksts', opValue : 'Vērtība', btnAdd : 'Pievienot', btnModify : 'Veikt izmaiņas', btnUp : 'Augšup', btnDown : 'Lejup', btnSetValue : 'Noteikt kā iezīmēto vērtību', btnDelete : 'Dzēst' }, // Textarea Dialog. textarea : { title : 'Teksta laukuma īpašības', cols : 'Kolonnas', rows : 'Rindas' }, // Text Field Dialog. textfield : { title : 'Teksta rindas īpašības', name : 'Nosaukums', value : 'Vērtība', charWidth : 'Simbolu platums', maxChars : 'Simbolu maksimālais daudzums', type : 'Tips', typeText : 'Teksts', typePass : 'Parole' }, // Hidden Field Dialog. hidden : { title : 'Paslēptās teksta rindas īpašības', name : 'Nosaukums', value : 'Vērtība' }, // Image Dialog. image : { title : 'Attēla īpašības', titleButton : 'Attēlpogas īpašības', menu : 'Attēla īpašības', infoTab : 'Informācija par attēlu', btnUpload : 'Nosūtīt serverim', upload : 'Augšupielādēt', alt : 'Alternatīvais teksts', lockRatio : 'Nemainīga Augstuma/Platuma attiecība', resetSize : 'Atjaunot sākotnējo izmēru', border : 'Rāmis', hSpace : 'Horizontālā telpa', vSpace : 'Vertikālā telpa', alertUrl : 'Lūdzu norādīt attēla hipersaiti', linkTab : 'Hipersaite', button2Img : 'Do you want to transform the selected image button on a simple image?', // MISSING img2Button : 'Do you want to transform the selected image on a image button?', // MISSING urlMissing : 'Image source URL is missing.', // MISSING validateBorder : 'Border must be a whole number.', // MISSING validateHSpace : 'HSpace must be a whole number.', // MISSING validateVSpace : 'VSpace must be a whole number.' // MISSING }, // Flash Dialog flash : { properties : 'Flash īpašības', propertiesTab : 'Properties', // MISSING title : 'Flash īpašības', chkPlay : 'Automātiska atskaņošana', chkLoop : 'Nepārtraukti', chkMenu : 'Atļaut Flash izvēlni', chkFull : 'Allow Fullscreen', // MISSING scale : 'Mainīt izmēru', scaleAll : 'Rādīt visu', scaleNoBorder : 'Bez rāmja', scaleFit : 'Precīzs izmērs', access : 'Script Access', // MISSING accessAlways : 'Always', // MISSING accessSameDomain: 'Same domain', // MISSING accessNever : 'Never', // MISSING alignAbsBottom : 'Absolūti apakšā', alignAbsMiddle : 'Absolūti vertikāli centrēts', alignBaseline : 'Pamatrindā', alignTextTop : 'Teksta augšā', quality : 'Quality', // MISSING qualityBest : 'Best', // MISSING qualityHigh : 'High', // MISSING qualityAutoHigh : 'Auto High', // MISSING qualityMedium : 'Medium', // MISSING qualityAutoLow : 'Auto Low', // MISSING qualityLow : 'Low', // MISSING windowModeWindow: 'Window', // MISSING windowModeOpaque: 'Opaque', // MISSING windowModeTransparent : 'Transparent', // MISSING windowMode : 'Window mode', // MISSING flashvars : 'Variables for Flash', // MISSING bgcolor : 'Fona krāsa', hSpace : 'Horizontālā telpa', vSpace : 'Vertikālā telpa', validateSrc : 'Lūdzu norādi hipersaiti', validateHSpace : 'HSpace must be a number.', // MISSING validateVSpace : 'VSpace must be a number.' // MISSING }, // Speller Pages Dialog spellCheck : { toolbar : 'Pareizrakstības pārbaude', title : 'Spell Check', // MISSING notAvailable : 'Sorry, but service is unavailable now.', // MISSING errorLoading : 'Error loading application service host: %s.', // MISSING notInDic : 'Netika atrasts vārdnīcā', changeTo : 'Nomainīt uz', btnIgnore : 'Ignorēt', btnIgnoreAll : 'Ignorēt visu', btnReplace : 'Aizvietot', btnReplaceAll : 'Aizvietot visu', btnUndo : 'Atcelt', noSuggestions : '- Nav ieteikumu -', progress : 'Notiek pareizrakstības pārbaude...', noMispell : 'Pareizrakstības pārbaude pabeigta: kļūdas netika atrastas', noChanges : 'Pareizrakstības pārbaude pabeigta: nekas netika labots', oneChange : 'Pareizrakstības pārbaude pabeigta: 1 vārds izmainīts', manyChanges : 'Pareizrakstības pārbaude pabeigta: %1 vārdi tika mainīti', ieSpellDownload : 'Pareizrakstības pārbaudītājs nav pievienots. Vai vēlaties to lejupielādēt tagad?' }, smiley : { toolbar : 'Smaidiņi', title : 'Ievietot smaidiņu', options : 'Smiley Options' // MISSING }, elementsPath : { eleLabel : 'Elements path', // MISSING eleTitle : '%1 element' // MISSING }, numberedlist : 'Numurēts saraksts', bulletedlist : 'Izcelts saraksts', indent : 'Palielināt atkāpi', outdent : 'Samazināt atkāpi', justify : { left : 'Izlīdzināt pa kreisi', center : 'Izlīdzināt pret centru', right : 'Izlīdzināt pa labi', block : 'Izlīdzināt malas' }, blockquote : 'Block Quote', // MISSING clipboard : { title : 'Ievietot', cutError : 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj editoram automātiski veikt izgriešanas darbību. Lūdzu, izmantojiet (Ctrl/Cmd+X, lai veiktu šo darbību.', copyError : 'Jūsu pārlūkprogrammas drošības iestatījumi nepieļauj editoram automātiski veikt kopēšanas darbību. Lūdzu, izmantojiet (Ctrl/Cmd+C), lai veiktu šo darbību.', pasteMsg : 'Lūdzu, ievietojiet tekstu šajā laukumā, izmantojot klaviatūru (<STRONG>Ctrl/Cmd+V</STRONG>) un apstipriniet ar <STRONG>Darīts!</STRONG>.', securityMsg : 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.', // MISSING pasteArea : 'Paste Area' // MISSING }, pastefromword : { confirmCleanup : 'The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?', // MISSING toolbar : 'Ievietot no Worda', title : 'Ievietot no Worda', error : 'It was not possible to clean up the pasted data due to an internal error' // MISSING }, pasteText : { button : 'Ievietot kā vienkāršu tekstu', title : 'Ievietot kā vienkāršu tekstu' }, templates : { button : 'Sagataves', title : 'Satura sagataves', options : 'Template Options', // MISSING insertOption : 'Replace actual contents', // MISSING selectPromptMsg : 'Lūdzu, norādiet sagatavi, ko atvērt editorā<br>(patreizējie dati tiks zaudēti):', emptyListMsg : '(Nav norādītas sagataves)' }, showBlocks : 'Show Blocks', // MISSING stylesCombo : { label : 'Stils', panelTitle : 'Formatting Styles', // MISSING panelTitle1 : 'Block Styles', // MISSING panelTitle2 : 'Inline Styles', // MISSING panelTitle3 : 'Object Styles' // MISSING }, format : { label : 'Formāts', panelTitle : 'Formāts', tag_p : 'Normāls teksts', tag_pre : 'Formatēts teksts', tag_address : 'Adrese', tag_h1 : 'Virsraksts 1', tag_h2 : 'Virsraksts 2', tag_h3 : 'Virsraksts 3', tag_h4 : 'Virsraksts 4', tag_h5 : 'Virsraksts 5', tag_h6 : 'Virsraksts 6', tag_div : 'Rindkopa (DIV)' }, div : { title : 'Create Div Container', // MISSING toolbar : 'Create Div Container', // MISSING cssClassInputLabel : 'Stylesheet Classes', // MISSING styleSelectLabel : 'Style', // MISSING IdInputLabel : 'Id', // MISSING languageCodeInputLabel : ' Language Code', // MISSING inlineStyleInputLabel : 'Inline Style', // MISSING advisoryTitleInputLabel : 'Advisory Title', // MISSING langDirLabel : 'Language Direction', // MISSING langDirLTRLabel : 'Left to Right (LTR)', // MISSING langDirRTLLabel : 'Right to Left (RTL)', // MISSING edit : 'Edit Div', // MISSING remove : 'Remove Div' // MISSING }, iframe : { title : 'IFrame Properties', // MISSING toolbar : 'IFrame', // MISSING noUrl : 'Please type the iframe URL', // MISSING scrolling : 'Enable scrollbars', // MISSING border : 'Show frame border' // MISSING }, font : { label : 'Šrifts', voiceLabel : 'Font', // MISSING panelTitle : 'Šrifts' }, fontSize : { label : 'Izmērs', voiceLabel : 'Font Size', // MISSING panelTitle : 'Izmērs' }, colorButton : { textColorTitle : 'Teksta krāsa', bgColorTitle : 'Fona krāsa', panelTitle : 'Colors', // MISSING auto : 'Automātiska', more : 'Plašāka palete...' }, colors : { '000' : 'Black', // MISSING '800000' : 'Maroon', // MISSING '8B4513' : 'Saddle Brown', // MISSING '2F4F4F' : 'Dark Slate Gray', // MISSING '008080' : 'Teal', // MISSING '000080' : 'Navy', // MISSING '4B0082' : 'Indigo', // MISSING '696969' : 'Dark Gray', // MISSING 'B22222' : 'Fire Brick', // MISSING 'A52A2A' : 'Brown', // MISSING 'DAA520' : 'Golden Rod', // MISSING '006400' : 'Dark Green', // MISSING '40E0D0' : 'Turquoise', // MISSING '0000CD' : 'Medium Blue', // MISSING '800080' : 'Purple', // MISSING '808080' : 'Gray', // MISSING 'F00' : 'Red', // MISSING 'FF8C00' : 'Dark Orange', // MISSING 'FFD700' : 'Gold', // MISSING '008000' : 'Green', // MISSING '0FF' : 'Cyan', // MISSING '00F' : 'Blue', // MISSING 'EE82EE' : 'Violet', // MISSING 'A9A9A9' : 'Dim Gray', // MISSING 'FFA07A' : 'Light Salmon', // MISSING 'FFA500' : 'Orange', // MISSING 'FFFF00' : 'Yellow', // MISSING '00FF00' : 'Lime', // MISSING 'AFEEEE' : 'Pale Turquoise', // MISSING 'ADD8E6' : 'Light Blue', // MISSING 'DDA0DD' : 'Plum', // MISSING 'D3D3D3' : 'Light Grey', // MISSING 'FFF0F5' : 'Lavender Blush', // MISSING 'FAEBD7' : 'Antique White', // MISSING 'FFFFE0' : 'Light Yellow', // MISSING 'F0FFF0' : 'Honeydew', // MISSING 'F0FFFF' : 'Azure', // MISSING 'F0F8FF' : 'Alice Blue', // MISSING 'E6E6FA' : 'Lavender', // MISSING 'FFF' : 'White' // MISSING }, scayt : { title : 'Spell Check As You Type', // MISSING opera_title : 'Not supported by Opera', // MISSING enable : 'Enable SCAYT', // MISSING disable : 'Disable SCAYT', // MISSING about : 'About SCAYT', // MISSING toggle : 'Toggle SCAYT', // MISSING options : 'Options', // MISSING langs : 'Languages', // MISSING moreSuggestions : 'More suggestions', // MISSING ignore : 'Ignore', // MISSING ignoreAll : 'Ignore All', // MISSING addWord : 'Add Word', // MISSING emptyDic : 'Dictionary name should not be empty.', // MISSING optionsTab : 'Options', // MISSING allCaps : 'Ignore All-Caps Words', // MISSING ignoreDomainNames : 'Ignore Domain Names', // MISSING mixedCase : 'Ignore Words with Mixed Case', // MISSING mixedWithDigits : 'Ignore Words with Numbers', // MISSING languagesTab : 'Languages', // MISSING dictionariesTab : 'Dictionaries', // MISSING dic_field_name : 'Dictionary name', // MISSING dic_create : 'Create', // MISSING dic_restore : 'Restore', // MISSING dic_delete : 'Delete', // MISSING dic_rename : 'Rename', // MISSING dic_info : 'Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.', // MISSING aboutTab : 'About' // MISSING }, about : { title : 'About CKEditor', // MISSING dlgTitle : 'About CKEditor', // MISSING help : 'Check $1 for help.', // MISSING userGuide : 'CKEditor User\'s Guide', // MISSING moreInfo : 'For licensing information please visit our web site:', // MISSING copy : 'Copyright &copy; $1. All rights reserved.' // MISSING }, maximize : 'Maximize', // MISSING minimize : 'Minimize', // MISSING fakeobjects : { anchor : 'Anchor', // MISSING flash : 'Flash Animation', // MISSING iframe : 'IFrame', // MISSING hiddenfield : 'Hidden Field', // MISSING unknown : 'Unknown Object' // MISSING }, resize : 'Drag to resize', // MISSING colordialog : { title : 'Select color', // MISSING options : 'Color Options', // MISSING highlight : 'Highlight', // MISSING selected : 'Selected Color', // MISSING clear : 'Clear' // MISSING }, toolbarCollapse : 'Collapse Toolbar', // MISSING toolbarExpand : 'Expand Toolbar', // MISSING toolbarGroups : { document : 'Document', // MISSING clipboard : 'Clipboard/Undo', // MISSING editing : 'Editing', // MISSING forms : 'Forms', // MISSING basicstyles : 'Basic Styles', // MISSING paragraph : 'Paragraph', // MISSING links : 'Links', // MISSING insert : 'Insert', // MISSING styles : 'Styles', // MISSING colors : 'Colors', // MISSING tools : 'Tools' // MISSING }, bidi : { ltr : 'Text direction from left to right', // MISSING rtl : 'Text direction from right to left' // MISSING }, docprops : { label : 'Dokumenta īpašības', title : 'Dokumenta īpašības', design : 'Design', // MISSING meta : 'META dati', chooseColor : 'Choose', // MISSING other : '<cits>', docTitle : 'Dokumenta virsraksts <Title>', charset : 'Simbolu kodējums', charsetOther : 'Cits simbolu kodējums', charsetASCII : 'ASCII', // MISSING charsetCE : 'Central European', // MISSING charsetCT : 'Chinese Traditional (Big5)', // MISSING charsetCR : 'Cyrillic', // MISSING charsetGR : 'Greek', // MISSING charsetJP : 'Japanese', // MISSING charsetKR : 'Korean', // MISSING charsetTR : 'Turkish', // MISSING charsetUN : 'Unicode (UTF-8)', // MISSING charsetWE : 'Western European', // MISSING docType : 'Dokumenta tips', docTypeOther : 'Cits dokumenta tips', xhtmlDec : 'Ietvert XHTML deklarācijas', bgColor : 'Fona krāsa', bgImage : 'Fona attēla hipersaite', bgFixed : 'Fona attēls ir fiksēts', txtColor : 'Teksta krāsa', margin : 'Lapas robežas', marginTop : 'Augšā', marginLeft : 'Pa kreisi', marginRight : 'Pa labi', marginBottom : 'Apakšā', metaKeywords : 'Dokumentu aprakstoši atslēgvārdi (atdalīti ar komatu)', metaDescription : 'Dokumenta apraksts', metaAuthor : 'Autors', metaCopyright : 'Autortiesības', previewHtml : '<p>This is some <strong>sample text</strong>. You are using <a href="javascript:void(0)">CKEditor</a>.</p>' // MISSING } };
/* Copyright (c) 2016, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * 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. */ #ifndef _IPA_UC_OFFLOAD_I_H_ #define _IPA_UC_OFFLOAD_I_H_ #include <linux/ipa.h> #include "ipa_i.h" /* * Neutrino protocol related data structures */ #define IPA_UC_MAX_NTN_TX_CHANNELS 1 #define IPA_UC_MAX_NTN_RX_CHANNELS 1 #define IPA_NTN_TX_DIR 1 #define IPA_NTN_RX_DIR 2 /** * @brief Enum value determined based on the feature it * corresponds to * +----------------+----------------+ * | 3 bits | 5 bits | * +----------------+----------------+ * | HW_FEATURE | OPCODE | * +----------------+----------------+ * */ #define FEATURE_ENUM_VAL(feature, opcode) ((feature << 5) | opcode) #define EXTRACT_UC_FEATURE(value) (value >> 5) #define IPA_HW_NUM_FEATURES 0x8 /** * enum ipa_hw_features - Values that represent the features supported in IPA HW * @IPA_HW_FEATURE_COMMON : Feature related to common operation of IPA HW * @IPA_HW_FEATURE_MHI : Feature related to MHI operation in IPA HW * @IPA_HW_FEATURE_WDI : Feature related to WDI operation in IPA HW * @IPA_HW_FEATURE_NTN : Feature related to NTN operation in IPA HW * @IPA_HW_FEATURE_OFFLOAD : Feature related to NTN operation in IPA HW */ enum ipa_hw_features { IPA_HW_FEATURE_COMMON = 0x0, IPA_HW_FEATURE_MHI = 0x1, IPA_HW_FEATURE_WDI = 0x3, IPA_HW_FEATURE_NTN = 0x4, IPA_HW_FEATURE_OFFLOAD = 0x5, IPA_HW_FEATURE_MAX = IPA_HW_NUM_FEATURES }; /** * struct IpaHwSharedMemCommonMapping_t - Structure referring to the common * section in 128B shared memory located in offset zero of SW Partition in IPA * SRAM. * @cmdOp : CPU->HW command opcode. See IPA_CPU_2_HW_COMMANDS * @cmdParams : CPU->HW command parameter. The parameter filed can hold 32 bits * of parameters (immediate parameters) and point on structure in system memory * (in such case the address must be accessible for HW) * @responseOp : HW->CPU response opcode. See IPA_HW_2_CPU_RESPONSES * @responseParams : HW->CPU response parameter. The parameter filed can hold 32 * bits of parameters (immediate parameters) and point on structure in system * memory * @eventOp : HW->CPU event opcode. See IPA_HW_2_CPU_EVENTS * @eventParams : HW->CPU event parameter. The parameter filed can hold 32 bits of * parameters (immediate parameters) and point on structure in system memory * @firstErrorAddress : Contains the address of first error-source on SNOC * @hwState : State of HW. The state carries information regarding the error type. * @warningCounter : The warnings counter. The counter carries information regarding * non fatal errors in HW * @interfaceVersionCommon : The Common interface version as reported by HW * * The shared memory is used for communication between IPA HW and CPU. */ struct IpaHwSharedMemCommonMapping_t { u8 cmdOp; u8 reserved_01; u16 reserved_03_02; u32 cmdParams; u8 responseOp; u8 reserved_09; u16 reserved_0B_0A; u32 responseParams; u8 eventOp; u8 reserved_11; u16 reserved_13_12; u32 eventParams; u32 reserved_1B_18; u32 firstErrorAddress; u8 hwState; u8 warningCounter; u16 reserved_23_22; u16 interfaceVersionCommon; u16 reserved_27_26; } __packed; /** * union IpaHwFeatureInfoData_t - parameters for stats/config blob * * @offset : Location of a feature within the EventInfoData * @size : Size of the feature */ union IpaHwFeatureInfoData_t { struct IpaHwFeatureInfoParams_t { u32 offset:16; u32 size:16; } __packed params; u32 raw32b; } __packed; /** * struct IpaHwEventInfoData_t - Structure holding the parameters for * statistics and config info * * @baseAddrOffset : Base Address Offset of the statistics or config * structure from IPA_WRAPPER_BASE * @IpaHwFeatureInfoData_t : Location and size of each feature within * the statistics or config structure * * @note Information about each feature in the featureInfo[] * array is populated at predefined indices per the IPA_HW_FEATURES * enum definition */ struct IpaHwEventInfoData_t { u32 baseAddrOffset; union IpaHwFeatureInfoData_t featureInfo[IPA_HW_NUM_FEATURES]; } __packed; /** * struct IpaHwEventLogInfoData_t - Structure holding the parameters for * IPA_HW_2_CPU_EVENT_LOG_INFO Event * * @featureMask : Mask indicating the features enabled in HW. * Refer IPA_HW_FEATURE_MASK * @circBuffBaseAddrOffset : Base Address Offset of the Circular Event * Log Buffer structure * @statsInfo : Statistics related information * @configInfo : Configuration related information * * @note The offset location of this structure from IPA_WRAPPER_BASE * will be provided as Event Params for the IPA_HW_2_CPU_EVENT_LOG_INFO * Event */ struct IpaHwEventLogInfoData_t { u32 featureMask; u32 circBuffBaseAddrOffset; struct IpaHwEventInfoData_t statsInfo; struct IpaHwEventInfoData_t configInfo; } __packed; /** * struct ipa_uc_ntn_ctx * @ntn_uc_stats_ofst: Neutrino stats offset * @ntn_uc_stats_mmio: Neutrino stats * @priv: private data of client * @uc_ready_cb: uc Ready cb */ struct ipa_uc_ntn_ctx { u32 ntn_uc_stats_ofst; struct IpaHwStatsNTNInfoData_t *ntn_uc_stats_mmio; void *priv; ipa_uc_ready_cb uc_ready_cb; }; /** * enum ipa_hw_2_cpu_ntn_events - Values that represent HW event * to be sent to CPU * @IPA_HW_2_CPU_EVENT_NTN_ERROR : Event to specify that HW * detected an error in NTN * */ enum ipa_hw_2_cpu_ntn_events { IPA_HW_2_CPU_EVENT_NTN_ERROR = FEATURE_ENUM_VAL(IPA_HW_FEATURE_NTN, 0), }; /** * enum ipa_hw_ntn_errors - NTN specific error types. * @IPA_HW_NTN_ERROR_NONE : No error persists * @IPA_HW_NTN_CHANNEL_ERROR : Error is specific to channel */ enum ipa_hw_ntn_errors { IPA_HW_NTN_ERROR_NONE = 0, IPA_HW_NTN_CHANNEL_ERROR = 1 }; /** * enum ipa_hw_ntn_channel_states - Values that represent NTN * channel state machine. * @IPA_HW_NTN_CHANNEL_STATE_INITED_DISABLED : Channel is * initialized but disabled * @IPA_HW_NTN_CHANNEL_STATE_RUNNING : Channel is running. * Entered after SET_UP_COMMAND is processed successfully * @IPA_HW_NTN_CHANNEL_STATE_ERROR : Channel is in error state * @IPA_HW_NTN_CHANNEL_STATE_INVALID : Invalid state. Shall not * be in use in operational scenario * * These states apply to both Tx and Rx paths. These do not reflect the * sub-state the state machine may be in. */ enum ipa_hw_ntn_channel_states { IPA_HW_NTN_CHANNEL_STATE_INITED_DISABLED = 1, IPA_HW_NTN_CHANNEL_STATE_RUNNING = 2, IPA_HW_NTN_CHANNEL_STATE_ERROR = 3, IPA_HW_NTN_CHANNEL_STATE_INVALID = 0xFF }; /** * enum ipa_hw_ntn_channel_errors - List of NTN Channel error * types. This is present in the event param * @IPA_HW_NTN_CH_ERR_NONE: No error persists * @IPA_HW_NTN_TX_FSM_ERROR: Error in the state machine * transition * @IPA_HW_NTN_TX_COMP_RE_FETCH_FAIL: Error while calculating * num RE to bring * @IPA_HW_NTN_RX_RING_WP_UPDATE_FAIL: Write pointer update * failed in Rx ring * @IPA_HW_NTN_RX_FSM_ERROR: Error in the state machine * transition * @IPA_HW_NTN_RX_CACHE_NON_EMPTY: * @IPA_HW_NTN_CH_ERR_RESERVED: * * These states apply to both Tx and Rx paths. These do not * reflect the sub-state the state machine may be in. */ enum ipa_hw_ntn_channel_errors { IPA_HW_NTN_CH_ERR_NONE = 0, IPA_HW_NTN_TX_RING_WP_UPDATE_FAIL = 1, IPA_HW_NTN_TX_FSM_ERROR = 2, IPA_HW_NTN_TX_COMP_RE_FETCH_FAIL = 3, IPA_HW_NTN_RX_RING_WP_UPDATE_FAIL = 4, IPA_HW_NTN_RX_FSM_ERROR = 5, IPA_HW_NTN_RX_CACHE_NON_EMPTY = 6, IPA_HW_NTN_CH_ERR_RESERVED = 0xFF }; /** * struct IpaHwNtnSetUpCmdData_t - Ntn setup command data * @ring_base_pa: physical address of the base of the Tx/Rx NTN * ring * @buff_pool_base_pa: physical address of the base of the Tx/Rx * buffer pool * @ntn_ring_size: size of the Tx/Rx NTN ring * @num_buffers: Rx/tx buffer pool size * @ntn_reg_base_ptr_pa: physical address of the Tx/Rx NTN * Ring's tail pointer * @ipa_pipe_number: IPA pipe number that has to be used for the * Tx/Rx path * @dir: Tx/Rx Direction * @data_buff_size: size of the each data buffer allocated in * DDR */ struct IpaHwNtnSetUpCmdData_t { u32 ring_base_pa; u32 buff_pool_base_pa; u16 ntn_ring_size; u16 num_buffers; u32 ntn_reg_base_ptr_pa; u8 ipa_pipe_number; u8 dir; u16 data_buff_size; } __packed; /** * struct IpaHwNtnCommonChCmdData_t - Structure holding the * parameters for Ntn Tear down command data params * *@ipa_pipe_number: IPA pipe number. This could be Tx or an Rx pipe */ union IpaHwNtnCommonChCmdData_t { struct IpaHwNtnCommonChCmdParams_t { u32 ipa_pipe_number :8; u32 reserved :24; } __packed params; uint32_t raw32b; } __packed; /** * struct IpaHwNTNErrorEventData_t - Structure holding the * IPA_HW_2_CPU_EVENT_NTN_ERROR event. The parameters are passed * as immediate params in the shared memory * *@ntn_error_type: type of NTN error (IPA_HW_NTN_ERRORS) *@ipa_pipe_number: IPA pipe number on which error has happened * Applicable only if error type indicates channel error *@ntn_ch_err_type: Information about the channel error (if * available) */ union IpaHwNTNErrorEventData_t { struct IpaHwNTNErrorEventParams_t { u32 ntn_error_type :8; u32 reserved :8; u32 ipa_pipe_number :8; u32 ntn_ch_err_type :8; } __packed params; uint32_t raw32b; } __packed; /** * struct NTNRxInfoData_t - NTN Structure holding the * Rx pipe information * *@max_outstanding_pkts: Number of outstanding packets in Rx * Ring *@num_pkts_processed: Number of packets processed - cumulative *@rx_ring_rp_value: Read pointer last advertized to the WLAN FW * *@ntn_ch_err_type: Information about the channel error (if * available) *@rx_ind_ring_stats: *@bam_stats: *@num_bam_int_handled: Number of Bam Interrupts handled by FW *@num_db: Number of times the doorbell was rung *@num_unexpected_db: Number of unexpected doorbells *@num_pkts_in_dis_uninit_state: *@num_bam_int_handled_while_not_in_bam: Number of Bam * Interrupts handled by FW *@num_bam_int_handled_while_in_bam_state: Number of Bam * Interrupts handled by FW */ struct NTNRxInfoData_t { u32 max_outstanding_pkts; u32 num_pkts_processed; u32 rx_ring_rp_value; struct IpaHwRingStats_t rx_ind_ring_stats; struct IpaHwBamStats_t bam_stats; u32 num_bam_int_handled; u32 num_db; u32 num_unexpected_db; u32 num_pkts_in_dis_uninit_state; u32 num_bam_int_handled_while_not_in_bam; u32 num_bam_int_handled_while_in_bam_state; } __packed; /** * struct NTNTxInfoData_t - Structure holding the NTN Tx channel * Ensure that this is always word aligned * *@num_pkts_processed: Number of packets processed - cumulative *@tail_ptr_val: Latest value of doorbell written to copy engine *@num_db_fired: Number of DB from uC FW to Copy engine * *@tx_comp_ring_stats: *@bam_stats: *@num_db: Number of times the doorbell was rung *@num_unexpected_db: Number of unexpected doorbells *@num_bam_int_handled: Number of Bam Interrupts handled by FW *@num_bam_int_in_non_running_state: Number of Bam interrupts * while not in Running state *@num_qmb_int_handled: Number of QMB interrupts handled *@num_bam_int_handled_while_wait_for_bam: Number of times the * Imm Cmd is injected due to fw_desc change */ struct NTNTxInfoData_t { u32 num_pkts_processed; u32 tail_ptr_val; u32 num_db_fired; struct IpaHwRingStats_t tx_comp_ring_stats; struct IpaHwBamStats_t bam_stats; u32 num_db; u32 num_unexpected_db; u32 num_bam_int_handled; u32 num_bam_int_in_non_running_state; u32 num_qmb_int_handled; u32 num_bam_int_handled_while_wait_for_bam; u32 num_bam_int_handled_while_not_in_bam; } __packed; /** * struct IpaHwStatsNTNInfoData_t - Structure holding the NTN Tx * channel Ensure that this is always word aligned * */ struct IpaHwStatsNTNInfoData_t { struct NTNRxInfoData_t rx_ch_stats[IPA_UC_MAX_NTN_RX_CHANNELS]; struct NTNTxInfoData_t tx_ch_stats[IPA_UC_MAX_NTN_TX_CHANNELS]; } __packed; /* * uC offload related data structures */ #define IPA_UC_OFFLOAD_CONNECTED BIT(0) #define IPA_UC_OFFLOAD_ENABLED BIT(1) #define IPA_UC_OFFLOAD_RESUMED BIT(2) /** * enum ipa_cpu_2_hw_offload_commands - Values that represent * the offload commands from CPU * @IPA_CPU_2_HW_CMD_OFFLOAD_CHANNEL_SET_UP : Command to set up * Offload protocol's Tx/Rx Path * @IPA_CPU_2_HW_CMD_OFFLOAD_RX_SET_UP : Command to tear down * Offload protocol's Tx/ Rx Path */ enum ipa_cpu_2_hw_offload_commands { IPA_CPU_2_HW_CMD_OFFLOAD_CHANNEL_SET_UP = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 1), IPA_CPU_2_HW_CMD_OFFLOAD_TEAR_DOWN, }; /** * enum ipa_hw_offload_channel_states - Values that represent * offload channel state machine. * @IPA_HW_OFFLOAD_CHANNEL_STATE_INITED_DISABLED : Channel is initialized but disabled * @IPA_HW_OFFLOAD_CHANNEL_STATE_RUNNING : Channel is running. Entered after SET_UP_COMMAND is processed successfully * @IPA_HW_OFFLOAD_CHANNEL_STATE_ERROR : Channel is in error state * @IPA_HW_OFFLOAD_CHANNEL_STATE_INVALID : Invalid state. Shall not be in use in operational scenario * * These states apply to both Tx and Rx paths. These do not * reflect the sub-state the state machine may be in */ enum ipa_hw_offload_channel_states { IPA_HW_OFFLOAD_CHANNEL_STATE_INITED_DISABLED = 1, IPA_HW_OFFLOAD_CHANNEL_STATE_RUNNING = 2, IPA_HW_OFFLOAD_CHANNEL_STATE_ERROR = 3, IPA_HW_OFFLOAD_CHANNEL_STATE_INVALID = 0xFF }; /** * enum ipa_hw_2_cpu_cmd_resp_status - Values that represent * offload related command response status to be sent to CPU. */ enum ipa_hw_2_cpu_offload_cmd_resp_status { IPA_HW_2_CPU_OFFLOAD_CMD_STATUS_SUCCESS = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 0), IPA_HW_2_CPU_OFFLOAD_MAX_TX_CHANNELS = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 1), IPA_HW_2_CPU_OFFLOAD_TX_RING_OVERRUN_POSSIBILITY = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 2), IPA_HW_2_CPU_OFFLOAD_TX_RING_SET_UP_FAILURE = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 3), IPA_HW_2_CPU_OFFLOAD_TX_RING_PARAMS_UNALIGNED = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 4), IPA_HW_2_CPU_OFFLOAD_UNKNOWN_TX_CHANNEL = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 5), IPA_HW_2_CPU_OFFLOAD_TX_INVALID_FSM_TRANSITION = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 6), IPA_HW_2_CPU_OFFLOAD_TX_FSM_TRANSITION_ERROR = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 7), IPA_HW_2_CPU_OFFLOAD_MAX_RX_CHANNELS = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 8), IPA_HW_2_CPU_OFFLOAD_RX_RING_PARAMS_UNALIGNED = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 9), IPA_HW_2_CPU_OFFLOAD_RX_RING_SET_UP_FAILURE = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 10), IPA_HW_2_CPU_OFFLOAD_UNKNOWN_RX_CHANNEL = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 11), IPA_HW_2_CPU_OFFLOAD_RX_INVALID_FSM_TRANSITION = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 12), IPA_HW_2_CPU_OFFLOAD_RX_FSM_TRANSITION_ERROR = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 13), IPA_HW_2_CPU_OFFLOAD_RX_RING_OVERRUN_POSSIBILITY = FEATURE_ENUM_VAL(IPA_HW_FEATURE_OFFLOAD, 14), }; /** * struct IpaHwSetUpCmd - * * */ union IpaHwSetUpCmd { struct IpaHwNtnSetUpCmdData_t NtnSetupCh_params; } __packed; /** * struct IpaHwOffloadSetUpCmdData_t - * * */ struct IpaHwOffloadSetUpCmdData_t { u8 protocol; union IpaHwSetUpCmd SetupCh_params; } __packed; /** * struct IpaHwCommonChCmd - Structure holding the parameters * for IPA_CPU_2_HW_CMD_OFFLOAD_TEAR_DOWN * * */ union IpaHwCommonChCmd { union IpaHwNtnCommonChCmdData_t NtnCommonCh_params; } __packed; struct IpaHwOffloadCommonChCmdData_t { u8 protocol; union IpaHwCommonChCmd CommonCh_params; } __packed; #endif /* _IPA_UC_OFFLOAD_I_H_ */
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source 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. * * 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 GOB_SCRIPT_H #define GOB_SCRIPT_H #include "common/str.h" #include "common/stack.h" #include "gob/totfile.h" namespace Gob { class GobEngine; class Expression; class Script { public: Script(GobEngine *vm); ~Script(); /** Read data and move the pointer accordingly. */ uint32 read(byte *data, int32 size); /** Read data (from an optional offset) without moving the pointer. */ uint32 peek(byte *data, int32 size, int32 offset = 0) const; // Stream properties int32 pos() const; int32 getSize() const; // Stream seeking bool seek(int32 offset, int whence = SEEK_SET); bool skip(int32 offset); bool skipBlock(); // Reading data byte readByte (); char readChar (); uint8 readUint8 (); uint16 readUint16(); uint32 readUint32(); int8 readInt8 (); int16 readInt16 (); int32 readInt32 (); char *readString(int32 length = -1); // Peeking data byte peekByte (int32 offset = 0); char peekChar (int32 offset = 0); uint8 peekUint8 (int32 offset = 0); uint16 peekUint16(int32 offset = 0); uint32 peekUint32(int32 offset = 0); int8 peekInt8 (int32 offset = 0); int16 peekInt16 (int32 offset = 0); int32 peekInt32 (int32 offset = 0); char *peekString(int32 offset = 0); // Expression parsing functions int16 readVarIndex(uint16 *size = 0, uint16 *type = 0); int16 readValExpr(byte stopToken = 99); int16 readExpr(byte stopToken, byte *type); void skipExpr(char stopToken); // Higher-level expression parsing functions char evalExpr(int16 *pRes); bool evalBool(); int32 evalInt(); const char *evalString(); // Accessing the result of expressions int32 getResultInt() const; char *getResultStr() const; /** Returns the offset the specified pointer is within the script data. */ int32 getOffset(byte *ptr) const; /** Returns the data pointer to the offset. */ byte *getData(int32 offset) const; /** Returns the raw data pointer. */ byte *getData(); /** Load a script file. */ bool load(const Common::String &fileName); /** Unload the script. */ void unload(); /** Was a script loaded? */ bool isLoaded() const; /** Setting the 'finished' property. */ void setFinished(bool finished); /** Querying the 'finished' property. */ bool isFinished() const; // Call stack operations /** Push the current script position onto the call stack. */ void push(); /** Pop a script position from the call stack (and return there). */ void pop(bool ret = true); /** Push the current script position and branch to the specified offset. */ void call(uint32 offset); // Fixed properties uint8 getVersionMajor () const; uint8 getVersionMinor () const; uint32 getVariablesCount () const; uint32 getTextsOffset () const; uint32 getResourcesOffset() const; uint16 getAnimDataSize () const; uint8 getImFileNumber () const; uint8 getExFileNumber () const; uint8 getCommunHandling () const; uint16 getFunctionOffset (uint8 function) const; static uint32 getVariablesCount(const char *fileName, GobEngine *vm); private: struct CallEntry { byte *totPtr; bool finished; }; GobEngine *_vm; Expression *_expression; bool _finished; Common::String _totFile; byte *_totData; byte *_totPtr; uint32 _totSize; Common::SeekableReadStream *_lom; TOTFile::Properties _totProperties; Common::Stack<CallEntry> _callStack; /** Loading a TOT file. */ bool loadTOT(const Common::String &fileName); /** Loading a LOM file. */ bool loadLOM(const Common::String &fileName); /** Unloading a TOT file. */ void unloadTOT(); }; } // End of namespace Gob #endif // GOB_SCRIPT_H
/* Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","id",{title:"Instruksi Accessibility",contents:"Bantuan. Tekan ESC untuk menutup dialog ini.",legend:[{name:"Umum",items:[{name:"Toolbar Editor",legend:"Tekan ${toolbarFocus} untuk berpindah ke toolbar. Untuk berpindah ke group toolbar selanjutnya dan sebelumnya gunakan TAB dan SHIFT+TAB. Untuk berpindah ke tombol toolbar selanjutnya dan sebelumnya gunakan RIGHT ARROW atau LEFT ARROW. Tekan SPASI atau ENTER untuk mengaktifkan tombol toolbar."},{name:"Dialog Editor", legend:"Pada jendela dialog, tekan TAB untuk berpindah pada elemen dialog selanjutnya, tekan SHIFT+TAB untuk berpindah pada elemen dialog sebelumnya, tekan ENTER untuk submit dialog, tekan ESC untuk membatalkan dialog. Pada dialog dengan multi tab, daftar tab dapat diakses dengan ALT+F10 ataupun dengan tombol TAB sesuai urutan tab pada dialog. Jika daftar tab aktif terpilih, untuk berpindah tab dapat menggunakan RIGHT dan LEFT ARROW."},{name:"Context Menu Editor",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."}, {name:"List Box Editor",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."},{name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]}, {name:"Commands",items:[{name:" Undo command",legend:"Press ${undo}"},{name:" Redo command",legend:"Press ${redo}"},{name:" Bold command",legend:"Press ${bold}"},{name:" Italic command",legend:"Press ${italic}"},{name:" Underline command",legend:"Press ${underline}"},{name:" Link command",legend:"Press ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},{name:" Accessibility Help",legend:"Press ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Down", leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3", f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
<!doctype html> <html ⚡> <head> <meta charset="utf-8"> <title>Released AMP components</title> <link rel="canonical" href="amps.html" > <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <link href='https://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'> <style amp-custom> body { max-width: 527px; font-family: 'Questrial', Arial; } .box1 { border: 1px solid black; margin: 8px 0; } </style> <script async custom-element="amp-ad" src="https://cdn.ampproject.org/v0/amp-ad-0.1.js"></script> <script async custom-element="amp-audio" src="https://cdn.ampproject.org/v0/amp-audio-0.1.js"></script> <script async custom-element="amp-anim" src="https://cdn.ampproject.org/v0/amp-anim-0.1.js"></script> <script async custom-element="amp-carousel" src="https://cdn.ampproject.org/v0/amp-carousel-0.1.js"></script> <script async custom-element="amp-iframe" src="https://cdn.ampproject.org/v0/amp-iframe-0.1.js"></script> <script async custom-element="amp-image-lightbox" src="https://cdn.ampproject.org/v0/amp-image-lightbox-0.1.js"></script> <script async custom-element="amp-instagram" src="https://cdn.ampproject.org/v0/amp-instagram-0.1.js"></script> <script async custom-element="amp-fit-text" src="https://cdn.ampproject.org/v0/amp-fit-text-0.1.js"></script> <script async custom-element="amp-twitter" src="https://cdn.ampproject.org/v0/amp-twitter-0.1.js"></script> <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> <script async src="https://cdn.ampproject.org/v0.js"></script> </head> <body> <h1>Released AMP components</h1> <h2>Responsive image (with lightbox)</h2> <p> <amp-img on="tap:lightbox1" role="button" tabindex="0" src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w2004-h734-no/PANO_20150726_171347%257E2.jpg" width=527 height=193 layout="responsive" ></amp-img> </p> <h2>Fixed size image</h2> <p> <amp-img id="img1" src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w2004-h734-no/PANO_20150726_171347%257E2.jpg" width=264 height=96></amp-img> </p> <h2>Hidden image</h2> <p> <amp-img id="img2" src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w2004-h734-no/PANO_20150726_171347%257E2.jpg" width=527 height=193 layout="nodisplay"></amp-img> </p> <section> <h2>Media query selection<h2> <amp-img media="(min-width: 650px)" id="img6" src="https://lh5.googleusercontent.com/-vmSp-YN10lA/VcH6S35gAWI/AAAAAAABYqk/6wuA5T3ApSk/w1832-h1376-no/IMG_20150805_131745-ANIMATION.gif" width=466 height=355 layout="responsive" ></amp-img> <amp-img media="(max-width: 649px)" id="img7" src="https://lh4.googleusercontent.com/-okOlNNHeoOc/VbYyrlFYFII/AAAAAAABYdA/La-3j3c-QQI/w2004-h734-no/PANO_20150726_171347%257E2.jpg" width=527 height=193 layout="responsive" ></amp-img> </section> <p> <amp-anim src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h225-no" width="400" height="225" layout="responsive"> <amp-img placeholder src="https://lh3.googleusercontent.com/qNn8GDz8Jfd-s9lt3Nc4lJeLjVyEaqGJTk1vuCUWazCmAeOBVjSWDD0SMTU7x0zhVe5UzOTKR0n-kN4SXx7yElvpKYvCMaRyS_g-jydhJ_cEVYmYPiZ_j1Y9de43mlKxU6s06uK1NAlpbSkL_046amEKOdgIACICkuWfOBwlw2hUDfjPOWskeyMrcTu8XOEerCLuVqXugG31QC345hz3lUyOlkdT9fMYVUynSERGNzHba7bXMOxKRe3izS5DIWUgJs3oeKYqA-V8iqgCvneD1jj0Ff68V_ajm4BDchQubBJU0ytXVkoWh27ngeEHubpnApOS6fcGsjPxeuMjnzAUtoTsiXz2FZi1mMrxrblJ-kZoAq1DJ95cnoqoa2CYq3BTgq2E8BRe2paNxLJ5GXBCTpNdXMpVJc6eD7ceijQyn-2qanilX-iK3ChbOq0uBHMvsdoC_LsFOu5KzbbNH71vM3DPkvDGmHJmF67Vj8sQ6uBrLnzpYlCyN4-Y9frR8zugDcqX5Q=w400-h225-no-k" width="400" height="225" layout="responsive"></amp-img> </amp-anim> </p> <h2>Audio</h2> <amp-audio src="/examples/av/audio.mp3"></amp-audio> <h2>Video</h2> <amp-video src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4" width="358" height="204" layout="responsive" controls></amp-video> <h2>Youtube</h2> <amp-youtube data-videoid="mGENRKrdoGY" layout="responsive" width="480" height="270"></amp-youtube> <h2>Ad A9</h2> <amp-ad width=300 height=250 type="a9" data-aax_size="300x250" data-aax_pubname="abc123" data-aax_src="302"> </amp-ad> <h2>Iframe</h2> <amp-iframe width=300 height=300 sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox" layout="responsive" frameborder="0" src="https://www.google.com/maps/embed/v1/place?key=AIzaSyDG9YXIhKBhqclZizcSzJ0ROiE0qgVfwzI&q=Alameda,%20CA"> </amp-iframe> <h2>Instagram</h2> <amp-instagram data-shortcode="fBwFP" width="320" height="392" layout="responsive"> </amp-instagram> <h2>Ad AdSense</h2> <amp-ad width=300 height=200 type="adsense" data-ad-client="ca-pub-9350112648257122"> </amp-ad> <h2>Twitter</h2> <amp-twitter width=486 height=256 layout="responsive" data-tweetID="585110598171631616" data-cards="hidden"> </amp-twitter> <h2>Fit-text</h2> <amp-fit-text width="300" height="200" layout="responsive" class="box1"> Lorem ipsum dolor sit amet, has nisl nihil convenire et, vim at aeque inermis reprehendunt. </amp-fit-text> <amp-image-lightbox id="lightbox1" layout="nodisplay"></amp-image-lightbox> <amp-pixel width=1 height=1 src="https://pubads.g.doubleclick.net/activity;dc_iu=/12344/pixel;ord=$RANDOM?"></amp-pixel> </body> </html>
<!doctype html> <html> <head> <script src="../../../resources/js-test.js"></script> </head> <body> <script> [ "adoptNode()", "createAttribute()", "createAttributeNS('http://www.w3.org/2000/svg')", "createAttributeNS()", "createCDATASection()", "createComment()", "createElement()", "createElementNS('http://www.w3.org/2000/svg')", "createElementNS()", "createEvent()", "createProcessingInstruction('xml')", "createProcessingInstruction()", "createTextNode()", "elementFromPoint()", "elementFromPoint(0)", "execCommand()", "getElementById()", "getElementsByClassName()", "getElementsByName()", "getElementsByTagName()", "getElementsByTagNameNS('http://www.w3.org/2000/svg')", "getElementsByTagNameNS()", "importNode()", "queryCommandEnabled()", "queryCommandIndeterm()", "queryCommandState()", "queryCommandSupported()", "queryCommandValue()", ].forEach(function(expr) { shouldThrow("document." + expr); }); </script> </body> </html>
<?php namespace Drupal\Core\Template; use Drupal\Component\Utility\Html; /** * A class that defines a type of Attribute that can be added to as an array. * * To use with Attribute, the array must be specified. * Correct: * @code * $attributes = new Attribute(); * $attributes['class'] = array(); * $attributes['class'][] = 'cat'; * @endcode * Incorrect: * @code * $attributes = new Attribute(); * $attributes['class'][] = 'cat'; * @endcode * * @see \Drupal\Core\Template\Attribute */ class AttributeArray extends AttributeValueBase implements \ArrayAccess, \IteratorAggregate { /** * Ensures empty array as a result of array_filter will not print '$name=""'. * * @see \Drupal\Core\Template\AttributeArray::__toString() * @see \Drupal\Core\Template\AttributeValueBase::render() */ const RENDER_EMPTY_ATTRIBUTE = FALSE; /** * {@inheritdoc} */ public function offsetGet($offset) { return $this->value[$offset]; } /** * {@inheritdoc} */ public function offsetSet($offset, $value) { if (isset($offset)) { $this->value[$offset] = $value; } else { $this->value[] = $value; } } /** * {@inheritdoc} */ public function offsetUnset($offset) { unset($this->value[$offset]); } /** * {@inheritdoc} */ public function offsetExists($offset) { return isset($this->value[$offset]); } /** * Implements the magic __toString() method. */ public function __toString() { // Filter out any empty values before printing. $this->value = array_unique(array_filter($this->value)); return Html::escape(implode(' ', $this->value)); } /** * {@inheritdoc} */ public function getIterator() { return new \ArrayIterator($this->value); } /** * Exchange the array for another one. * * @see ArrayObject::exchangeArray * * @param array $input * The array input to replace the internal value. * * @return array * The old array value. */ public function exchangeArray($input) { $old = $this->value; $this->value = $input; return $old; } }
require 'spec_helper' describe RailsAdmin::Config::Fields::Types::Color do it_behaves_like 'a generic field type', :string_field, :color end
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP #include <cstddef> #include <algorithm> #include <map> #include <set> #include <vector> #ifdef BOOST_GEOMETRY_DEBUG_ENRICH # include <iostream> # include <boost/geometry/algorithms/detail/overlay/debug_turn_info.hpp> # include <boost/geometry/io/wkt/wkt.hpp> # define BOOST_GEOMETRY_DEBUG_IDENTIFIER #endif #include <boost/range.hpp> #include <boost/geometry/iterators/ever_circling_iterator.hpp> #include <boost/geometry/algorithms/detail/ring_identifier.hpp> #include <boost/geometry/algorithms/detail/overlay/copy_segment_point.hpp> #include <boost/geometry/algorithms/detail/overlay/handle_colocations.hpp> #include <boost/geometry/algorithms/detail/overlay/less_by_segment_ratio.hpp> #include <boost/geometry/algorithms/detail/overlay/overlay_type.hpp> #include <boost/geometry/algorithms/detail/overlay/sort_by_side.hpp> #include <boost/geometry/policies/robustness/robust_type.hpp> #include <boost/geometry/strategies/side.hpp> #ifdef BOOST_GEOMETRY_DEBUG_ENRICH # include <boost/geometry/algorithms/detail/overlay/check_enrich.hpp> #endif namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace overlay { // Sorts IP-s of this ring on segment-identifier, and if on same segment, // on distance. // Then assigns for each IP which is the next IP on this segment, // plus the vertex-index to travel to, plus the next IP // (might be on another segment) template < bool Reverse1, bool Reverse2, typename Operations, typename Turns, typename Geometry1, typename Geometry2, typename RobustPolicy, typename Strategy > inline void enrich_sort(Operations& operations, Turns const& turns, operation_type for_operation, Geometry1 const& geometry1, Geometry2 const& geometry2, RobustPolicy const& robust_policy, Strategy const& /*strategy*/) { std::sort(boost::begin(operations), boost::end(operations), less_by_segment_ratio < Turns, typename boost::range_value<Operations>::type, Geometry1, Geometry2, RobustPolicy, Reverse1, Reverse2 >(turns, for_operation, geometry1, geometry2, robust_policy)); } template <typename Operations, typename Turns> inline void enrich_assign(Operations& operations, Turns& turns) { typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::turn_operation_type op_type; typedef typename boost::range_iterator<Operations>::type iterator_type; if (operations.size() > 0) { // Assign travel-to-vertex/ip index for each turning point. // Iterator "next" is circular geometry::ever_circling_range_iterator<Operations const> next(operations); ++next; for (iterator_type it = boost::begin(operations); it != boost::end(operations); ++it) { turn_type& turn = turns[it->turn_index]; op_type& op = turn.operations[it->operation_index]; // Normal behaviour: next should point at next turn: if (it->turn_index == next->turn_index) { ++next; } // Cluster behaviour: next should point after cluster, unless // their seg_ids are not the same while (turn.cluster_id != -1 && it->turn_index != next->turn_index && turn.cluster_id == turns[next->turn_index].cluster_id && op.seg_id == turns[next->turn_index].operations[next->operation_index].seg_id) { ++next; } turn_type const& next_turn = turns[next->turn_index]; op_type const& next_op = next_turn.operations[next->operation_index]; op.enriched.travels_to_ip_index = static_cast<signed_size_type>(next->turn_index); op.enriched.travels_to_vertex_index = next->subject->seg_id.segment_index; if (op.seg_id.segment_index == next_op.seg_id.segment_index && op.fraction < next_op.fraction) { // Next turn is located further on same segment // assign next_ip_index // (this is one not circular therefore fraction is considered) op.enriched.next_ip_index = static_cast<signed_size_type>(next->turn_index); } } } // DEBUG #ifdef BOOST_GEOMETRY_DEBUG_ENRICH { for (iterator_type it = boost::begin(operations); it != boost::end(operations); ++it) { op_type& op = turns[it->turn_index] .operations[it->operation_index]; std::cout << it->turn_index << " cl=" << turns[it->turn_index].cluster_id << " meth=" << method_char(turns[it->turn_index].method) << " seg=" << op.seg_id << " dst=" << op.fraction // needs define << " op=" << operation_char(turns[it->turn_index].operations[0].operation) << operation_char(turns[it->turn_index].operations[1].operation) << " (" << operation_char(op.operation) << ")" << " nxt=" << op.enriched.next_ip_index << " / " << op.enriched.travels_to_ip_index << " [vx " << op.enriched.travels_to_vertex_index << "]" << std::boolalpha << turns[it->turn_index].discarded << std::endl; ; } } #endif // END DEBUG } template <typename Turns, typename MappedVector> inline void create_map(Turns const& turns, detail::overlay::operation_type for_operation, MappedVector& mapped_vector) { typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::container_type container_type; typedef typename MappedVector::mapped_type mapped_type; typedef typename boost::range_value<mapped_type>::type indexed_type; std::size_t index = 0; for (typename boost::range_iterator<Turns const>::type it = boost::begin(turns); it != boost::end(turns); ++it, ++index) { // Add all (non discarded) operations on this ring // Blocked operations or uu on clusters (for intersection) // should be included, to block potential paths in clusters turn_type const& turn = *it; if (turn.discarded) { continue; } if (for_operation == operation_intersection && turn.cluster_id == -1 && turn.both(operation_union)) { // Only include uu turns if part of cluster (to block potential paths), // otherwise they can block possibly viable paths continue; } std::size_t op_index = 0; for (typename boost::range_iterator<container_type const>::type op_it = boost::begin(turn.operations); op_it != boost::end(turn.operations); ++op_it, ++op_index) { ring_identifier const ring_id ( op_it->seg_id.source_index, op_it->seg_id.multi_index, op_it->seg_id.ring_index ); mapped_vector[ring_id].push_back ( indexed_type(index, op_index, *op_it, it->operations[1 - op_index].seg_id) ); } } } }} // namespace detail::overlay #endif //DOXYGEN_NO_DETAIL /*! \brief All intersection points are enriched with successor information \ingroup overlay \tparam Turns type of intersection container (e.g. vector of "intersection/turn point"'s) \tparam Clusters type of cluster container \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \tparam Strategy side strategy type \param turns container containing intersection points \param clusters container containing clusters \param geometry1 \param_geometry \param geometry2 \param_geometry \param robust_policy policy to handle robustness issues \param strategy strategy */ template < bool Reverse1, bool Reverse2, overlay_type OverlayType, typename Turns, typename Clusters, typename Geometry1, typename Geometry2, typename RobustPolicy, typename Strategy > inline void enrich_intersection_points(Turns& turns, Clusters& clusters, Geometry1 const& geometry1, Geometry2 const& geometry2, RobustPolicy const& robust_policy, Strategy const& strategy) { static const detail::overlay::operation_type for_operation = detail::overlay::operation_from_overlay<OverlayType>::value; typedef typename boost::range_value<Turns>::type turn_type; typedef typename turn_type::turn_operation_type op_type; typedef detail::overlay::indexed_turn_operation < op_type > indexed_turn_operation; typedef std::map < ring_identifier, std::vector<indexed_turn_operation> > mapped_vector_type; bool const has_colocations = detail::overlay::handle_colocations<Reverse1, Reverse2>(turns, clusters, geometry1, geometry2); // Discard none turns, if any for (typename boost::range_iterator<Turns>::type it = boost::begin(turns); it != boost::end(turns); ++it) { if (it->both(detail::overlay::operation_none)) { it->discarded = true; } } // Create a map of vectors of indexed operation-types to be able // to sort intersection points PER RING mapped_vector_type mapped_vector; detail::overlay::create_map(turns, for_operation, mapped_vector); // No const-iterator; contents of mapped copy is temporary, // and changed by enrich for (typename mapped_vector_type::iterator mit = mapped_vector.begin(); mit != mapped_vector.end(); ++mit) { #ifdef BOOST_GEOMETRY_DEBUG_ENRICH std::cout << "ENRICH-sort Ring " << mit->first << std::endl; #endif detail::overlay::enrich_sort<Reverse1, Reverse2>( mit->second, turns, for_operation, geometry1, geometry2, robust_policy, strategy); } for (typename mapped_vector_type::iterator mit = mapped_vector.begin(); mit != mapped_vector.end(); ++mit) { #ifdef BOOST_GEOMETRY_DEBUG_ENRICH std::cout << "ENRICH-assign Ring " << mit->first << std::endl; #endif detail::overlay::enrich_assign(mit->second, turns); } if (has_colocations) { detail::overlay::gather_cluster_properties<Reverse1, Reverse2>( clusters, turns, for_operation, geometry1, geometry2); } #ifdef BOOST_GEOMETRY_DEBUG_ENRICH //detail::overlay::check_graph(turns, for_operation); #endif } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_ENRICH_HPP
<?php /** * Smarty Internal Plugin Compile Include * Compiles the {include} tag * * @package Smarty * @subpackage Compiler * @author Uwe Tews */ /** * Smarty Internal Plugin Compile Include Class * * @package Smarty * @subpackage Compiler */ class Smarty_Internal_Compile_Include extends Smarty_Internal_CompileBase { /** * caching mode to create nocache code but no cache file */ const CACHING_NOCACHE_CODE = 9999; /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $required_attributes = array('file'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $shorttag_order = array('file'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $option_flags = array('nocache', 'inline', 'caching'); /** * Attribute definition: Overwrites base class. * * @var array * @see Smarty_Internal_CompileBase */ public $optional_attributes = array('_any'); /** * Valid scope names * * @var array */ public $valid_scopes = array('parent' => Smarty::SCOPE_PARENT, 'root' => Smarty::SCOPE_ROOT, 'global' => Smarty::SCOPE_GLOBAL, 'tpl_root' => Smarty::SCOPE_TPL_ROOT, 'smarty' => Smarty::SCOPE_SMARTY); /** * Compiles code for the {include} tag * * @param array $args array with attributes from parser * @param Smarty_Internal_SmartyTemplateCompiler $compiler compiler object * @param array $parameter array with compilation parameter * * @throws SmartyCompilerException * @return string compiled code */ public function compile($args, Smarty_Internal_SmartyTemplateCompiler $compiler, $parameter) { $uid = $t_hash = null; // check and get attributes $_attr = $this->getAttributes($compiler, $args); $fullResourceName = $source_resource = $_attr[ 'file' ]; $variable_template = false; $cache_tpl = false; // parse resource_name if (preg_match('/^([\'"])(([A-Za-z0-9_\-]{2,})[:])?(([^$()]+)|(.+))\1$/', $source_resource, $match)) { $type = !empty($match[ 3 ]) ? $match[ 3 ] : $compiler->template->smarty->default_resource_type; $name = !empty($match[ 5 ]) ? $match[ 5 ] : $match[ 6 ]; $handler = Smarty_Resource::load($compiler->smarty, $type); if ($handler->recompiled || $handler->uncompiled) { $variable_template = true; } if (!$variable_template) { if ($type != 'string') { $fullResourceName = "{$type}:{$name}"; $compiled = $compiler->parent_compiler->template->compiled; if (isset($compiled->includes[ $fullResourceName ])) { $compiled->includes[ $fullResourceName ] ++; $cache_tpl = true; } else { if ("{$compiler->template->source->type}:{$compiler->template->source->name}" == $fullResourceName ) { // recursive call of current template $compiled->includes[ $fullResourceName ] = 2; $cache_tpl = true; } else { $compiled->includes[ $fullResourceName ] = 1; } } $fullResourceName = '"' . $fullResourceName . '"'; } } if (empty($match[ 5 ])) { $variable_template = true; } } else { $variable_template = true; } // scope setup $_scope = $compiler->convertScope($_attr, $this->valid_scopes); // set flag to cache subtemplate object when called within loop or template name is variable. if ($cache_tpl || $variable_template || $compiler->loopNesting > 0) { $_cache_tpl = 'true'; } else { $_cache_tpl = 'false'; } // assume caching is off $_caching = Smarty::CACHING_OFF; $call_nocache = $compiler->tag_nocache || $compiler->nocache; // caching was on and {include} is not in nocache mode if ($compiler->template->caching && !$compiler->nocache && !$compiler->tag_nocache) { $_caching = self::CACHING_NOCACHE_CODE; } // flag if included template code should be merged into caller $merge_compiled_includes = ($compiler->smarty->merge_compiled_includes || $_attr[ 'inline' ] === true) && !$compiler->template->source->handler->recompiled; if ($merge_compiled_includes) { // variable template name ? if ($variable_template) { $merge_compiled_includes = false; } // variable compile_id? if (isset($_attr[ 'compile_id' ]) && $compiler->isVariable($_attr[ 'compile_id' ])) { $merge_compiled_includes = false; } } /* * if the {include} tag provides individual parameter for caching or compile_id * the subtemplate must not be included into the common cache file and is treated like * a call in nocache mode. * */ if ($_attr[ 'nocache' ] !== true && $_attr[ 'caching' ]) { $_caching = $_new_caching = (int) $_attr[ 'caching' ]; $call_nocache = true; } else { $_new_caching = Smarty::CACHING_LIFETIME_CURRENT; } if (isset($_attr[ 'cache_lifetime' ])) { $_cache_lifetime = $_attr[ 'cache_lifetime' ]; $call_nocache = true; $_caching = $_new_caching; } else { $_cache_lifetime = '$_smarty_tpl->cache_lifetime'; } if (isset($_attr[ 'cache_id' ])) { $_cache_id = $_attr[ 'cache_id' ]; $call_nocache = true; $_caching = $_new_caching; } else { $_cache_id = '$_smarty_tpl->cache_id'; } if (isset($_attr[ 'compile_id' ])) { $_compile_id = $_attr[ 'compile_id' ]; } else { $_compile_id = '$_smarty_tpl->compile_id'; } // if subtemplate will be called in nocache mode do not merge if ($compiler->template->caching && $call_nocache) { $merge_compiled_includes = false; } // assign attribute if (isset($_attr[ 'assign' ])) { // output will be stored in a smarty variable instead of being displayed if ($_assign = $compiler->getId($_attr[ 'assign' ])) { $_assign = "'{$_assign}'"; if ($compiler->tag_nocache || $compiler->nocache || $call_nocache) { // create nocache var to make it know for further compiling $compiler->setNocacheInVariable($_attr[ 'assign' ]); } } else { $_assign = $_attr[ 'assign' ]; } } $has_compiled_template = false; if ($merge_compiled_includes) { $c_id = isset($_attr[ 'compile_id' ]) ? $_attr[ 'compile_id' ] : $compiler->template->compile_id; // we must observe different compile_id and caching $t_hash = sha1($c_id . ($_caching ? '--caching' : '--nocaching')); $compiler->smarty->allow_ambiguous_resources = true; /* @var Smarty_Internal_Template $tpl */ $tpl = new $compiler->smarty->template_class (trim($fullResourceName, '"\''), $compiler->smarty, $compiler->template, $compiler->template->cache_id, $c_id, $_caching); $uid = $tpl->source->type . $tpl->source->uid; if (!isset($compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ])) { $has_compiled_template = $this->compileInlineTemplate($compiler, $tpl, $t_hash); } else { $has_compiled_template = true; } unset($tpl); } // delete {include} standard attributes unset($_attr[ 'file' ], $_attr[ 'assign' ], $_attr[ 'cache_id' ], $_attr[ 'compile_id' ], $_attr[ 'cache_lifetime' ], $_attr[ 'nocache' ], $_attr[ 'caching' ], $_attr[ 'scope' ], $_attr[ 'inline' ]); // remaining attributes must be assigned as smarty variable $_vars = 'array()'; if (!empty($_attr)) { $_pairs = array(); // create variables foreach ($_attr as $key => $value) { $_pairs[] = "'$key'=>$value"; } $_vars = 'array(' . join(',', $_pairs) . ')'; } $update_compile_id = $compiler->template->caching && !$compiler->tag_nocache && !$compiler->nocache && $_compile_id != '$_smarty_tpl->compile_id'; if ($has_compiled_template && !$call_nocache) { $_output = "<?php\n"; if ($update_compile_id) { $_output .= $compiler->makeNocacheCode("\$_compile_id_save[] = \$_smarty_tpl->compile_id;\n\$_smarty_tpl->compile_id = {$_compile_id};\n"); } if (!empty($_attr) && $_caching == 9999 && $compiler->template->caching) { $_vars_nc = "foreach ($_vars as \$ik => \$iv) {\n"; $_vars_nc .= "\$_smarty_tpl->tpl_vars[\$ik] = new Smarty_Variable(\$iv);\n"; $_vars_nc .= "}\n"; $_output .= substr($compiler->processNocacheCode('<?php ' . $_vars_nc . "?>\n", true), 6, - 3); } if (isset($_assign)) { $_output .= "ob_start();\n"; } $_output .= "\$_smarty_tpl->_subTemplateRender({$fullResourceName}, {$_cache_id}, {$_compile_id}, {$_caching}, {$_cache_lifetime}, {$_vars}, {$_scope}, {$_cache_tpl}, '{$compiler->parent_compiler->mergedSubTemplatesData[$uid][$t_hash]['uid']}', '{$compiler->parent_compiler->mergedSubTemplatesData[$uid][$t_hash]['func']}');\n"; if (isset($_assign)) { $_output .= "\$_smarty_tpl->assign({$_assign}, ob_get_clean());\n"; } if ($update_compile_id) { $_output .= $compiler->makeNocacheCode("\$_smarty_tpl->compile_id = array_pop(\$_compile_id_save);\n"); } $_output .= "?>\n"; return $_output; } if ($call_nocache) { $compiler->tag_nocache = true; } $_output = "<?php "; if ($update_compile_id) { $_output .= "\$_compile_id_save[] = \$_smarty_tpl->compile_id;\n\$_smarty_tpl->compile_id = {$_compile_id};\n"; } // was there an assign attribute if (isset($_assign)) { $_output .= "ob_start();\n"; } $_output .= "\$_smarty_tpl->_subTemplateRender({$fullResourceName}, $_cache_id, $_compile_id, $_caching, $_cache_lifetime, $_vars, $_scope, {$_cache_tpl});\n"; if (isset($_assign)) { $_output .= "\$_smarty_tpl->assign({$_assign}, ob_get_clean());\n"; } if ($update_compile_id) { $_output .= "\$_smarty_tpl->compile_id = array_pop(\$_compile_id_save);\n"; } $_output .= "?>\n"; return $_output; } /** * Compile inline sub template * * @param \Smarty_Internal_SmartyTemplateCompiler $compiler * @param \Smarty_Internal_Template $tpl * @param string $t_hash * * @return bool */ public function compileInlineTemplate(Smarty_Internal_SmartyTemplateCompiler $compiler, Smarty_Internal_Template $tpl, $t_hash) { $uid = $tpl->source->type . $tpl->source->uid; if (!($tpl->source->handler->uncompiled) && $tpl->source->exists) { $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'uid' ] = $tpl->source->uid; if (isset($compiler->template->inheritance)) { $tpl->inheritance = clone $compiler->template->inheritance; } $tpl->compiled = new Smarty_Template_Compiled(); $tpl->compiled->nocache_hash = $compiler->parent_compiler->template->compiled->nocache_hash; $tpl->loadCompiler(); // save unique function name $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'func' ] = $tpl->compiled->unifunc = 'content_' . str_replace(array('.', ','), '_', uniqid('', true)); // make sure whole chain gets compiled $tpl->mustCompile = true; $compiler->parent_compiler->mergedSubTemplatesData[ $uid ][ $t_hash ][ 'nocache_hash' ] = $tpl->compiled->nocache_hash; if ($compiler->template->source->type == 'file') { $sourceInfo = $compiler->template->source->filepath; } else { $basename = $compiler->template->source->handler->getBasename($compiler->template->source); $sourceInfo = $compiler->template->source->type . ':' . ($basename ? $basename : $compiler->template->source->name); } // get compiled code $compiled_code = "<?php\n\n"; $compiled_code .= "/* Start inline template \"{$sourceInfo}\" =============================*/\n"; $compiled_code .= "function {$tpl->compiled->unifunc} (\$_smarty_tpl) {\n"; $compiled_code .= "?>\n" . $tpl->compiler->compileTemplateSource($tpl, null, $compiler->parent_compiler); $compiled_code .= "<?php\n"; $compiled_code .= "}\n?>\n"; $compiled_code .= $tpl->compiler->postFilter($tpl->compiler->blockOrFunctionCode); $compiled_code .= "<?php\n\n"; $compiled_code .= "/* End inline template \"{$sourceInfo}\" =============================*/\n"; $compiled_code .= "?>"; unset($tpl->compiler); if ($tpl->compiled->has_nocache_code) { // replace nocache_hash $compiled_code = str_replace("{$tpl->compiled->nocache_hash}", $compiler->template->compiled->nocache_hash, $compiled_code); $compiler->template->compiled->has_nocache_code = true; } $compiler->parent_compiler->mergedSubTemplatesCode[ $tpl->compiled->unifunc ] = $compiled_code; return true; } else { return false; } } }
# API Documentation *Please use only this documented API when working with the parser. Methods not documented here are subject to change at any point.* ## `parser` function This is the module's main entry point. ```js const parser = require('postcss-selector-parser'); ``` ### `parser([transform], [options])` Creates a new `processor` instance ```js const processor = parser(); // or, with optional transform function const transform = selectors => { selectors.walkUniversals(selector => { selector.remove(); }); }; const processor = parser(transform) // Example const result = processor.processSync('*.class'); // => .class ``` [See processor documentation](#processor) Arguments: * `transform (function)`: Provide a function to work with the parsed AST. * `options (object)`: Provide default options for all calls on the returned `Processor`. ### `parser.attribute([props])` Creates a new attribute selector. ```js parser.attribute({attribute: 'href'}); // => [href] ``` Arguments: * `props (object)`: The new node's properties. ### `parser.className([props])` Creates a new class selector. ```js parser.className({value: 'button'}); // => .button ``` Arguments: * `props (object)`: The new node's properties. ### `parser.combinator([props])` Creates a new selector combinator. ```js parser.combinator({value: '+'}); // => + ``` Arguments: * `props (object)`: The new node's properties. ### `parser.comment([props])` Creates a new comment. ```js parser.comment({value: '/* Affirmative, Dave. I read you. */'}); // => /* Affirmative, Dave. I read you. */ ``` Arguments: * `props (object)`: The new node's properties. ### `parser.id([props])` Creates a new id selector. ```js parser.id({value: 'search'}); // => #search ``` Arguments: * `props (object)`: The new node's properties. ### `parser.nesting([props])` Creates a new nesting selector. ```js parser.nesting(); // => & ``` Arguments: * `props (object)`: The new node's properties. ### `parser.pseudo([props])` Creates a new pseudo selector. ```js parser.pseudo({value: '::before'}); // => ::before ``` Arguments: * `props (object)`: The new node's properties. ### `parser.root([props])` Creates a new root node. ```js parser.root(); // => (empty) ``` Arguments: * `props (object)`: The new node's properties. ### `parser.selector([props])` Creates a new selector node. ```js parser.selector(); // => (empty) ``` Arguments: * `props (object)`: The new node's properties. ### `parser.string([props])` Creates a new string node. ```js parser.string(); // => (empty) ``` Arguments: * `props (object)`: The new node's properties. ### `parser.tag([props])` Creates a new tag selector. ```js parser.tag({value: 'button'}); // => button ``` Arguments: * `props (object)`: The new node's properties. ### `parser.universal([props])` Creates a new universal selector. ```js parser.universal(); // => * ``` Arguments: * `props (object)`: The new node's properties. ## Node types ### `node.type` A string representation of the selector type. It can be one of the following; `attribute`, `class`, `combinator`, `comment`, `id`, `nesting`, `pseudo`, `root`, `selector`, `string`, `tag`, or `universal`. Note that for convenience, these constants are exposed on the main `parser` as uppercased keys. So for example you can get `id` by querying `parser.ID`. ```js parser.attribute({attribute: 'href'}).type; // => 'attribute' ``` ### `node.parent` Returns the parent node. ```js root.nodes[0].parent === root; ``` ### `node.toString()`, `String(node)`, or `'' + node` Returns a string representation of the node. ```js const id = parser.id({value: 'search'}); console.log(String(id)); // => #search ``` ### `node.next()` & `node.prev()` Returns the next/previous child of the parent node. ```js const next = id.next(); if (next && next.type !== 'combinator') { throw new Error('Qualified IDs are not allowed!'); } ``` ### `node.replaceWith(node)` Replace a node with another. ```js const attr = selectors.first.first; const className = parser.className({value: 'test'}); attr.replaceWith(className); ``` Arguments: * `node`: The node to substitute the original with. ### `node.remove()` Removes the node from its parent node. ```js if (node.type === 'id') { node.remove(); } ``` ### `node.clone()` Returns a copy of a node, detached from any parent containers that the original might have had. ```js const cloned = parser.id({value: 'search'}); String(cloned); // => #search ``` ### `node.spaces` Extra whitespaces around the node will be moved into `node.spaces.before` and `node.spaces.after`. So for example, these spaces will be moved as they have no semantic meaning: ```css h1 , h2 {} ``` However, *combinating* spaces will form a `combinator` node: ```css h1 h2 {} ``` A `combinator` node may only have the `spaces` property set if the combinator value is a non-whitespace character, such as `+`, `~` or `>`. Otherwise, the combinator value will contain all of the spaces between selectors. ### `node.source` An object describing the node's start/end, line/column source position. Within the following CSS, the `.bar` class node ... ```css .foo, .bar {} ``` ... will contain the following `source` object. ```js source: { start: { line: 2, column: 3 }, end: { line: 2, column: 6 } } ``` ### `node.sourceIndex` The zero-based index of the node within the original source string. Within the following CSS, the `.baz` class node will have a `sourceIndex` of `12`. ```css .foo, .bar, .baz {} ``` ## Container types The `root`, `selector`, and `pseudo` nodes have some helper methods for working with their children. ### `container.nodes` An array of the container's children. ```js // Input: h1 h2 selectors.at(0).nodes.length // => 3 selectors.at(0).nodes[0].value // => 'h1' selectors.at(0).nodes[1].value // => ' ' ``` ### `container.first` & `container.last` The first/last child of the container. ```js selector.first === selector.nodes[0]; selector.last === selector.nodes[selector.nodes.length - 1]; ``` ### `container.at(index)` Returns the node at position `index`. ```js selector.at(0) === selector.first; selector.at(0) === selector.nodes[0]; ``` Arguments: * `index`: The index of the node to return. ### `container.index(node)` Return the index of the node within its container. ```js selector.index(selector.nodes[2]) // => 2 ``` Arguments: * `node`: A node within the current container. ### `container.length` Proxy to the length of the container's nodes. ```js container.length === container.nodes.length ``` ### `container` Array iterators The container class provides proxies to certain Array methods; these are: * `container.map === container.nodes.map` * `container.reduce === container.nodes.reduce` * `container.every === container.nodes.every` * `container.some === container.nodes.some` * `container.filter === container.nodes.filter` * `container.sort === container.nodes.sort` Note that these methods only work on a container's immediate children; recursive iteration is provided by `container.walk`. ### `container.each(callback)` Iterate the container's immediate children, calling `callback` for each child. You may return `false` within the callback to break the iteration. ```js let className; selectors.each((selector, index) => { if (selector.type === 'class') { className = selector.value; return false; } }); ``` Note that unlike `Array#forEach()`, this iterator is safe to use whilst adding or removing nodes from the container. Arguments: * `callback (function)`: A function to call for each node, which receives `node` and `index` arguments. ### `container.walk(callback)` Like `container#each`, but will also iterate child nodes as long as they are `container` types. ```js selectors.walk((selector, index) => { // all nodes }); ``` Arguments: * `callback (function)`: A function to call for each node, which receives `node` and `index` arguments. This iterator is safe to use whilst mutating `container.nodes`, like `container#each`. ### `container.walk` proxies The container class provides proxy methods for iterating over types of nodes, so that it is easier to write modules that target specific selectors. Those methods are: * `container.walkAttributes` * `container.walkClasses` * `container.walkCombinators` * `container.walkComments` * `container.walkIds` * `container.walkNesting` * `container.walkPseudos` * `container.walkTags` * `container.walkUniversals` ### `container.split(callback)` This method allows you to split a group of nodes by returning `true` from a callback. It returns an array of arrays, where each inner array corresponds to the groups that you created via the callback. ```js // (input) => h1 h2>>h3 const list = selectors.first.split(selector => { return selector.type === 'combinator'; }); // (node values) => [['h1', ' '], ['h2', '>>'], ['h3']] ``` Arguments: * `callback (function)`: A function to call for each node, which receives `node` as an argument. ### `container.prepend(node)` & `container.append(node)` Add a node to the start/end of the container. Note that doing so will set the parent property of the node to this container. ```js const id = parser.id({value: 'search'}); selector.append(id); ``` Arguments: * `node`: The node to add. ### `container.insertBefore(old, new)` & `container.insertAfter(old, new)` Add a node before or after an existing node in a container: ```js selectors.walk(selector => { if (selector.type !== 'class') { const className = parser.className({value: 'theme-name'}); selector.parent.insertAfter(selector, className); } }); ``` Arguments: * `old`: The existing node in the container. * `new`: The new node to add before/after the existing node. ### `container.removeChild(node)` Remove the node from the container. Note that you can also use `node.remove()` if you would like to remove just a single node. ```js selector.length // => 2 selector.remove(id) selector.length // => 1; id.parent // undefined ``` Arguments: * `node`: The node to remove. ### `container.removeAll()` or `container.empty()` Remove all children from the container. ```js selector.removeAll(); selector.length // => 0 ``` ## Root nodes A root node represents a comma separated list of selectors. Indeed, all a root's `toString()` method does is join its selector children with a ','. Other than this, it has no special functionality and acts like a container. ### `root.trailingComma` This will be set to `true` if the input has a trailing comma, in order to support parsing of legacy CSS hacks. ## Selector nodes A selector node represents a single compound selector. For example, this selector string `h1 h2 h3, [href] > p`, is represented as two selector nodes. It has no special functionality of its own. ## Pseudo nodes A pseudo selector extends a container node; if it has any parameters of its own (such as `h1:not(h2, h3)`), they will be its children. Note that the pseudo `value` will always contain the colons preceding the pseudo identifier. This is so that both `:before` and `::before` are properly represented in the AST. ## Attribute nodes ### `attribute.quoted` Returns `true` if the attribute's value is wrapped in quotation marks, false if it is not. Remains `undefined` if there is no attribute value. ```css [href=foo] /* false */ [href='foo'] /* true */ [href="foo"] /* true */ [href] /* undefined */ ``` ### `attribute.qualifiedAttribute` Returns the attribute name qualified with the namespace if one is given. ### `attribute.offsetOf(part)` Returns the offset of the attribute part specified relative to the start of the node of the output string. This is useful in raising error messages about a specific part of the attribute, especially in combination with `attribute.sourceIndex`. Returns `-1` if the name is invalid or the value doesn't exist in this attribute. The legal values for `part` are: * `"ns"` - alias for "namespace" * `"namespace"` - the namespace if it exists. * `"attribute"` - the attribute name * `"attributeNS"` - the start of the attribute or its namespace * `"operator"` - the match operator of the attribute * `"value"` - The value (string or identifier) * `"insensitive"` - the case insensitivity flag ### `attribute.raws.unquoted` Returns the unquoted content of the attribute's value. Remains `undefined` if there is no attribute value. ```css [href=foo] /* foo */ [href='foo'] /* foo */ [href="foo"] /* foo */ [href] /* undefined */ ``` ### `attribute.spaces` Like `node.spaces` with the `before` and `after` values containing the spaces around the element, the parts of the attribute can also have spaces before and after them. The for each of `attribute`, `operator`, `value` and `insensitive` there is corresponding property of the same nam in `node.spaces` that has an optional `before` or `after` string containing only whitespace. Note that corresponding values in `attributes.raws.spaces` contain values including any comments. If set, these values will override the `attribute.spaces` value. Take care to remove them if changing `attribute.spaces`. ### `attribute.raws` The raws object stores comments and other information necessary to re-render the node exactly as it was in the source. If a comment is embedded within the identifiers for the `namespace`, `attribute` or `value` then a property is placed in the raws for that value containing the full source of the propery including comments. If a comment is embedded within the space between parts of the attribute then the raw for that space is set accordingly. Setting an attribute's property `raws` value to be deleted. For now, changing the spaces required also updating or removing any of the raws values that override them. Example: `[ /*before*/ href /* after-attr */ = /* after-operator */ te/*inside-value*/st/* wow */ /*omg*/i/*bbq*/ /*whodoesthis*/]` would parse as: ```js { attribute: "href", operatator: "=", value: "test", spaces: { before: '', after: '', attribute: { before: ' ', after: ' ' }, operator: { after: ' ' }, value: { after: ' ' }, insensitive: { after: ' ' } }, raws: { spaces: { attribute: { before: ' /*before*/ ', after: ' /* after-attr */ ' }, operator: { after: ' /* after-operator */ ' }, value: { after: '/* wow */ /*omg*/' }, insensitive: { after: '/*bbq*/ /*whodoesthis*/' } }, unquoted: 'test', value: 'te/*inside-value*/st' } } ``` ## `Processor` ### `ProcessorOptions` * `lossless` - When `true`, whitespace is preserved. Defaults to `true`. * `updateSelector` - When `true`, if any processor methods are passed a postcss `Rule` node instead of a string, then that Rule's selector is updated with the results of the processing. Defaults to `true`. ### `process|processSync(selectors, [options])` Processes the `selectors`, returning a string from the result of processing. Note: when the `updateSelector` option is set, the rule's selector will be updated with the resulting string. **Example:** ```js const parser = require("postcss-selector-parser"); const processor = parser(); let result = processor.processSync(' .class'); console.log(result); // => .class // Asynchronous operation let promise = processor.process(' .class').then(result => { console.log(result) // => .class }); // To have the parser normalize whitespace values, utilize the options result = processor.processSync(' .class ', {lossless: false}); console.log(result); // => .class // For better syntax errors, pass a PostCSS Rule node. const postcss = require('postcss'); rule = postcss.rule({selector: ' #foo > a, .class '}); processor.process(rule, {lossless: false, updateSelector: true}).then(result => { console.log(result); // => #foo>a,.class console.log("rule:", rule.selector); // => rule: #foo>a,.class }) ``` Arguments: * `selectors (string|postcss.Rule)`: Either a selector string or a PostCSS Rule node. * `[options] (object)`: Process options ### `ast|astSync(selectors, [options])` Like `process()` and `processSync()` but after processing the `selectors` these methods return the `Root` node of the result instead of a string. Note: when the `updateSelector` option is set, the rule's selector will be updated with the resulting string. ### `transform|transformSync(selectors, [options])` Like `process()` and `processSync()` but after processing the `selectors` these methods return the value returned by the processor callback. Note: when the `updateSelector` option is set, the rule's selector will be updated with the resulting string. ### Error Handling Within Selector Processors The root node passed to the selector processor callback has a method `error(message, options)` that returns an error object. This method should always be used to raise errors relating to the syntax of selectors. The options to this method are passed to postcss's error constructor ([documentation](http://api.postcss.org/Container.html#error)). #### Async Error Example ```js let processor = (root) => { return new Promise((resolve, reject) => { root.walkClasses((classNode) => { if (/^(.*)[-_]/.test(classNode.value)) { let msg = "classes may not have underscores or dashes in them"; reject(root.error(msg, { index: classNode.sourceIndex + RegExp.$1.length + 1, word: classNode.value })); } }); resolve(); }); }; const postcss = require("postcss"); const parser = require("postcss-selector-parser"); const selectorProcessor = parser(processor); const plugin = postcss.plugin('classValidator', (options) => { return (root) => { let promises = []; root.walkRules(rule => { promises.push(selectorProcessor.process(rule)); }); return Promise.all(promises); }; }); postcss(plugin()).process(` .foo-bar { color: red; } `.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString())); // CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them // // > 1 | .foo-bar { // | ^ // 2 | color: red; // 3 | } ``` #### Synchronous Error Example ```js let processor = (root) => { root.walkClasses((classNode) => { if (/.*[-_]/.test(classNode.value)) { let msg = "classes may not have underscores or dashes in them"; throw root.error(msg, { index: classNode.sourceIndex, word: classNode.value }); } }); }; const postcss = require("postcss"); const parser = require("postcss-selector-parser"); const selectorProcessor = parser(processor); const plugin = postcss.plugin('classValidator', (options) => { return (root) => { root.walkRules(rule => { selectorProcessor.processSync(rule); }); }; }); postcss(plugin()).process(` .foo-bar { color: red; } `.trim(), {from: 'test.css'}).catch((e) => console.error(e.toString())); // CssSyntaxError: classValidator: ./test.css:1:5: classes may not have underscores or dashes in them // // > 1 | .foo-bar { // | ^ // 2 | color: red; // 3 | } ```
/* Copyright (c) 2011, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * 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/slab.h> #include <linux/delay.h> #include <linux/types.h> #include <linux/i2c.h> #include <linux/uaccess.h> #include <linux/miscdevice.h> #include <media/msm_camera.h> #include <mach/gpio.h> #include "mt9d113.h" /* Micron MT9D113 Registers and their values */ #define REG_MT9D113_MODEL_ID 0x0000 #define MT9D113_MODEL_ID 0x2580 #define Q8 0x00000100 struct mt9d113_work { struct work_struct work; }; static struct mt9d113_work *mt9d113_sensorw; static struct i2c_client *mt9d113_client; struct mt9d113_ctrl { const struct msm_camera_sensor_info *sensordata; uint32_t sensormode; uint32_t fps_divider;/* init to 1 * 0x00000400 */ uint32_t pict_fps_divider;/* init to 1 * 0x00000400 */ uint16_t fps; uint16_t curr_step_pos; uint16_t my_reg_gain; uint32_t my_reg_line_count; uint16_t total_lines_per_frame; uint16_t config_csi; enum mt9d113_resolution_t prev_res; enum mt9d113_resolution_t pict_res; enum mt9d113_resolution_t curr_res; enum mt9d113_test_mode_t set_test; }; static struct mt9d113_ctrl *mt9d113_ctrl; static DECLARE_WAIT_QUEUE_HEAD(mt9d113_wait_queue); DEFINE_MUTEX(mt9d113_mut); static int mt9d113_i2c_rxdata(unsigned short saddr, unsigned char *rxdata, int length) { struct i2c_msg msgs[] = { { .addr = saddr, .flags = 0, .len = 2, .buf = rxdata, }, { .addr = saddr, .flags = I2C_M_RD, .len = length, .buf = rxdata, }, }; if (i2c_transfer(mt9d113_client->adapter, msgs, 2) < 0) { CDBG("mt9d113_i2c_rxdata failed!\n"); return -EIO; } return 0; } static int32_t mt9d113_i2c_read(unsigned short saddr, unsigned short raddr, unsigned short *rdata, enum mt9d113_width width) { int32_t rc = 0; unsigned char buf[4]; if (!rdata) return -EIO; memset(buf, 0, sizeof(buf)); switch (width) { case WORD_LEN: { buf[0] = (raddr & 0xFF00)>>8; buf[1] = (raddr & 0x00FF); rc = mt9d113_i2c_rxdata(saddr, buf, 2); if (rc < 0) return rc; *rdata = buf[0] << 8 | buf[1]; } break; default: break; } if (rc < 0) CDBG("mt9d113_i2c_read failed !\n"); return rc; } static int32_t mt9d113_i2c_txdata(unsigned short saddr, unsigned char *txdata, int length) { struct i2c_msg msg[] = { { .addr = saddr, .flags = 0, .len = length, .buf = txdata, }, }; if (i2c_transfer(mt9d113_client->adapter, msg, 1) < 0) { CDBG("mt9d113_i2c_txdata failed\n"); return -EIO; } return 0; } static int32_t mt9d113_i2c_write(unsigned short saddr, unsigned short waddr, unsigned short wdata, enum mt9d113_width width) { int32_t rc = -EIO; unsigned char buf[4]; memset(buf, 0, sizeof(buf)); switch (width) { case WORD_LEN: { buf[0] = (waddr & 0xFF00)>>8; buf[1] = (waddr & 0x00FF); buf[2] = (wdata & 0xFF00)>>8; buf[3] = (wdata & 0x00FF); rc = mt9d113_i2c_txdata(saddr, buf, 4); } break; case BYTE_LEN: { buf[0] = waddr; buf[1] = wdata; rc = mt9d113_i2c_txdata(saddr, buf, 2); } break; default: break; } if (rc < 0) printk(KERN_ERR "i2c_write failed, addr = 0x%x, val = 0x%x!\n", waddr, wdata); return rc; } static int32_t mt9d113_i2c_write_table( struct mt9d113_i2c_reg_conf const *reg_conf_tbl, int num_of_items_in_table) { int i; int32_t rc = -EIO; for (i = 0; i < num_of_items_in_table; i++) { rc = mt9d113_i2c_write(mt9d113_client->addr, reg_conf_tbl->waddr, reg_conf_tbl->wdata, WORD_LEN); if (rc < 0) break; reg_conf_tbl++; } return rc; } static long mt9d113_reg_init(void) { uint16_t data = 0; int32_t rc = 0; int count = 0; struct msm_camera_csi_params mt9d113_csi_params; if (!mt9d113_ctrl->config_csi) { mt9d113_csi_params.lane_cnt = 1; mt9d113_csi_params.data_format = CSI_8BIT; mt9d113_csi_params.lane_assign = 0xe4; mt9d113_csi_params.dpcm_scheme = 0; mt9d113_csi_params.settle_cnt = 0x14; rc = msm_camio_csi_config(&mt9d113_csi_params); mt9d113_ctrl->config_csi = 1; msleep(50); } /* Disable parallel and enable mipi*/ rc = mt9d113_i2c_write(mt9d113_client->addr, 0x001A, 0x0051, WORD_LEN); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x001A, 0x0050, WORD_LEN); msleep(20); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x001A, 0x0058, WORD_LEN); /* Preset pll settings begin*/ rc = mt9d113_i2c_write_table(&mt9d113_regs.pll_tbl[0], mt9d113_regs.pll_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0014, &data, WORD_LEN); data = data&0x8000; /* Poll*/ while (data == 0x0000) { data = 0; rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0014, &data, WORD_LEN); data = data & 0x8000; usleep_range(11000, 12000); count++; if (count == 100) { CDBG(" Timeout:1\n"); break; } } rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0014, 0x20FA, WORD_LEN); /*Preset pll Ends*/ mt9d113_i2c_write(mt9d113_client->addr, 0x0018, 0x402D, WORD_LEN); mt9d113_i2c_write(mt9d113_client->addr, 0x0018, 0x402C, WORD_LEN); /*POLL_REG=0x0018,0x4000,!=0x0000,DELAY=10,TIMEOUT=100*/ data = 0; rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0018, &data, WORD_LEN); data = data & 0x4000; count = 0; while (data != 0x0000) { rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0018, &data, WORD_LEN); data = data & 0x4000; CDBG(" data is %d\n" , data); usleep_range(11000, 12000); count++; if (count == 100) { CDBG(" Loop2 timeout: MT9D113\n"); break; } CDBG(" Not streaming\n"); } CDBG("MT9D113: Start stream\n"); /*Preset Register Wizard Conf*/ rc = mt9d113_i2c_write_table(&mt9d113_regs.register_tbl[0], mt9d113_regs.register_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_write_table(&mt9d113_regs.err_tbl[0], mt9d113_regs.err_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_write_table(&mt9d113_regs.eeprom_tbl[0], mt9d113_regs.eeprom_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_write_table(&mt9d113_regs.low_light_tbl[0], mt9d113_regs.low_light_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_write_table(&mt9d113_regs.awb_tbl[0], mt9d113_regs.awb_tbl_size); if (rc < 0) return rc; rc = mt9d113_i2c_write_table(&mt9d113_regs.patch_tbl[0], mt9d113_regs.patch_tbl_size); if (rc < 0) return rc; /*check patch load*/ mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA024, WORD_LEN); count = 0; /*To check if patch is loaded properly poll the register 0x990 till the condition is met or till the timeout*/ data = 0; rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0990, &data, WORD_LEN); while (data == 0) { data = 0; rc = mt9d113_i2c_read(mt9d113_client->addr, 0x0990, &data, WORD_LEN); usleep_range(11000, 12000); count++; if (count == 100) { CDBG("Timeout in patch loading\n"); break; } } /*BITFIELD=0x0018, 0x0004, 0*/ /*Preset continue begin */ rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0018, 0x0028, WORD_LEN); CDBG(" mt9d113 wait for seq done\n"); /* syncronize the FW with the sensor MCU_ADDRESS [SEQ_CMD]*/ rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN); /*mt9d113 wait for seq done syncronize the FW with the sensor */ msleep(20); /*Preset continue end */ CDBG(" MT9D113: Preset continue end\n"); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0012, 0x00F5, WORD_LEN); /*continue begin */ CDBG(" MT9D113: Preset continue begin\n"); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0018, 0x0028 , WORD_LEN); /*mt9d113 wait for seq done syncronize the FW with the sensor MCU_ADDRESS [SEQ_CMD]*/ msleep(20); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); /* MCU DATA */ rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0006, WORD_LEN); /*mt9d113 wait for seq done syncronize the FW with the sensor */ /* MCU_ADDRESS [SEQ_CMD]*/ msleep(20); /*Preset continue end*/ return rc; } static long mt9d113_set_sensor_mode(int mode) { long rc = 0; switch (mode) { case SENSOR_PREVIEW_MODE: rc = mt9d113_reg_init(); CDBG("MT9D113: configure to preview begin\n"); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN); if (rc < 0) return rc; rc = mt9d113_i2c_write(mt9d113_client->addr, 0x0990, 0x0000, WORD_LEN); if (rc < 0) return rc; rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); if (rc < 0) return rc; rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x0001, WORD_LEN); if (rc < 0) return rc; break; case SENSOR_SNAPSHOT_MODE: case SENSOR_RAW_SNAPSHOT_MODE: rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA115, WORD_LEN); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x0002, WORD_LEN); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0xA103, WORD_LEN); rc = mt9d113_i2c_write(mt9d113_client->addr, 0x098C, 0x0002, WORD_LEN); break; default: return -EINVAL; } return 0; } static int mt9d113_sensor_init_probe(const struct msm_camera_sensor_info * data) { uint16_t model_id = 0; int rc = 0; /* Read the Model ID of the sensor */ rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID, &model_id, WORD_LEN); if (rc < 0) goto init_probe_fail; /* Check if it matches it with the value in Datasheet */ if (model_id != MT9D113_MODEL_ID) printk(KERN_INFO "mt9d113 model_id = 0x%x\n", model_id); if (rc < 0) goto init_probe_fail; return rc; init_probe_fail: printk(KERN_INFO "probe fail\n"); return rc; } static int mt9d113_init_client(struct i2c_client *client) { /* Initialize the MSM_CAMI2C Chip */ init_waitqueue_head(&mt9d113_wait_queue); return 0; } int mt9d113_sensor_config(void __user *argp) { struct sensor_cfg_data cfg_data; long rc = 0; if (copy_from_user(&cfg_data, (void *)argp, (sizeof(struct sensor_cfg_data)))) return -EFAULT; mutex_lock(&mt9d113_mut); CDBG("mt9d113_ioctl, cfgtype = %d, mode = %d\n", cfg_data.cfgtype, cfg_data.mode); switch (cfg_data.cfgtype) { case CFG_SET_MODE: rc = mt9d113_set_sensor_mode( cfg_data.mode); break; case CFG_SET_EFFECT: return rc; case CFG_GET_AF_MAX_STEPS: default: rc = -EINVAL; break; } mutex_unlock(&mt9d113_mut); return rc; } int mt9d113_sensor_release(void) { int rc = 0; mutex_lock(&mt9d113_mut); gpio_set_value_cansleep(mt9d113_ctrl->sensordata->sensor_reset, 0); msleep(20); gpio_free(mt9d113_ctrl->sensordata->sensor_reset); kfree(mt9d113_ctrl); mutex_unlock(&mt9d113_mut); return rc; } static int mt9d113_probe_init_done(const struct msm_camera_sensor_info *data) { gpio_free(data->sensor_reset); return 0; } static int mt9d113_probe_init_sensor(const struct msm_camera_sensor_info *data) { int32_t rc = 0; uint16_t chipid = 0; rc = gpio_request(data->sensor_pwd, "mt9d113"); if (!rc) { printk(KERN_INFO "sensor_reset = %d\n", rc); gpio_direction_output(data->sensor_pwd, 0); usleep_range(11000, 12000); } else { goto init_probe_done; } msleep(20); rc = gpio_request(data->sensor_reset, "mt9d113"); printk(KERN_INFO " mt9d113_probe_init_sensor\n"); if (!rc) { printk(KERN_INFO "sensor_reset = %d\n", rc); gpio_direction_output(data->sensor_reset, 0); usleep_range(11000, 12000); gpio_set_value_cansleep(data->sensor_reset, 1); usleep_range(11000, 12000); } else goto init_probe_done; printk(KERN_INFO " mt9d113_probe_init_sensor called\n"); rc = mt9d113_i2c_read(mt9d113_client->addr, REG_MT9D113_MODEL_ID, &chipid, 2); if (rc < 0) goto init_probe_fail; /*Compare sensor ID to MT9D113 ID: */ if (chipid != MT9D113_MODEL_ID) { printk(KERN_INFO "mt9d113_probe_init_sensor chip idis%d\n", chipid); } CDBG("mt9d113_probe_init_sensor Success\n"); goto init_probe_done; init_probe_fail: CDBG(" ov2720_probe_init_sensor fails\n"); gpio_set_value_cansleep(data->sensor_reset, 0); mt9d113_probe_init_done(data); init_probe_done: printk(KERN_INFO " mt9d113_probe_init_sensor finishes\n"); return rc; } static int mt9d113_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc = 0; if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { rc = -ENOTSUPP; goto probe_failure; } mt9d113_sensorw = kzalloc(sizeof(struct mt9d113_work), GFP_KERNEL); if (!mt9d113_sensorw) { rc = -ENOMEM; goto probe_failure; } i2c_set_clientdata(client, mt9d113_sensorw); mt9d113_init_client(client); mt9d113_client = client; CDBG("mt9d113_probe succeeded!\n"); return 0; probe_failure: kfree(mt9d113_sensorw); mt9d113_sensorw = NULL; CDBG("mt9d113_probe failed!\n"); return rc; } static const struct i2c_device_id mt9d113_i2c_id[] = { { "mt9d113", 0}, {}, }; static struct i2c_driver mt9d113_i2c_driver = { .id_table = mt9d113_i2c_id, .probe = mt9d113_i2c_probe, .remove = __exit_p(mt9d113_i2c_remove), .driver = { .name = "mt9d113", }, }; int mt9d113_sensor_open_init(const struct msm_camera_sensor_info *data) { int32_t rc = 0; mt9d113_ctrl = kzalloc(sizeof(struct mt9d113_ctrl), GFP_KERNEL); if (!mt9d113_ctrl) { printk(KERN_INFO "mt9d113_init failed!\n"); rc = -ENOMEM; goto init_done; } mt9d113_ctrl->fps_divider = 1 * 0x00000400; mt9d113_ctrl->pict_fps_divider = 1 * 0x00000400; mt9d113_ctrl->set_test = TEST_OFF; mt9d113_ctrl->config_csi = 0; mt9d113_ctrl->prev_res = QTR_SIZE; mt9d113_ctrl->pict_res = FULL_SIZE; mt9d113_ctrl->curr_res = INVALID_SIZE; if (data) mt9d113_ctrl->sensordata = data; if (rc < 0) { printk(KERN_INFO "mt9d113_sensor_open_init fail\n"); return rc; } /* enable mclk first */ msm_camio_clk_rate_set(24000000); msleep(20); rc = mt9d113_probe_init_sensor(data); if (rc < 0) goto init_fail; mt9d113_ctrl->fps = 30*Q8; rc = mt9d113_sensor_init_probe(data); if (rc < 0) { gpio_set_value_cansleep(data->sensor_reset, 0); goto init_fail; } else printk(KERN_ERR "%s: %d\n", __func__, __LINE__); goto init_done; init_fail: printk(KERN_INFO "init_fail\n"); mt9d113_probe_init_done(data); init_done: CDBG("init_done\n"); return rc; } static int mt9d113_sensor_probe(const struct msm_camera_sensor_info *info, struct msm_sensor_ctrl *s) { int rc = 0; rc = i2c_add_driver(&mt9d113_i2c_driver); if (rc < 0 || mt9d113_client == NULL) { rc = -ENOTSUPP; goto probe_fail; } msm_camio_clk_rate_set(24000000); usleep_range(5000, 6000); rc = mt9d113_probe_init_sensor(info); if (rc < 0) goto probe_fail; s->s_init = mt9d113_sensor_open_init; s->s_release = mt9d113_sensor_release; s->s_config = mt9d113_sensor_config; s->s_camera_type = FRONT_CAMERA_2D; s->s_mount_angle = 0; gpio_set_value_cansleep(info->sensor_reset, 0); mt9d113_probe_init_done(info); return rc; probe_fail: printk(KERN_INFO "mt9d113_sensor_probe: SENSOR PROBE FAILS!\n"); return rc; } static int __mt9d113_probe(struct platform_device *pdev) { return msm_camera_drv_start(pdev, mt9d113_sensor_probe); } static struct platform_driver msm_camera_driver = { .probe = __mt9d113_probe, .driver = { .name = "msm_camera_mt9d113", .owner = THIS_MODULE, }, }; static int __init mt9d113_init(void) { return platform_driver_register(&msm_camera_driver); } module_init(mt9d113_init); MODULE_DESCRIPTION("Micron 2MP YUV sensor driver"); MODULE_LICENSE("GPL v2");
// SPDX-License-Identifier: GPL-2.0-only #include <linux/types.h> #include <linux/mm.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/module.h> #include <asm/page.h> #include <asm/pgtable.h> #include <asm/amigaints.h> #include <asm/amigahw.h> #include "scsi.h" #include "wd33c93.h" #include "a3000.h" struct a3000_hostdata { struct WD33C93_hostdata wh; struct a3000_scsiregs *regs; }; static irqreturn_t a3000_intr(int irq, void *data) { struct Scsi_Host *instance = data; struct a3000_hostdata *hdata = shost_priv(instance); unsigned int status = hdata->regs->ISTR; unsigned long flags; if (!(status & ISTR_INT_P)) return IRQ_NONE; if (status & ISTR_INTS) { spin_lock_irqsave(instance->host_lock, flags); wd33c93_intr(instance); spin_unlock_irqrestore(instance->host_lock, flags); return IRQ_HANDLED; } pr_warn("Non-serviced A3000 SCSI-interrupt? ISTR = %02x\n", status); return IRQ_NONE; } static int dma_setup(struct scsi_cmnd *cmd, int dir_in) { struct Scsi_Host *instance = cmd->device->host; struct a3000_hostdata *hdata = shost_priv(instance); struct WD33C93_hostdata *wh = &hdata->wh; struct a3000_scsiregs *regs = hdata->regs; unsigned short cntr = CNTR_PDMD | CNTR_INTEN; unsigned long addr = virt_to_bus(cmd->SCp.ptr); /* * if the physical address has the wrong alignment, or if * physical address is bad, or if it is a write and at the * end of a physical memory chunk, then allocate a bounce * buffer */ if (addr & A3000_XFER_MASK) { wh->dma_bounce_len = (cmd->SCp.this_residual + 511) & ~0x1ff; wh->dma_bounce_buffer = kmalloc(wh->dma_bounce_len, GFP_KERNEL); /* can't allocate memory; use PIO */ if (!wh->dma_bounce_buffer) { wh->dma_bounce_len = 0; return 1; } if (!dir_in) { /* copy to bounce buffer for a write */ memcpy(wh->dma_bounce_buffer, cmd->SCp.ptr, cmd->SCp.this_residual); } addr = virt_to_bus(wh->dma_bounce_buffer); } /* setup dma direction */ if (!dir_in) cntr |= CNTR_DDIR; /* remember direction */ wh->dma_dir = dir_in; regs->CNTR = cntr; /* setup DMA *physical* address */ regs->ACR = addr; if (dir_in) { /* invalidate any cache */ cache_clear(addr, cmd->SCp.this_residual); } else { /* push any dirty cache */ cache_push(addr, cmd->SCp.this_residual); } /* start DMA */ mb(); /* make sure setup is completed */ regs->ST_DMA = 1; mb(); /* make sure DMA has started before next IO */ /* return success */ return 0; } static void dma_stop(struct Scsi_Host *instance, struct scsi_cmnd *SCpnt, int status) { struct a3000_hostdata *hdata = shost_priv(instance); struct WD33C93_hostdata *wh = &hdata->wh; struct a3000_scsiregs *regs = hdata->regs; /* disable SCSI interrupts */ unsigned short cntr = CNTR_PDMD; if (!wh->dma_dir) cntr |= CNTR_DDIR; regs->CNTR = cntr; mb(); /* make sure CNTR is updated before next IO */ /* flush if we were reading */ if (wh->dma_dir) { regs->FLUSH = 1; mb(); /* don't allow prefetch */ while (!(regs->ISTR & ISTR_FE_FLG)) barrier(); mb(); /* no IO until FLUSH is done */ } /* clear a possible interrupt */ /* I think that this CINT is only necessary if you are * using the terminal count features. HM 7 Mar 1994 */ regs->CINT = 1; /* stop DMA */ regs->SP_DMA = 1; mb(); /* make sure DMA is stopped before next IO */ /* restore the CONTROL bits (minus the direction flag) */ regs->CNTR = CNTR_PDMD | CNTR_INTEN; mb(); /* make sure CNTR is updated before next IO */ /* copy from a bounce buffer, if necessary */ if (status && wh->dma_bounce_buffer) { if (SCpnt) { if (wh->dma_dir && SCpnt) memcpy(SCpnt->SCp.ptr, wh->dma_bounce_buffer, SCpnt->SCp.this_residual); kfree(wh->dma_bounce_buffer); wh->dma_bounce_buffer = NULL; wh->dma_bounce_len = 0; } else { kfree(wh->dma_bounce_buffer); wh->dma_bounce_buffer = NULL; wh->dma_bounce_len = 0; } } } static struct scsi_host_template amiga_a3000_scsi_template = { .module = THIS_MODULE, .name = "Amiga 3000 built-in SCSI", .show_info = wd33c93_show_info, .write_info = wd33c93_write_info, .proc_name = "A3000", .queuecommand = wd33c93_queuecommand, .eh_abort_handler = wd33c93_abort, .eh_host_reset_handler = wd33c93_host_reset, .can_queue = CAN_QUEUE, .this_id = 7, .sg_tablesize = SG_ALL, .cmd_per_lun = CMD_PER_LUN, }; static int __init amiga_a3000_scsi_probe(struct platform_device *pdev) { struct resource *res; struct Scsi_Host *instance; int error; struct a3000_scsiregs *regs; wd33c93_regs wdregs; struct a3000_hostdata *hdata; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -ENODEV; if (!request_mem_region(res->start, resource_size(res), "wd33c93")) return -EBUSY; instance = scsi_host_alloc(&amiga_a3000_scsi_template, sizeof(struct a3000_hostdata)); if (!instance) { error = -ENOMEM; goto fail_alloc; } instance->irq = IRQ_AMIGA_PORTS; regs = ZTWO_VADDR(res->start); regs->DAWR = DAWR_A3000; wdregs.SASR = &regs->SASR; wdregs.SCMD = &regs->SCMD; hdata = shost_priv(instance); hdata->wh.no_sync = 0xff; hdata->wh.fast = 0; hdata->wh.dma_mode = CTRL_DMA; hdata->regs = regs; wd33c93_init(instance, wdregs, dma_setup, dma_stop, WD33C93_FS_12_15); error = request_irq(IRQ_AMIGA_PORTS, a3000_intr, IRQF_SHARED, "A3000 SCSI", instance); if (error) goto fail_irq; regs->CNTR = CNTR_PDMD | CNTR_INTEN; error = scsi_add_host(instance, NULL); if (error) goto fail_host; platform_set_drvdata(pdev, instance); scsi_scan_host(instance); return 0; fail_host: free_irq(IRQ_AMIGA_PORTS, instance); fail_irq: scsi_host_put(instance); fail_alloc: release_mem_region(res->start, resource_size(res)); return error; } static int __exit amiga_a3000_scsi_remove(struct platform_device *pdev) { struct Scsi_Host *instance = platform_get_drvdata(pdev); struct a3000_hostdata *hdata = shost_priv(instance); struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0); hdata->regs->CNTR = 0; scsi_remove_host(instance); free_irq(IRQ_AMIGA_PORTS, instance); scsi_host_put(instance); release_mem_region(res->start, resource_size(res)); return 0; } static struct platform_driver amiga_a3000_scsi_driver = { .remove = __exit_p(amiga_a3000_scsi_remove), .driver = { .name = "amiga-a3000-scsi", }, }; module_platform_driver_probe(amiga_a3000_scsi_driver, amiga_a3000_scsi_probe); MODULE_DESCRIPTION("Amiga 3000 built-in SCSI"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:amiga-a3000-scsi");
/* * Public API and common code for kernel->userspace relay file support. * * See Documentation/filesystems/relay.txt for an overview. * * Copyright (C) 2002-2005 - Tom Zanussi (zanussi@us.ibm.com), IBM Corp * Copyright (C) 1999-2005 - Karim Yaghmour (karim@opersys.com) * * Moved to kernel/relay.c by Paul Mundt, 2006. * November 2006 - CPU hotplug support by Mathieu Desnoyers * (mathieu.desnoyers@polymtl.ca) * * This file is released under the GPL. */ #include <linux/errno.h> #include <linux/stddef.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/string.h> #include <linux/relay.h> #include <linux/vmalloc.h> #include <linux/mm.h> #include <linux/cpu.h> #include <linux/splice.h> /* list of open channels, for cpu hotplug */ static DEFINE_MUTEX(relay_channels_mutex); static LIST_HEAD(relay_channels); /* * close() vm_op implementation for relay file mapping. */ static void relay_file_mmap_close(struct vm_area_struct *vma) { struct rchan_buf *buf = vma->vm_private_data; buf->chan->cb->buf_unmapped(buf, vma->vm_file); } /* * fault() vm_op implementation for relay file mapping. */ static int relay_buf_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page; struct rchan_buf *buf = vma->vm_private_data; pgoff_t pgoff = vmf->pgoff; if (!buf) return VM_FAULT_OOM; page = vmalloc_to_page(buf->start + (pgoff << PAGE_SHIFT)); if (!page) return VM_FAULT_SIGBUS; get_page(page); vmf->page = page; return 0; } /* * vm_ops for relay file mappings. */ static struct vm_operations_struct relay_file_mmap_ops = { .fault = relay_buf_fault, .close = relay_file_mmap_close, }; /* * allocate an array of pointers of struct page */ static struct page **relay_alloc_page_array(unsigned int n_pages) { struct page **array; size_t pa_size = n_pages * sizeof(struct page *); if (pa_size > PAGE_SIZE) { array = vmalloc(pa_size); if (array) memset(array, 0, pa_size); } else { array = kzalloc(pa_size, GFP_KERNEL); } return array; } /* * free an array of pointers of struct page */ static void relay_free_page_array(struct page **array) { if (is_vmalloc_addr(array)) vfree(array); else kfree(array); } /** * relay_mmap_buf: - mmap channel buffer to process address space * @buf: relay channel buffer * @vma: vm_area_struct describing memory to be mapped * * Returns 0 if ok, negative on error * * Caller should already have grabbed mmap_sem. */ static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma) { unsigned long length = vma->vm_end - vma->vm_start; struct file *filp = vma->vm_file; if (!buf) return -EBADF; if (length != (unsigned long)buf->chan->alloc_size) return -EINVAL; vma->vm_ops = &relay_file_mmap_ops; vma->vm_flags |= VM_DONTEXPAND; vma->vm_private_data = buf; buf->chan->cb->buf_mapped(buf, filp); return 0; } /** * relay_alloc_buf - allocate a channel buffer * @buf: the buffer struct * @size: total size of the buffer * * Returns a pointer to the resulting buffer, %NULL if unsuccessful. The * passed in size will get page aligned, if it isn't already. */ static void *relay_alloc_buf(struct rchan_buf *buf, size_t *size) { void *mem; unsigned int i, j, n_pages; *size = PAGE_ALIGN(*size); n_pages = *size >> PAGE_SHIFT; buf->page_array = relay_alloc_page_array(n_pages); if (!buf->page_array) return NULL; for (i = 0; i < n_pages; i++) { buf->page_array[i] = alloc_page(GFP_KERNEL); if (unlikely(!buf->page_array[i])) goto depopulate; set_page_private(buf->page_array[i], (unsigned long)buf); } mem = vmap(buf->page_array, n_pages, VM_MAP, PAGE_KERNEL); if (!mem) goto depopulate; memset(mem, 0, *size); buf->page_count = n_pages; return mem; depopulate: for (j = 0; j < i; j++) __free_page(buf->page_array[j]); relay_free_page_array(buf->page_array); return NULL; } /** * relay_create_buf - allocate and initialize a channel buffer * @chan: the relay channel * * Returns channel buffer if successful, %NULL otherwise. */ static struct rchan_buf *relay_create_buf(struct rchan *chan) { struct rchan_buf *buf = kzalloc(sizeof(struct rchan_buf), GFP_KERNEL); if (!buf) return NULL; buf->padding = kmalloc(chan->n_subbufs * sizeof(size_t *), GFP_KERNEL); if (!buf->padding) goto free_buf; buf->start = relay_alloc_buf(buf, &chan->alloc_size); if (!buf->start) goto free_buf; buf->chan = chan; kref_get(&buf->chan->kref); return buf; free_buf: kfree(buf->padding); kfree(buf); return NULL; } /** * relay_destroy_channel - free the channel struct * @kref: target kernel reference that contains the relay channel * * Should only be called from kref_put(). */ static void relay_destroy_channel(struct kref *kref) { struct rchan *chan = container_of(kref, struct rchan, kref); kfree(chan); } /** * relay_destroy_buf - destroy an rchan_buf struct and associated buffer * @buf: the buffer struct */ static void relay_destroy_buf(struct rchan_buf *buf) { struct rchan *chan = buf->chan; unsigned int i; if (likely(buf->start)) { vunmap(buf->start); for (i = 0; i < buf->page_count; i++) __free_page(buf->page_array[i]); relay_free_page_array(buf->page_array); } chan->buf[buf->cpu] = NULL; kfree(buf->padding); kfree(buf); kref_put(&chan->kref, relay_destroy_channel); } /** * relay_remove_buf - remove a channel buffer * @kref: target kernel reference that contains the relay buffer * * Removes the file from the fileystem, which also frees the * rchan_buf_struct and the channel buffer. Should only be called from * kref_put(). */ static void relay_remove_buf(struct kref *kref) { struct rchan_buf *buf = container_of(kref, struct rchan_buf, kref); buf->chan->cb->remove_buf_file(buf->dentry); relay_destroy_buf(buf); } /** * relay_buf_empty - boolean, is the channel buffer empty? * @buf: channel buffer * * Returns 1 if the buffer is empty, 0 otherwise. */ static int relay_buf_empty(struct rchan_buf *buf) { return (buf->subbufs_produced - buf->subbufs_consumed) ? 0 : 1; } /** * relay_buf_full - boolean, is the channel buffer full? * @buf: channel buffer * * Returns 1 if the buffer is full, 0 otherwise. */ int relay_buf_full(struct rchan_buf *buf) { size_t ready = buf->subbufs_produced - buf->subbufs_consumed; return (ready >= buf->chan->n_subbufs) ? 1 : 0; } EXPORT_SYMBOL_GPL(relay_buf_full); /* * High-level relay kernel API and associated functions. */ /* * rchan_callback implementations defining default channel behavior. Used * in place of corresponding NULL values in client callback struct. */ /* * subbuf_start() default callback. Does nothing. */ static int subbuf_start_default_callback (struct rchan_buf *buf, void *subbuf, void *prev_subbuf, size_t prev_padding) { if (relay_buf_full(buf)) return 0; return 1; } /* * buf_mapped() default callback. Does nothing. */ static void buf_mapped_default_callback(struct rchan_buf *buf, struct file *filp) { } /* * buf_unmapped() default callback. Does nothing. */ static void buf_unmapped_default_callback(struct rchan_buf *buf, struct file *filp) { } /* * create_buf_file_create() default callback. Does nothing. */ static struct dentry *create_buf_file_default_callback(const char *filename, struct dentry *parent, int mode, struct rchan_buf *buf, int *is_global) { return NULL; } /* * remove_buf_file() default callback. Does nothing. */ static int remove_buf_file_default_callback(struct dentry *dentry) { return -EINVAL; } /* relay channel default callbacks */ static struct rchan_callbacks default_channel_callbacks = { .subbuf_start = subbuf_start_default_callback, .buf_mapped = buf_mapped_default_callback, .buf_unmapped = buf_unmapped_default_callback, .create_buf_file = create_buf_file_default_callback, .remove_buf_file = remove_buf_file_default_callback, }; /** * wakeup_readers - wake up readers waiting on a channel * @data: contains the channel buffer * * This is the timer function used to defer reader waking. */ static void wakeup_readers(unsigned long data) { struct rchan_buf *buf = (struct rchan_buf *)data; wake_up_interruptible(&buf->read_wait); } /** * __relay_reset - reset a channel buffer * @buf: the channel buffer * @init: 1 if this is a first-time initialization * * See relay_reset() for description of effect. */ static void __relay_reset(struct rchan_buf *buf, unsigned int init) { size_t i; if (init) { init_waitqueue_head(&buf->read_wait); kref_init(&buf->kref); setup_timer(&buf->timer, wakeup_readers, (unsigned long)buf); } else del_timer_sync(&buf->timer); buf->subbufs_produced = 0; buf->subbufs_consumed = 0; buf->bytes_consumed = 0; buf->finalized = 0; buf->data = buf->start; buf->offset = 0; for (i = 0; i < buf->chan->n_subbufs; i++) buf->padding[i] = 0; buf->chan->cb->subbuf_start(buf, buf->data, NULL, 0); } /** * relay_reset - reset the channel * @chan: the channel * * This has the effect of erasing all data from all channel buffers * and restarting the channel in its initial state. The buffers * are not freed, so any mappings are still in effect. * * NOTE. Care should be taken that the channel isn't actually * being used by anything when this call is made. */ void relay_reset(struct rchan *chan) { unsigned int i; if (!chan) return; if (chan->is_global && chan->buf[0]) { __relay_reset(chan->buf[0], 0); return; } mutex_lock(&relay_channels_mutex); for_each_possible_cpu(i) if (chan->buf[i]) __relay_reset(chan->buf[i], 0); mutex_unlock(&relay_channels_mutex); } EXPORT_SYMBOL_GPL(relay_reset); static inline void relay_set_buf_dentry(struct rchan_buf *buf, struct dentry *dentry) { buf->dentry = dentry; buf->dentry->d_inode->i_size = buf->early_bytes; } static struct dentry *relay_create_buf_file(struct rchan *chan, struct rchan_buf *buf, unsigned int cpu) { struct dentry *dentry; char *tmpname; tmpname = kzalloc(NAME_MAX + 1, GFP_KERNEL); if (!tmpname) return NULL; snprintf(tmpname, NAME_MAX, "%s%d", chan->base_filename, cpu); /* Create file in fs */ dentry = chan->cb->create_buf_file(tmpname, chan->parent, S_IRUSR, buf, &chan->is_global); kfree(tmpname); return dentry; } /* * relay_open_buf - create a new relay channel buffer * * used by relay_open() and CPU hotplug. */ static struct rchan_buf *relay_open_buf(struct rchan *chan, unsigned int cpu) { struct rchan_buf *buf = NULL; struct dentry *dentry; if (chan->is_global) return chan->buf[0]; buf = relay_create_buf(chan); if (!buf) return NULL; if (chan->has_base_filename) { dentry = relay_create_buf_file(chan, buf, cpu); if (!dentry) goto free_buf; relay_set_buf_dentry(buf, dentry); } buf->cpu = cpu; __relay_reset(buf, 1); if(chan->is_global) { chan->buf[0] = buf; buf->cpu = 0; } return buf; free_buf: relay_destroy_buf(buf); return NULL; } /** * relay_close_buf - close a channel buffer * @buf: channel buffer * * Marks the buffer finalized and restores the default callbacks. * The channel buffer and channel buffer data structure are then freed * automatically when the last reference is given up. */ static void relay_close_buf(struct rchan_buf *buf) { buf->finalized = 1; del_timer_sync(&buf->timer); kref_put(&buf->kref, relay_remove_buf); } static void setup_callbacks(struct rchan *chan, struct rchan_callbacks *cb) { if (!cb) { chan->cb = &default_channel_callbacks; return; } if (!cb->subbuf_start) cb->subbuf_start = subbuf_start_default_callback; if (!cb->buf_mapped) cb->buf_mapped = buf_mapped_default_callback; if (!cb->buf_unmapped) cb->buf_unmapped = buf_unmapped_default_callback; if (!cb->create_buf_file) cb->create_buf_file = create_buf_file_default_callback; if (!cb->remove_buf_file) cb->remove_buf_file = remove_buf_file_default_callback; chan->cb = cb; } /** * relay_hotcpu_callback - CPU hotplug callback * @nb: notifier block * @action: hotplug action to take * @hcpu: CPU number * * Returns the success/failure of the operation. (%NOTIFY_OK, %NOTIFY_BAD) */ static int __cpuinit relay_hotcpu_callback(struct notifier_block *nb, unsigned long action, void *hcpu) { unsigned int hotcpu = (unsigned long)hcpu; struct rchan *chan; switch(action) { case CPU_UP_PREPARE: case CPU_UP_PREPARE_FROZEN: mutex_lock(&relay_channels_mutex); list_for_each_entry(chan, &relay_channels, list) { if (chan->buf[hotcpu]) continue; chan->buf[hotcpu] = relay_open_buf(chan, hotcpu); if(!chan->buf[hotcpu]) { printk(KERN_ERR "relay_hotcpu_callback: cpu %d buffer " "creation failed\n", hotcpu); mutex_unlock(&relay_channels_mutex); return NOTIFY_BAD; } } mutex_unlock(&relay_channels_mutex); break; case CPU_DEAD: case CPU_DEAD_FROZEN: /* No need to flush the cpu : will be flushed upon * final relay_flush() call. */ break; } return NOTIFY_OK; } /** * relay_open - create a new relay channel * @base_filename: base name of files to create, %NULL for buffering only * @parent: dentry of parent directory, %NULL for root directory or buffer * @subbuf_size: size of sub-buffers * @n_subbufs: number of sub-buffers * @cb: client callback functions * @private_data: user-defined data * * Returns channel pointer if successful, %NULL otherwise. * * Creates a channel buffer for each cpu using the sizes and * attributes specified. The created channel buffer files * will be named base_filename0...base_filenameN-1. File * permissions will be %S_IRUSR. */ struct rchan *relay_open(const char *base_filename, struct dentry *parent, size_t subbuf_size, size_t n_subbufs, struct rchan_callbacks *cb, void *private_data) { unsigned int i; struct rchan *chan; if (!(subbuf_size && n_subbufs)) return NULL; chan = kzalloc(sizeof(struct rchan), GFP_KERNEL); if (!chan) return NULL; chan->version = RELAYFS_CHANNEL_VERSION; chan->n_subbufs = n_subbufs; chan->subbuf_size = subbuf_size; chan->alloc_size = FIX_SIZE(subbuf_size * n_subbufs); chan->parent = parent; chan->private_data = private_data; if (base_filename) { chan->has_base_filename = 1; strlcpy(chan->base_filename, base_filename, NAME_MAX); } setup_callbacks(chan, cb); kref_init(&chan->kref); mutex_lock(&relay_channels_mutex); for_each_online_cpu(i) { chan->buf[i] = relay_open_buf(chan, i); if (!chan->buf[i]) goto free_bufs; } list_add(&chan->list, &relay_channels); mutex_unlock(&relay_channels_mutex); return chan; free_bufs: for_each_possible_cpu(i) { if (chan->buf[i]) relay_close_buf(chan->buf[i]); } kref_put(&chan->kref, relay_destroy_channel); mutex_unlock(&relay_channels_mutex); return NULL; } EXPORT_SYMBOL_GPL(relay_open); struct rchan_percpu_buf_dispatcher { struct rchan_buf *buf; struct dentry *dentry; }; /* Called in atomic context. */ static void __relay_set_buf_dentry(void *info) { struct rchan_percpu_buf_dispatcher *p = info; relay_set_buf_dentry(p->buf, p->dentry); } /** * relay_late_setup_files - triggers file creation * @chan: channel to operate on * @base_filename: base name of files to create * @parent: dentry of parent directory, %NULL for root directory * * Returns 0 if successful, non-zero otherwise. * * Use to setup files for a previously buffer-only channel. * Useful to do early tracing in kernel, before VFS is up, for example. */ int relay_late_setup_files(struct rchan *chan, const char *base_filename, struct dentry *parent) { int err = 0; unsigned int i, curr_cpu; unsigned long flags; struct dentry *dentry; struct rchan_percpu_buf_dispatcher disp; if (!chan || !base_filename) return -EINVAL; strlcpy(chan->base_filename, base_filename, NAME_MAX); mutex_lock(&relay_channels_mutex); /* Is chan already set up? */ if (unlikely(chan->has_base_filename)) { mutex_unlock(&relay_channels_mutex); return -EEXIST; } chan->has_base_filename = 1; chan->parent = parent; curr_cpu = get_cpu(); /* * The CPU hotplug notifier ran before us and created buffers with * no files associated. So it's safe to call relay_setup_buf_file() * on all currently online CPUs. */ for_each_online_cpu(i) { if (unlikely(!chan->buf[i])) { WARN_ONCE(1, KERN_ERR "CPU has no buffer!\n"); err = -EINVAL; break; } dentry = relay_create_buf_file(chan, chan->buf[i], i); if (unlikely(!dentry)) { err = -EINVAL; break; } if (curr_cpu == i) { local_irq_save(flags); relay_set_buf_dentry(chan->buf[i], dentry); local_irq_restore(flags); } else { disp.buf = chan->buf[i]; disp.dentry = dentry; smp_mb(); /* relay_channels_mutex must be held, so wait. */ err = smp_call_function_single(i, __relay_set_buf_dentry, &disp, 1); } if (unlikely(err)) break; } put_cpu(); mutex_unlock(&relay_channels_mutex); return err; } /** * relay_switch_subbuf - switch to a new sub-buffer * @buf: channel buffer * @length: size of current event * * Returns either the length passed in or 0 if full. * * Performs sub-buffer-switch tasks such as invoking callbacks, * updating padding counts, waking up readers, etc. */ size_t relay_switch_subbuf(struct rchan_buf *buf, size_t length) { void *old, *new; size_t old_subbuf, new_subbuf; if (unlikely(length > buf->chan->subbuf_size)) goto toobig; if (buf->offset != buf->chan->subbuf_size + 1) { buf->prev_padding = buf->chan->subbuf_size - buf->offset; old_subbuf = buf->subbufs_produced % buf->chan->n_subbufs; buf->padding[old_subbuf] = buf->prev_padding; buf->subbufs_produced++; if (buf->dentry) buf->dentry->d_inode->i_size += buf->chan->subbuf_size - buf->padding[old_subbuf]; else buf->early_bytes += buf->chan->subbuf_size - buf->padding[old_subbuf]; smp_mb(); if (waitqueue_active(&buf->read_wait)) /* * Calling wake_up_interruptible() from here * will deadlock if we happen to be logging * from the scheduler (trying to re-grab * rq->lock), so defer it. */ mod_timer(&buf->timer, jiffies + 1); } old = buf->data; new_subbuf = buf->subbufs_produced % buf->chan->n_subbufs; new = buf->start + new_subbuf * buf->chan->subbuf_size; buf->offset = 0; if (!buf->chan->cb->subbuf_start(buf, new, old, buf->prev_padding)) { buf->offset = buf->chan->subbuf_size + 1; return 0; } buf->data = new; buf->padding[new_subbuf] = 0; if (unlikely(length + buf->offset > buf->chan->subbuf_size)) goto toobig; return length; toobig: buf->chan->last_toobig = length; return 0; } EXPORT_SYMBOL_GPL(relay_switch_subbuf); /** * relay_subbufs_consumed - update the buffer's sub-buffers-consumed count * @chan: the channel * @cpu: the cpu associated with the channel buffer to update * @subbufs_consumed: number of sub-buffers to add to current buf's count * * Adds to the channel buffer's consumed sub-buffer count. * subbufs_consumed should be the number of sub-buffers newly consumed, * not the total consumed. * * NOTE. Kernel clients don't need to call this function if the channel * mode is 'overwrite'. */ void relay_subbufs_consumed(struct rchan *chan, unsigned int cpu, size_t subbufs_consumed) { struct rchan_buf *buf; if (!chan) return; if (cpu >= NR_CPUS || !chan->buf[cpu] || subbufs_consumed > chan->n_subbufs) return; buf = chan->buf[cpu]; if (subbufs_consumed > buf->subbufs_produced - buf->subbufs_consumed) buf->subbufs_consumed = buf->subbufs_produced; else buf->subbufs_consumed += subbufs_consumed; } EXPORT_SYMBOL_GPL(relay_subbufs_consumed); /** * relay_close - close the channel * @chan: the channel * * Closes all channel buffers and frees the channel. */ void relay_close(struct rchan *chan) { unsigned int i; if (!chan) return; mutex_lock(&relay_channels_mutex); if (chan->is_global && chan->buf[0]) relay_close_buf(chan->buf[0]); else for_each_possible_cpu(i) if (chan->buf[i]) relay_close_buf(chan->buf[i]); if (chan->last_toobig) printk(KERN_WARNING "relay: one or more items not logged " "[item size (%Zd) > sub-buffer size (%Zd)]\n", chan->last_toobig, chan->subbuf_size); list_del(&chan->list); kref_put(&chan->kref, relay_destroy_channel); mutex_unlock(&relay_channels_mutex); } EXPORT_SYMBOL_GPL(relay_close); /** * relay_flush - close the channel * @chan: the channel * * Flushes all channel buffers, i.e. forces buffer switch. */ void relay_flush(struct rchan *chan) { unsigned int i; if (!chan) return; if (chan->is_global && chan->buf[0]) { relay_switch_subbuf(chan->buf[0], 0); return; } mutex_lock(&relay_channels_mutex); for_each_possible_cpu(i) if (chan->buf[i]) relay_switch_subbuf(chan->buf[i], 0); mutex_unlock(&relay_channels_mutex); } EXPORT_SYMBOL_GPL(relay_flush); /** * relay_file_open - open file op for relay files * @inode: the inode * @filp: the file * * Increments the channel buffer refcount. */ static int relay_file_open(struct inode *inode, struct file *filp) { struct rchan_buf *buf = inode->i_private; kref_get(&buf->kref); filp->private_data = buf; return nonseekable_open(inode, filp); } /** * relay_file_mmap - mmap file op for relay files * @filp: the file * @vma: the vma describing what to map * * Calls upon relay_mmap_buf() to map the file into user space. */ static int relay_file_mmap(struct file *filp, struct vm_area_struct *vma) { struct rchan_buf *buf = filp->private_data; return relay_mmap_buf(buf, vma); } /** * relay_file_poll - poll file op for relay files * @filp: the file * @wait: poll table * * Poll implemention. */ static unsigned int relay_file_poll(struct file *filp, poll_table *wait) { unsigned int mask = 0; struct rchan_buf *buf = filp->private_data; if (buf->finalized) return POLLERR; if (filp->f_mode & FMODE_READ) { poll_wait(filp, &buf->read_wait, wait); if (!relay_buf_empty(buf)) mask |= POLLIN | POLLRDNORM; } return mask; } /** * relay_file_release - release file op for relay files * @inode: the inode * @filp: the file * * Decrements the channel refcount, as the filesystem is * no longer using it. */ static int relay_file_release(struct inode *inode, struct file *filp) { struct rchan_buf *buf = filp->private_data; kref_put(&buf->kref, relay_remove_buf); return 0; } /* * relay_file_read_consume - update the consumed count for the buffer */ static void relay_file_read_consume(struct rchan_buf *buf, size_t read_pos, size_t bytes_consumed) { size_t subbuf_size = buf->chan->subbuf_size; size_t n_subbufs = buf->chan->n_subbufs; size_t read_subbuf; if (buf->subbufs_produced == buf->subbufs_consumed && buf->offset == buf->bytes_consumed) return; if (buf->bytes_consumed + bytes_consumed > subbuf_size) { relay_subbufs_consumed(buf->chan, buf->cpu, 1); buf->bytes_consumed = 0; } buf->bytes_consumed += bytes_consumed; if (!read_pos) read_subbuf = buf->subbufs_consumed % n_subbufs; else read_subbuf = read_pos / buf->chan->subbuf_size; if (buf->bytes_consumed + buf->padding[read_subbuf] == subbuf_size) { if ((read_subbuf == buf->subbufs_produced % n_subbufs) && (buf->offset == subbuf_size)) return; relay_subbufs_consumed(buf->chan, buf->cpu, 1); buf->bytes_consumed = 0; } } /* * relay_file_read_avail - boolean, are there unconsumed bytes available? */ static int relay_file_read_avail(struct rchan_buf *buf, size_t read_pos) { size_t subbuf_size = buf->chan->subbuf_size; size_t n_subbufs = buf->chan->n_subbufs; size_t produced = buf->subbufs_produced; size_t consumed = buf->subbufs_consumed; relay_file_read_consume(buf, read_pos, 0); consumed = buf->subbufs_consumed; if (unlikely(buf->offset > subbuf_size)) { if (produced == consumed) return 0; return 1; } if (unlikely(produced - consumed >= n_subbufs)) { consumed = produced - n_subbufs + 1; buf->subbufs_consumed = consumed; buf->bytes_consumed = 0; } produced = (produced % n_subbufs) * subbuf_size + buf->offset; consumed = (consumed % n_subbufs) * subbuf_size + buf->bytes_consumed; if (consumed > produced) produced += n_subbufs * subbuf_size; if (consumed == produced) { if (buf->offset == subbuf_size && buf->subbufs_produced > buf->subbufs_consumed) return 1; return 0; } return 1; } /** * relay_file_read_subbuf_avail - return bytes available in sub-buffer * @read_pos: file read position * @buf: relay channel buffer */ static size_t relay_file_read_subbuf_avail(size_t read_pos, struct rchan_buf *buf) { size_t padding, avail = 0; size_t read_subbuf, read_offset, write_subbuf, write_offset; size_t subbuf_size = buf->chan->subbuf_size; write_subbuf = (buf->data - buf->start) / subbuf_size; write_offset = buf->offset > subbuf_size ? subbuf_size : buf->offset; read_subbuf = read_pos / subbuf_size; read_offset = read_pos % subbuf_size; padding = buf->padding[read_subbuf]; if (read_subbuf == write_subbuf) { if (read_offset + padding < write_offset) avail = write_offset - (read_offset + padding); } else avail = (subbuf_size - padding) - read_offset; return avail; } /** * relay_file_read_start_pos - find the first available byte to read * @read_pos: file read position * @buf: relay channel buffer * * If the @read_pos is in the middle of padding, return the * position of the first actually available byte, otherwise * return the original value. */ static size_t relay_file_read_start_pos(size_t read_pos, struct rchan_buf *buf) { size_t read_subbuf, padding, padding_start, padding_end; size_t subbuf_size = buf->chan->subbuf_size; size_t n_subbufs = buf->chan->n_subbufs; size_t consumed = buf->subbufs_consumed % n_subbufs; if (!read_pos) read_pos = consumed * subbuf_size + buf->bytes_consumed; read_subbuf = read_pos / subbuf_size; padding = buf->padding[read_subbuf]; padding_start = (read_subbuf + 1) * subbuf_size - padding; padding_end = (read_subbuf + 1) * subbuf_size; if (read_pos >= padding_start && read_pos < padding_end) { read_subbuf = (read_subbuf + 1) % n_subbufs; read_pos = read_subbuf * subbuf_size; } return read_pos; } /** * relay_file_read_end_pos - return the new read position * @read_pos: file read position * @buf: relay channel buffer * @count: number of bytes to be read */ static size_t relay_file_read_end_pos(struct rchan_buf *buf, size_t read_pos, size_t count) { size_t read_subbuf, padding, end_pos; size_t subbuf_size = buf->chan->subbuf_size; size_t n_subbufs = buf->chan->n_subbufs; read_subbuf = read_pos / subbuf_size; padding = buf->padding[read_subbuf]; if (read_pos % subbuf_size + count + padding == subbuf_size) end_pos = (read_subbuf + 1) * subbuf_size; else end_pos = read_pos + count; if (end_pos >= subbuf_size * n_subbufs) end_pos = 0; return end_pos; } /* * subbuf_read_actor - read up to one subbuf's worth of data */ static int subbuf_read_actor(size_t read_start, struct rchan_buf *buf, size_t avail, read_descriptor_t *desc, read_actor_t actor) { void *from; int ret = 0; from = buf->start + read_start; ret = avail; if (copy_to_user(desc->arg.buf, from, avail)) { desc->error = -EFAULT; ret = 0; } desc->arg.data += ret; desc->written += ret; desc->count -= ret; return ret; } typedef int (*subbuf_actor_t) (size_t read_start, struct rchan_buf *buf, size_t avail, read_descriptor_t *desc, read_actor_t actor); /* * relay_file_read_subbufs - read count bytes, bridging subbuf boundaries */ static ssize_t relay_file_read_subbufs(struct file *filp, loff_t *ppos, subbuf_actor_t subbuf_actor, read_actor_t actor, read_descriptor_t *desc) { struct rchan_buf *buf = filp->private_data; size_t read_start, avail; int ret; if (!desc->count) return 0; mutex_lock(&filp->f_path.dentry->d_inode->i_mutex); do { if (!relay_file_read_avail(buf, *ppos)) break; read_start = relay_file_read_start_pos(*ppos, buf); avail = relay_file_read_subbuf_avail(read_start, buf); if (!avail) break; avail = min(desc->count, avail); ret = subbuf_actor(read_start, buf, avail, desc, actor); if (desc->error < 0) break; if (ret) { relay_file_read_consume(buf, read_start, ret); *ppos = relay_file_read_end_pos(buf, read_start, ret); } } while (desc->count && ret); mutex_unlock(&filp->f_path.dentry->d_inode->i_mutex); return desc->written; } static ssize_t relay_file_read(struct file *filp, char __user *buffer, size_t count, loff_t *ppos) { read_descriptor_t desc; desc.written = 0; desc.count = count; desc.arg.buf = buffer; desc.error = 0; return relay_file_read_subbufs(filp, ppos, subbuf_read_actor, NULL, &desc); } static void relay_consume_bytes(struct rchan_buf *rbuf, int bytes_consumed) { rbuf->bytes_consumed += bytes_consumed; if (rbuf->bytes_consumed >= rbuf->chan->subbuf_size) { relay_subbufs_consumed(rbuf->chan, rbuf->cpu, 1); rbuf->bytes_consumed %= rbuf->chan->subbuf_size; } } static void relay_pipe_buf_release(struct pipe_inode_info *pipe, struct pipe_buffer *buf) { struct rchan_buf *rbuf; rbuf = (struct rchan_buf *)page_private(buf->page); relay_consume_bytes(rbuf, buf->private); } static struct pipe_buf_operations relay_pipe_buf_ops = { .can_merge = 0, .map = generic_pipe_buf_map, .unmap = generic_pipe_buf_unmap, .confirm = generic_pipe_buf_confirm, .release = relay_pipe_buf_release, .steal = generic_pipe_buf_steal, .get = generic_pipe_buf_get, }; static void relay_page_release(struct splice_pipe_desc *spd, unsigned int i) { } /* * subbuf_splice_actor - splice up to one subbuf's worth of data */ static int subbuf_splice_actor(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags, int *nonpad_ret) { unsigned int pidx, poff, total_len, subbuf_pages, nr_pages, ret; struct rchan_buf *rbuf = in->private_data; unsigned int subbuf_size = rbuf->chan->subbuf_size; uint64_t pos = (uint64_t) *ppos; uint32_t alloc_size = (uint32_t) rbuf->chan->alloc_size; size_t read_start = (size_t) do_div(pos, alloc_size); size_t read_subbuf = read_start / subbuf_size; size_t padding = rbuf->padding[read_subbuf]; size_t nonpad_end = read_subbuf * subbuf_size + subbuf_size - padding; struct page *pages[PIPE_BUFFERS]; struct partial_page partial[PIPE_BUFFERS]; struct splice_pipe_desc spd = { .pages = pages, .nr_pages = 0, .partial = partial, .flags = flags, .ops = &relay_pipe_buf_ops, .spd_release = relay_page_release, }; if (rbuf->subbufs_produced == rbuf->subbufs_consumed) return 0; /* * Adjust read len, if longer than what is available */ if (len > (subbuf_size - read_start % subbuf_size)) len = subbuf_size - read_start % subbuf_size; subbuf_pages = rbuf->chan->alloc_size >> PAGE_SHIFT; pidx = (read_start / PAGE_SIZE) % subbuf_pages; poff = read_start & ~PAGE_MASK; nr_pages = min_t(unsigned int, subbuf_pages, PIPE_BUFFERS); for (total_len = 0; spd.nr_pages < nr_pages; spd.nr_pages++) { unsigned int this_len, this_end, private; unsigned int cur_pos = read_start + total_len; if (!len) break; this_len = min_t(unsigned long, len, PAGE_SIZE - poff); private = this_len; spd.pages[spd.nr_pages] = rbuf->page_array[pidx]; spd.partial[spd.nr_pages].offset = poff; this_end = cur_pos + this_len; if (this_end >= nonpad_end) { this_len = nonpad_end - cur_pos; private = this_len + padding; } spd.partial[spd.nr_pages].len = this_len; spd.partial[spd.nr_pages].private = private; len -= this_len; total_len += this_len; poff = 0; pidx = (pidx + 1) % subbuf_pages; if (this_end >= nonpad_end) { spd.nr_pages++; break; } } if (!spd.nr_pages) return 0; ret = *nonpad_ret = splice_to_pipe(pipe, &spd); if (ret < 0 || ret < total_len) return ret; if (read_start + ret == nonpad_end) ret += padding; return ret; } static ssize_t relay_file_splice_read(struct file *in, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { ssize_t spliced; int ret; int nonpad_ret = 0; ret = 0; spliced = 0; while (len && !spliced) { ret = subbuf_splice_actor(in, ppos, pipe, len, flags, &nonpad_ret); if (ret < 0) break; else if (!ret) { if (flags & SPLICE_F_NONBLOCK) ret = -EAGAIN; break; } *ppos += ret; if (ret > len) len = 0; else len -= ret; spliced += nonpad_ret; nonpad_ret = 0; } if (spliced) return spliced; return ret; } const struct file_operations relay_file_operations = { .open = relay_file_open, .poll = relay_file_poll, .mmap = relay_file_mmap, .read = relay_file_read, .llseek = no_llseek, .release = relay_file_release, .splice_read = relay_file_splice_read, }; EXPORT_SYMBOL_GPL(relay_file_operations); static __init int relay_init(void) { hotcpu_notifier(relay_hotcpu_callback, 0); return 0; } early_initcall(relay_init);
/* * dvb_frontend.c: DVB frontend tuning interface/thread * * * Copyright (C) 1999-2001 Ralph Metzler * Marcus Metzler * Holger Waechtler * for convergence integrated media GmbH * * Copyright (C) 2004 Andrew de Quincey (tuning thread cleanup) * * 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. * * 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. * Or, point your browser to http://www.gnu.org/copyleft/gpl.html */ /* Enables DVBv3 compatibility bits at the headers */ #define __DVB_CORE__ #include <linux/string.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/wait.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/semaphore.h> #include <linux/module.h> #include <linux/list.h> #include <linux/freezer.h> #include <linux/jiffies.h> #include <linux/kthread.h> #include <linux/ktime.h> #include <asm/processor.h> #include "dvb_frontend.h" #include "dvbdev.h" #include <linux/dvb/version.h> static int dvb_frontend_debug; static int dvb_shutdown_timeout; static int dvb_force_auto_inversion; static int dvb_override_tune_delay; static int dvb_powerdown_on_sleep = 1; static int dvb_mfe_wait_time = 5; module_param_named(frontend_debug, dvb_frontend_debug, int, 0644); MODULE_PARM_DESC(frontend_debug, "Turn on/off frontend core debugging (default:off)."); module_param(dvb_shutdown_timeout, int, 0644); MODULE_PARM_DESC(dvb_shutdown_timeout, "wait <shutdown_timeout> seconds after close() before suspending hardware"); module_param(dvb_force_auto_inversion, int, 0644); MODULE_PARM_DESC(dvb_force_auto_inversion, "0: normal (default), 1: INVERSION_AUTO forced always"); module_param(dvb_override_tune_delay, int, 0644); MODULE_PARM_DESC(dvb_override_tune_delay, "0: normal (default), >0 => delay in milliseconds to wait for lock after a tune attempt"); module_param(dvb_powerdown_on_sleep, int, 0644); MODULE_PARM_DESC(dvb_powerdown_on_sleep, "0: do not power down, 1: turn LNB voltage off on sleep (default)"); module_param(dvb_mfe_wait_time, int, 0644); MODULE_PARM_DESC(dvb_mfe_wait_time, "Wait up to <mfe_wait_time> seconds on open() for multi-frontend to become available (default:5 seconds)"); #define FESTATE_IDLE 1 #define FESTATE_RETUNE 2 #define FESTATE_TUNING_FAST 4 #define FESTATE_TUNING_SLOW 8 #define FESTATE_TUNED 16 #define FESTATE_ZIGZAG_FAST 32 #define FESTATE_ZIGZAG_SLOW 64 #define FESTATE_DISEQC 128 #define FESTATE_ERROR 256 #define FESTATE_WAITFORLOCK (FESTATE_TUNING_FAST | FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW | FESTATE_DISEQC) #define FESTATE_SEARCHING_FAST (FESTATE_TUNING_FAST | FESTATE_ZIGZAG_FAST) #define FESTATE_SEARCHING_SLOW (FESTATE_TUNING_SLOW | FESTATE_ZIGZAG_SLOW) #define FESTATE_LOSTLOCK (FESTATE_ZIGZAG_FAST | FESTATE_ZIGZAG_SLOW) /* * FESTATE_IDLE. No tuning parameters have been supplied and the loop is idling. * FESTATE_RETUNE. Parameters have been supplied, but we have not yet performed the first tune. * FESTATE_TUNING_FAST. Tuning parameters have been supplied and fast zigzag scan is in progress. * FESTATE_TUNING_SLOW. Tuning parameters have been supplied. Fast zigzag failed, so we're trying again, but slower. * FESTATE_TUNED. The frontend has successfully locked on. * FESTATE_ZIGZAG_FAST. The lock has been lost, and a fast zigzag has been initiated to try and regain it. * FESTATE_ZIGZAG_SLOW. The lock has been lost. Fast zigzag has been failed, so we're trying again, but slower. * FESTATE_DISEQC. A DISEQC command has just been issued. * FESTATE_WAITFORLOCK. When we're waiting for a lock. * FESTATE_SEARCHING_FAST. When we're searching for a signal using a fast zigzag scan. * FESTATE_SEARCHING_SLOW. When we're searching for a signal using a slow zigzag scan. * FESTATE_LOSTLOCK. When the lock has been lost, and we're searching it again. */ static DEFINE_MUTEX(frontend_mutex); struct dvb_frontend_private { struct kref refcount; /* thread/frontend values */ struct dvb_device *dvbdev; struct dvb_frontend_parameters parameters_out; struct dvb_fe_events events; struct semaphore sem; struct list_head list_head; wait_queue_head_t wait_queue; struct task_struct *thread; unsigned long release_jiffies; unsigned int wakeup; enum fe_status status; unsigned long tune_mode_flags; unsigned int delay; unsigned int reinitialise; int tone; int voltage; /* swzigzag values */ unsigned int state; unsigned int bending; int lnb_drift; unsigned int inversion; unsigned int auto_step; unsigned int auto_sub_step; unsigned int started_auto_step; unsigned int min_delay; unsigned int max_drift; unsigned int step_size; int quality; unsigned int check_wrapped; enum dvbfe_search algo_status; #if defined(CONFIG_MEDIA_CONTROLLER_DVB) struct media_pipeline pipe; #endif }; static void dvb_frontend_private_free(struct kref *ref) { struct dvb_frontend_private *fepriv = container_of(ref, struct dvb_frontend_private, refcount); kfree(fepriv); } static void dvb_frontend_private_put(struct dvb_frontend_private *fepriv) { kref_put(&fepriv->refcount, dvb_frontend_private_free); } static void dvb_frontend_private_get(struct dvb_frontend_private *fepriv) { kref_get(&fepriv->refcount); } static void dvb_frontend_wakeup(struct dvb_frontend *fe); static int dtv_get_frontend(struct dvb_frontend *fe, struct dtv_frontend_properties *c, struct dvb_frontend_parameters *p_out); static int dtv_property_legacy_params_sync(struct dvb_frontend *fe, const struct dtv_frontend_properties *c, struct dvb_frontend_parameters *p); static bool has_get_frontend(struct dvb_frontend *fe) { return fe->ops.get_frontend != NULL; } /* * Due to DVBv3 API calls, a delivery system should be mapped into one of * the 4 DVBv3 delivery systems (FE_QPSK, FE_QAM, FE_OFDM or FE_ATSC), * otherwise, a DVBv3 call will fail. */ enum dvbv3_emulation_type { DVBV3_UNKNOWN, DVBV3_QPSK, DVBV3_QAM, DVBV3_OFDM, DVBV3_ATSC, }; static enum dvbv3_emulation_type dvbv3_type(u32 delivery_system) { switch (delivery_system) { case SYS_DVBC_ANNEX_A: case SYS_DVBC_ANNEX_C: return DVBV3_QAM; case SYS_DVBS: case SYS_DVBS2: case SYS_TURBO: case SYS_ISDBS: case SYS_DSS: return DVBV3_QPSK; case SYS_DVBT: case SYS_DVBT2: case SYS_ISDBT: case SYS_DTMB: return DVBV3_OFDM; case SYS_ATSC: case SYS_ATSCMH: case SYS_DVBC_ANNEX_B: return DVBV3_ATSC; case SYS_UNDEFINED: case SYS_ISDBC: case SYS_DVBH: case SYS_DAB: default: /* * Doesn't know how to emulate those types and/or * there's no frontend driver from this type yet * with some emulation code, so, we're not sure yet how * to handle them, or they're not compatible with a DVBv3 call. */ return DVBV3_UNKNOWN; } } static void dvb_frontend_add_event(struct dvb_frontend *fe, enum fe_status status) { struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct dvb_fe_events *events = &fepriv->events; struct dvb_frontend_event *e; int wp; dev_dbg(fe->dvb->device, "%s:\n", __func__); if ((status & FE_HAS_LOCK) && has_get_frontend(fe)) dtv_get_frontend(fe, c, &fepriv->parameters_out); mutex_lock(&events->mtx); wp = (events->eventw + 1) % MAX_EVENT; if (wp == events->eventr) { events->overflow = 1; events->eventr = (events->eventr + 1) % MAX_EVENT; } e = &events->events[events->eventw]; e->status = status; e->parameters = fepriv->parameters_out; events->eventw = wp; mutex_unlock(&events->mtx); wake_up_interruptible (&events->wait_queue); } static int dvb_frontend_get_event(struct dvb_frontend *fe, struct dvb_frontend_event *event, int flags) { struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dvb_fe_events *events = &fepriv->events; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (events->overflow) { events->overflow = 0; return -EOVERFLOW; } if (events->eventw == events->eventr) { int ret; if (flags & O_NONBLOCK) return -EWOULDBLOCK; up(&fepriv->sem); ret = wait_event_interruptible (events->wait_queue, events->eventw != events->eventr); if (down_interruptible (&fepriv->sem)) return -ERESTARTSYS; if (ret < 0) return ret; } mutex_lock(&events->mtx); *event = events->events[events->eventr]; events->eventr = (events->eventr + 1) % MAX_EVENT; mutex_unlock(&events->mtx); return 0; } static void dvb_frontend_clear_events(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dvb_fe_events *events = &fepriv->events; mutex_lock(&events->mtx); events->eventr = events->eventw; mutex_unlock(&events->mtx); } static void dvb_frontend_init(struct dvb_frontend *fe) { dev_dbg(fe->dvb->device, "%s: initialising adapter %i frontend %i (%s)...\n", __func__, fe->dvb->num, fe->id, fe->ops.info.name); if (fe->ops.init) fe->ops.init(fe); if (fe->ops.tuner_ops.init) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.init(fe); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } } void dvb_frontend_reinitialise(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; fepriv->reinitialise = 1; dvb_frontend_wakeup(fe); } EXPORT_SYMBOL(dvb_frontend_reinitialise); static void dvb_frontend_swzigzag_update_delay(struct dvb_frontend_private *fepriv, int locked) { int q2; struct dvb_frontend *fe = fepriv->dvbdev->priv; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (locked) (fepriv->quality) = (fepriv->quality * 220 + 36*256) / 256; else (fepriv->quality) = (fepriv->quality * 220 + 0) / 256; q2 = fepriv->quality - 128; q2 *= q2; fepriv->delay = fepriv->min_delay + q2 * HZ / (128*128); } /** * Performs automatic twiddling of frontend parameters. * * @param fe The frontend concerned. * @param check_wrapped Checks if an iteration has completed. DO NOT SET ON THE FIRST ATTEMPT * @returns Number of complete iterations that have been performed. */ static int dvb_frontend_swzigzag_autotune(struct dvb_frontend *fe, int check_wrapped) { int autoinversion; int ready = 0; int fe_set_err = 0; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache, tmp; int original_inversion = c->inversion; u32 original_frequency = c->frequency; /* are we using autoinversion? */ autoinversion = ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) && (c->inversion == INVERSION_AUTO)); /* setup parameters correctly */ while(!ready) { /* calculate the lnb_drift */ fepriv->lnb_drift = fepriv->auto_step * fepriv->step_size; /* wrap the auto_step if we've exceeded the maximum drift */ if (fepriv->lnb_drift > fepriv->max_drift) { fepriv->auto_step = 0; fepriv->auto_sub_step = 0; fepriv->lnb_drift = 0; } /* perform inversion and +/- zigzag */ switch(fepriv->auto_sub_step) { case 0: /* try with the current inversion and current drift setting */ ready = 1; break; case 1: if (!autoinversion) break; fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF; ready = 1; break; case 2: if (fepriv->lnb_drift == 0) break; fepriv->lnb_drift = -fepriv->lnb_drift; ready = 1; break; case 3: if (fepriv->lnb_drift == 0) break; if (!autoinversion) break; fepriv->inversion = (fepriv->inversion == INVERSION_OFF) ? INVERSION_ON : INVERSION_OFF; fepriv->lnb_drift = -fepriv->lnb_drift; ready = 1; break; default: fepriv->auto_step++; fepriv->auto_sub_step = -1; /* it'll be incremented to 0 in a moment */ break; } if (!ready) fepriv->auto_sub_step++; } /* if this attempt would hit where we started, indicate a complete * iteration has occurred */ if ((fepriv->auto_step == fepriv->started_auto_step) && (fepriv->auto_sub_step == 0) && check_wrapped) { return 1; } dev_dbg(fe->dvb->device, "%s: drift:%i inversion:%i auto_step:%i " \ "auto_sub_step:%i started_auto_step:%i\n", __func__, fepriv->lnb_drift, fepriv->inversion, fepriv->auto_step, fepriv->auto_sub_step, fepriv->started_auto_step); /* set the frontend itself */ c->frequency += fepriv->lnb_drift; if (autoinversion) c->inversion = fepriv->inversion; tmp = *c; if (fe->ops.set_frontend) fe_set_err = fe->ops.set_frontend(fe); *c = tmp; if (fe_set_err < 0) { fepriv->state = FESTATE_ERROR; return fe_set_err; } c->frequency = original_frequency; c->inversion = original_inversion; fepriv->auto_sub_step++; return 0; } static void dvb_frontend_swzigzag(struct dvb_frontend *fe) { enum fe_status s = 0; int retval = 0; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache, tmp; /* if we've got no parameters, just keep idling */ if (fepriv->state & FESTATE_IDLE) { fepriv->delay = 3*HZ; fepriv->quality = 0; return; } /* in SCAN mode, we just set the frontend when asked and leave it alone */ if (fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT) { if (fepriv->state & FESTATE_RETUNE) { tmp = *c; if (fe->ops.set_frontend) retval = fe->ops.set_frontend(fe); *c = tmp; if (retval < 0) fepriv->state = FESTATE_ERROR; else fepriv->state = FESTATE_TUNED; } fepriv->delay = 3*HZ; fepriv->quality = 0; return; } /* get the frontend status */ if (fepriv->state & FESTATE_RETUNE) { s = 0; } else { if (fe->ops.read_status) fe->ops.read_status(fe, &s); if (s != fepriv->status) { dvb_frontend_add_event(fe, s); fepriv->status = s; } } /* if we're not tuned, and we have a lock, move to the TUNED state */ if ((fepriv->state & FESTATE_WAITFORLOCK) && (s & FE_HAS_LOCK)) { dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK); fepriv->state = FESTATE_TUNED; /* if we're tuned, then we have determined the correct inversion */ if ((!(fe->ops.info.caps & FE_CAN_INVERSION_AUTO)) && (c->inversion == INVERSION_AUTO)) { c->inversion = fepriv->inversion; } return; } /* if we are tuned already, check we're still locked */ if (fepriv->state & FESTATE_TUNED) { dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK); /* we're tuned, and the lock is still good... */ if (s & FE_HAS_LOCK) { return; } else { /* if we _WERE_ tuned, but now don't have a lock */ fepriv->state = FESTATE_ZIGZAG_FAST; fepriv->started_auto_step = fepriv->auto_step; fepriv->check_wrapped = 0; } } /* don't actually do anything if we're in the LOSTLOCK state, * the frontend is set to FE_CAN_RECOVER, and the max_drift is 0 */ if ((fepriv->state & FESTATE_LOSTLOCK) && (fe->ops.info.caps & FE_CAN_RECOVER) && (fepriv->max_drift == 0)) { dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK); return; } /* don't do anything if we're in the DISEQC state, since this * might be someone with a motorized dish controlled by DISEQC. * If its actually a re-tune, there will be a SET_FRONTEND soon enough. */ if (fepriv->state & FESTATE_DISEQC) { dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK); return; } /* if we're in the RETUNE state, set everything up for a brand * new scan, keeping the current inversion setting, as the next * tune is _very_ likely to require the same */ if (fepriv->state & FESTATE_RETUNE) { fepriv->lnb_drift = 0; fepriv->auto_step = 0; fepriv->auto_sub_step = 0; fepriv->started_auto_step = 0; fepriv->check_wrapped = 0; } /* fast zigzag. */ if ((fepriv->state & FESTATE_SEARCHING_FAST) || (fepriv->state & FESTATE_RETUNE)) { fepriv->delay = fepriv->min_delay; /* perform a tune */ retval = dvb_frontend_swzigzag_autotune(fe, fepriv->check_wrapped); if (retval < 0) { return; } else if (retval) { /* OK, if we've run out of trials at the fast speed. * Drop back to slow for the _next_ attempt */ fepriv->state = FESTATE_SEARCHING_SLOW; fepriv->started_auto_step = fepriv->auto_step; return; } fepriv->check_wrapped = 1; /* if we've just retuned, enter the ZIGZAG_FAST state. * This ensures we cannot return from an * FE_SET_FRONTEND ioctl before the first frontend tune * occurs */ if (fepriv->state & FESTATE_RETUNE) { fepriv->state = FESTATE_TUNING_FAST; } } /* slow zigzag */ if (fepriv->state & FESTATE_SEARCHING_SLOW) { dvb_frontend_swzigzag_update_delay(fepriv, s & FE_HAS_LOCK); /* Note: don't bother checking for wrapping; we stay in this * state until we get a lock */ dvb_frontend_swzigzag_autotune(fe, 0); } } static int dvb_frontend_is_exiting(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; if (fe->exit != DVB_FE_NO_EXIT) return 1; if (fepriv->dvbdev->writers == 1) if (time_after_eq(jiffies, fepriv->release_jiffies + dvb_shutdown_timeout * HZ)) return 1; return 0; } static int dvb_frontend_should_wakeup(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; if (fepriv->wakeup) { fepriv->wakeup = 0; return 1; } return dvb_frontend_is_exiting(fe); } static void dvb_frontend_wakeup(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; fepriv->wakeup = 1; wake_up_interruptible(&fepriv->wait_queue); } static int dvb_frontend_thread(void *data) { struct dvb_frontend *fe = data; struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct dvb_frontend_private *fepriv = fe->frontend_priv; enum fe_status s; enum dvbfe_algo algo; bool re_tune = false; bool semheld = false; dev_dbg(fe->dvb->device, "%s:\n", __func__); fepriv->check_wrapped = 0; fepriv->quality = 0; fepriv->delay = 3*HZ; fepriv->status = 0; fepriv->wakeup = 0; fepriv->reinitialise = 0; dvb_frontend_init(fe); set_freezable(); while (1) { up(&fepriv->sem); /* is locked when we enter the thread... */ restart: wait_event_interruptible_timeout(fepriv->wait_queue, dvb_frontend_should_wakeup(fe) || kthread_should_stop() || freezing(current), fepriv->delay); if (kthread_should_stop() || dvb_frontend_is_exiting(fe)) { /* got signal or quitting */ if (!down_interruptible(&fepriv->sem)) semheld = true; fe->exit = DVB_FE_NORMAL_EXIT; break; } if (try_to_freeze()) goto restart; if (down_interruptible(&fepriv->sem)) break; if (fepriv->reinitialise) { dvb_frontend_init(fe); if (fe->ops.set_tone && fepriv->tone != -1) fe->ops.set_tone(fe, fepriv->tone); if (fe->ops.set_voltage && fepriv->voltage != -1) fe->ops.set_voltage(fe, fepriv->voltage); fepriv->reinitialise = 0; } /* do an iteration of the tuning loop */ if (fe->ops.get_frontend_algo) { algo = fe->ops.get_frontend_algo(fe); switch (algo) { case DVBFE_ALGO_HW: dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_HW\n", __func__); if (fepriv->state & FESTATE_RETUNE) { dev_dbg(fe->dvb->device, "%s: Retune requested, FESTATE_RETUNE\n", __func__); re_tune = true; fepriv->state = FESTATE_TUNED; } else { re_tune = false; } if (fe->ops.tune) fe->ops.tune(fe, re_tune, fepriv->tune_mode_flags, &fepriv->delay, &s); if (s != fepriv->status && !(fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT)) { dev_dbg(fe->dvb->device, "%s: state changed, adding current state\n", __func__); dvb_frontend_add_event(fe, s); fepriv->status = s; } break; case DVBFE_ALGO_SW: dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_SW\n", __func__); dvb_frontend_swzigzag(fe); break; case DVBFE_ALGO_CUSTOM: dev_dbg(fe->dvb->device, "%s: Frontend ALGO = DVBFE_ALGO_CUSTOM, state=%d\n", __func__, fepriv->state); if (fepriv->state & FESTATE_RETUNE) { dev_dbg(fe->dvb->device, "%s: Retune requested, FESTAT_RETUNE\n", __func__); fepriv->state = FESTATE_TUNED; } /* Case where we are going to search for a carrier * User asked us to retune again for some reason, possibly * requesting a search with a new set of parameters */ if (fepriv->algo_status & DVBFE_ALGO_SEARCH_AGAIN) { if (fe->ops.search) { fepriv->algo_status = fe->ops.search(fe); /* We did do a search as was requested, the flags are * now unset as well and has the flags wrt to search. */ } else { fepriv->algo_status &= ~DVBFE_ALGO_SEARCH_AGAIN; } } /* Track the carrier if the search was successful */ if (fepriv->algo_status != DVBFE_ALGO_SEARCH_SUCCESS) { fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN; fepriv->delay = HZ / 2; } dtv_property_legacy_params_sync(fe, c, &fepriv->parameters_out); fe->ops.read_status(fe, &s); if (s != fepriv->status) { dvb_frontend_add_event(fe, s); /* update event list */ fepriv->status = s; if (!(s & FE_HAS_LOCK)) { fepriv->delay = HZ / 10; fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN; } else { fepriv->delay = 60 * HZ; } } break; default: dev_dbg(fe->dvb->device, "%s: UNDEFINED ALGO !\n", __func__); break; } } else { dvb_frontend_swzigzag(fe); } } if (dvb_powerdown_on_sleep) { if (fe->ops.set_voltage) fe->ops.set_voltage(fe, SEC_VOLTAGE_OFF); if (fe->ops.tuner_ops.sleep) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.sleep(fe); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } if (fe->ops.sleep) fe->ops.sleep(fe); } fepriv->thread = NULL; if (kthread_should_stop()) fe->exit = DVB_FE_DEVICE_REMOVED; else fe->exit = DVB_FE_NO_EXIT; mb(); if (semheld) up(&fepriv->sem); dvb_frontend_wakeup(fe); return 0; } static void dvb_frontend_stop(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (fe->exit != DVB_FE_DEVICE_REMOVED) fe->exit = DVB_FE_NORMAL_EXIT; mb(); if (!fepriv->thread) return; kthread_stop(fepriv->thread); sema_init(&fepriv->sem, 1); fepriv->state = FESTATE_IDLE; /* paranoia check in case a signal arrived */ if (fepriv->thread) dev_warn(fe->dvb->device, "dvb_frontend_stop: warning: thread %p won't exit\n", fepriv->thread); } /* * Sleep for the amount of time given by add_usec parameter * * This needs to be as precise as possible, as it affects the detection of * the dish tone command at the satellite subsystem. The precision is improved * by using a scheduled msleep followed by udelay for the remainder. */ void dvb_frontend_sleep_until(ktime_t *waketime, u32 add_usec) { s32 delta; *waketime = ktime_add_us(*waketime, add_usec); delta = ktime_us_delta(ktime_get_boottime(), *waketime); if (delta > 2500) { msleep((delta - 1500) / 1000); delta = ktime_us_delta(ktime_get_boottime(), *waketime); } if (delta > 0) udelay(delta); } EXPORT_SYMBOL(dvb_frontend_sleep_until); static int dvb_frontend_start(struct dvb_frontend *fe) { int ret; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct task_struct *fe_thread; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (fepriv->thread) { if (fe->exit == DVB_FE_NO_EXIT) return 0; else dvb_frontend_stop (fe); } if (signal_pending(current)) return -EINTR; if (down_interruptible (&fepriv->sem)) return -EINTR; fepriv->state = FESTATE_IDLE; fe->exit = DVB_FE_NO_EXIT; fepriv->thread = NULL; mb(); fe_thread = kthread_run(dvb_frontend_thread, fe, "kdvb-ad-%i-fe-%i", fe->dvb->num,fe->id); if (IS_ERR(fe_thread)) { ret = PTR_ERR(fe_thread); dev_warn(fe->dvb->device, "dvb_frontend_start: failed to start kthread (%d)\n", ret); up(&fepriv->sem); return ret; } fepriv->thread = fe_thread; return 0; } static void dvb_frontend_get_frequency_limits(struct dvb_frontend *fe, u32 *freq_min, u32 *freq_max) { *freq_min = max(fe->ops.info.frequency_min, fe->ops.tuner_ops.info.frequency_min); if (fe->ops.info.frequency_max == 0) *freq_max = fe->ops.tuner_ops.info.frequency_max; else if (fe->ops.tuner_ops.info.frequency_max == 0) *freq_max = fe->ops.info.frequency_max; else *freq_max = min(fe->ops.info.frequency_max, fe->ops.tuner_ops.info.frequency_max); if (*freq_min == 0 || *freq_max == 0) dev_warn(fe->dvb->device, "DVB: adapter %i frontend %u frequency limits undefined - fix the driver\n", fe->dvb->num, fe->id); } static int dvb_frontend_check_parameters(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; u32 freq_min; u32 freq_max; /* range check: frequency */ dvb_frontend_get_frequency_limits(fe, &freq_min, &freq_max); if ((freq_min && c->frequency < freq_min) || (freq_max && c->frequency > freq_max)) { dev_warn(fe->dvb->device, "DVB: adapter %i frontend %i frequency %u out of range (%u..%u)\n", fe->dvb->num, fe->id, c->frequency, freq_min, freq_max); return -EINVAL; } /* range check: symbol rate */ switch (c->delivery_system) { case SYS_DVBS: case SYS_DVBS2: case SYS_TURBO: case SYS_DVBC_ANNEX_A: case SYS_DVBC_ANNEX_C: if ((fe->ops.info.symbol_rate_min && c->symbol_rate < fe->ops.info.symbol_rate_min) || (fe->ops.info.symbol_rate_max && c->symbol_rate > fe->ops.info.symbol_rate_max)) { dev_warn(fe->dvb->device, "DVB: adapter %i frontend %i symbol rate %u out of range (%u..%u)\n", fe->dvb->num, fe->id, c->symbol_rate, fe->ops.info.symbol_rate_min, fe->ops.info.symbol_rate_max); return -EINVAL; } default: break; } return 0; } static int dvb_frontend_clear_cache(struct dvb_frontend *fe) { struct dtv_frontend_properties *c = &fe->dtv_property_cache; int i; u32 delsys; delsys = c->delivery_system; memset(c, 0, offsetof(struct dtv_frontend_properties, strength)); c->delivery_system = delsys; c->state = DTV_CLEAR; dev_dbg(fe->dvb->device, "%s: Clearing cache for delivery system %d\n", __func__, c->delivery_system); c->transmission_mode = TRANSMISSION_MODE_AUTO; c->bandwidth_hz = 0; /* AUTO */ c->guard_interval = GUARD_INTERVAL_AUTO; c->hierarchy = HIERARCHY_AUTO; c->symbol_rate = 0; c->code_rate_HP = FEC_AUTO; c->code_rate_LP = FEC_AUTO; c->fec_inner = FEC_AUTO; c->rolloff = ROLLOFF_AUTO; c->voltage = SEC_VOLTAGE_OFF; c->sectone = SEC_TONE_OFF; c->pilot = PILOT_AUTO; c->isdbt_partial_reception = 0; c->isdbt_sb_mode = 0; c->isdbt_sb_subchannel = 0; c->isdbt_sb_segment_idx = 0; c->isdbt_sb_segment_count = 0; c->isdbt_layer_enabled = 0; for (i = 0; i < 3; i++) { c->layer[i].fec = FEC_AUTO; c->layer[i].modulation = QAM_AUTO; c->layer[i].interleaving = 0; c->layer[i].segment_count = 0; } c->stream_id = NO_STREAM_ID_FILTER; switch (c->delivery_system) { case SYS_DVBS: case SYS_DVBS2: case SYS_TURBO: c->modulation = QPSK; /* implied for DVB-S in legacy API */ c->rolloff = ROLLOFF_35;/* implied for DVB-S */ break; case SYS_ATSC: c->modulation = VSB_8; break; case SYS_ISDBS: c->symbol_rate = 28860000; c->rolloff = ROLLOFF_35; c->bandwidth_hz = c->symbol_rate / 100 * 135; break; default: c->modulation = QAM_AUTO; break; } c->lna = LNA_AUTO; return 0; } #define _DTV_CMD(n, s, b) \ [n] = { \ .name = #n, \ .cmd = n, \ .set = s,\ .buffer = b \ } static struct dtv_cmds_h dtv_cmds[DTV_MAX_COMMAND + 1] = { _DTV_CMD(DTV_TUNE, 1, 0), _DTV_CMD(DTV_CLEAR, 1, 0), /* Set */ _DTV_CMD(DTV_FREQUENCY, 1, 0), _DTV_CMD(DTV_BANDWIDTH_HZ, 1, 0), _DTV_CMD(DTV_MODULATION, 1, 0), _DTV_CMD(DTV_INVERSION, 1, 0), _DTV_CMD(DTV_DISEQC_MASTER, 1, 1), _DTV_CMD(DTV_SYMBOL_RATE, 1, 0), _DTV_CMD(DTV_INNER_FEC, 1, 0), _DTV_CMD(DTV_VOLTAGE, 1, 0), _DTV_CMD(DTV_TONE, 1, 0), _DTV_CMD(DTV_PILOT, 1, 0), _DTV_CMD(DTV_ROLLOFF, 1, 0), _DTV_CMD(DTV_DELIVERY_SYSTEM, 1, 0), _DTV_CMD(DTV_HIERARCHY, 1, 0), _DTV_CMD(DTV_CODE_RATE_HP, 1, 0), _DTV_CMD(DTV_CODE_RATE_LP, 1, 0), _DTV_CMD(DTV_GUARD_INTERVAL, 1, 0), _DTV_CMD(DTV_TRANSMISSION_MODE, 1, 0), _DTV_CMD(DTV_INTERLEAVING, 1, 0), _DTV_CMD(DTV_ISDBT_PARTIAL_RECEPTION, 1, 0), _DTV_CMD(DTV_ISDBT_SOUND_BROADCASTING, 1, 0), _DTV_CMD(DTV_ISDBT_SB_SUBCHANNEL_ID, 1, 0), _DTV_CMD(DTV_ISDBT_SB_SEGMENT_IDX, 1, 0), _DTV_CMD(DTV_ISDBT_SB_SEGMENT_COUNT, 1, 0), _DTV_CMD(DTV_ISDBT_LAYER_ENABLED, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERA_FEC, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERA_MODULATION, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERA_SEGMENT_COUNT, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERA_TIME_INTERLEAVING, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERB_FEC, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERB_MODULATION, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERB_SEGMENT_COUNT, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERB_TIME_INTERLEAVING, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERC_FEC, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERC_MODULATION, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERC_SEGMENT_COUNT, 1, 0), _DTV_CMD(DTV_ISDBT_LAYERC_TIME_INTERLEAVING, 1, 0), _DTV_CMD(DTV_STREAM_ID, 1, 0), _DTV_CMD(DTV_DVBT2_PLP_ID_LEGACY, 1, 0), _DTV_CMD(DTV_LNA, 1, 0), /* Get */ _DTV_CMD(DTV_DISEQC_SLAVE_REPLY, 0, 1), _DTV_CMD(DTV_API_VERSION, 0, 0), _DTV_CMD(DTV_ENUM_DELSYS, 0, 0), _DTV_CMD(DTV_ATSCMH_PARADE_ID, 1, 0), _DTV_CMD(DTV_ATSCMH_RS_FRAME_ENSEMBLE, 1, 0), _DTV_CMD(DTV_ATSCMH_FIC_VER, 0, 0), _DTV_CMD(DTV_ATSCMH_NOG, 0, 0), _DTV_CMD(DTV_ATSCMH_TNOG, 0, 0), _DTV_CMD(DTV_ATSCMH_SGN, 0, 0), _DTV_CMD(DTV_ATSCMH_PRC, 0, 0), _DTV_CMD(DTV_ATSCMH_RS_FRAME_MODE, 0, 0), _DTV_CMD(DTV_ATSCMH_RS_CODE_MODE_PRI, 0, 0), _DTV_CMD(DTV_ATSCMH_RS_CODE_MODE_SEC, 0, 0), _DTV_CMD(DTV_ATSCMH_SCCC_BLOCK_MODE, 0, 0), _DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_A, 0, 0), _DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_B, 0, 0), _DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_C, 0, 0), _DTV_CMD(DTV_ATSCMH_SCCC_CODE_MODE_D, 0, 0), /* Statistics API */ _DTV_CMD(DTV_STAT_SIGNAL_STRENGTH, 0, 0), _DTV_CMD(DTV_STAT_CNR, 0, 0), _DTV_CMD(DTV_STAT_PRE_ERROR_BIT_COUNT, 0, 0), _DTV_CMD(DTV_STAT_PRE_TOTAL_BIT_COUNT, 0, 0), _DTV_CMD(DTV_STAT_POST_ERROR_BIT_COUNT, 0, 0), _DTV_CMD(DTV_STAT_POST_TOTAL_BIT_COUNT, 0, 0), _DTV_CMD(DTV_STAT_ERROR_BLOCK_COUNT, 0, 0), _DTV_CMD(DTV_STAT_TOTAL_BLOCK_COUNT, 0, 0), }; static void dtv_property_dump(struct dvb_frontend *fe, bool is_set, struct dtv_property *tvp) { int i; if (tvp->cmd <= 0 || tvp->cmd > DTV_MAX_COMMAND) { dev_warn(fe->dvb->device, "%s: %s tvp.cmd = 0x%08x undefined\n", __func__, is_set ? "SET" : "GET", tvp->cmd); return; } dev_dbg(fe->dvb->device, "%s: %s tvp.cmd = 0x%08x (%s)\n", __func__, is_set ? "SET" : "GET", tvp->cmd, dtv_cmds[tvp->cmd].name); if (dtv_cmds[tvp->cmd].buffer) { dev_dbg(fe->dvb->device, "%s: tvp.u.buffer.len = 0x%02x\n", __func__, tvp->u.buffer.len); for(i = 0; i < tvp->u.buffer.len; i++) dev_dbg(fe->dvb->device, "%s: tvp.u.buffer.data[0x%02x] = 0x%02x\n", __func__, i, tvp->u.buffer.data[i]); } else { dev_dbg(fe->dvb->device, "%s: tvp.u.data = 0x%08x\n", __func__, tvp->u.data); } } /* Synchronise the legacy tuning parameters into the cache, so that demodulator * drivers can use a single set_frontend tuning function, regardless of whether * it's being used for the legacy or new API, reducing code and complexity. */ static int dtv_property_cache_sync(struct dvb_frontend *fe, struct dtv_frontend_properties *c, const struct dvb_frontend_parameters *p) { c->frequency = p->frequency; c->inversion = p->inversion; switch (dvbv3_type(c->delivery_system)) { case DVBV3_QPSK: dev_dbg(fe->dvb->device, "%s: Preparing QPSK req\n", __func__); c->symbol_rate = p->u.qpsk.symbol_rate; c->fec_inner = p->u.qpsk.fec_inner; break; case DVBV3_QAM: dev_dbg(fe->dvb->device, "%s: Preparing QAM req\n", __func__); c->symbol_rate = p->u.qam.symbol_rate; c->fec_inner = p->u.qam.fec_inner; c->modulation = p->u.qam.modulation; break; case DVBV3_OFDM: dev_dbg(fe->dvb->device, "%s: Preparing OFDM req\n", __func__); switch (p->u.ofdm.bandwidth) { case BANDWIDTH_10_MHZ: c->bandwidth_hz = 10000000; break; case BANDWIDTH_8_MHZ: c->bandwidth_hz = 8000000; break; case BANDWIDTH_7_MHZ: c->bandwidth_hz = 7000000; break; case BANDWIDTH_6_MHZ: c->bandwidth_hz = 6000000; break; case BANDWIDTH_5_MHZ: c->bandwidth_hz = 5000000; break; case BANDWIDTH_1_712_MHZ: c->bandwidth_hz = 1712000; break; case BANDWIDTH_AUTO: c->bandwidth_hz = 0; } c->code_rate_HP = p->u.ofdm.code_rate_HP; c->code_rate_LP = p->u.ofdm.code_rate_LP; c->modulation = p->u.ofdm.constellation; c->transmission_mode = p->u.ofdm.transmission_mode; c->guard_interval = p->u.ofdm.guard_interval; c->hierarchy = p->u.ofdm.hierarchy_information; break; case DVBV3_ATSC: dev_dbg(fe->dvb->device, "%s: Preparing ATSC req\n", __func__); c->modulation = p->u.vsb.modulation; if (c->delivery_system == SYS_ATSCMH) break; if ((c->modulation == VSB_8) || (c->modulation == VSB_16)) c->delivery_system = SYS_ATSC; else c->delivery_system = SYS_DVBC_ANNEX_B; break; case DVBV3_UNKNOWN: dev_err(fe->dvb->device, "%s: doesn't know how to handle a DVBv3 call to delivery system %i\n", __func__, c->delivery_system); return -EINVAL; } return 0; } /* Ensure the cached values are set correctly in the frontend * legacy tuning structures, for the advanced tuning API. */ static int dtv_property_legacy_params_sync(struct dvb_frontend *fe, const struct dtv_frontend_properties *c, struct dvb_frontend_parameters *p) { p->frequency = c->frequency; p->inversion = c->inversion; switch (dvbv3_type(c->delivery_system)) { case DVBV3_UNKNOWN: dev_err(fe->dvb->device, "%s: doesn't know how to handle a DVBv3 call to delivery system %i\n", __func__, c->delivery_system); return -EINVAL; case DVBV3_QPSK: dev_dbg(fe->dvb->device, "%s: Preparing QPSK req\n", __func__); p->u.qpsk.symbol_rate = c->symbol_rate; p->u.qpsk.fec_inner = c->fec_inner; break; case DVBV3_QAM: dev_dbg(fe->dvb->device, "%s: Preparing QAM req\n", __func__); p->u.qam.symbol_rate = c->symbol_rate; p->u.qam.fec_inner = c->fec_inner; p->u.qam.modulation = c->modulation; break; case DVBV3_OFDM: dev_dbg(fe->dvb->device, "%s: Preparing OFDM req\n", __func__); switch (c->bandwidth_hz) { case 10000000: p->u.ofdm.bandwidth = BANDWIDTH_10_MHZ; break; case 8000000: p->u.ofdm.bandwidth = BANDWIDTH_8_MHZ; break; case 7000000: p->u.ofdm.bandwidth = BANDWIDTH_7_MHZ; break; case 6000000: p->u.ofdm.bandwidth = BANDWIDTH_6_MHZ; break; case 5000000: p->u.ofdm.bandwidth = BANDWIDTH_5_MHZ; break; case 1712000: p->u.ofdm.bandwidth = BANDWIDTH_1_712_MHZ; break; case 0: default: p->u.ofdm.bandwidth = BANDWIDTH_AUTO; } p->u.ofdm.code_rate_HP = c->code_rate_HP; p->u.ofdm.code_rate_LP = c->code_rate_LP; p->u.ofdm.constellation = c->modulation; p->u.ofdm.transmission_mode = c->transmission_mode; p->u.ofdm.guard_interval = c->guard_interval; p->u.ofdm.hierarchy_information = c->hierarchy; break; case DVBV3_ATSC: dev_dbg(fe->dvb->device, "%s: Preparing VSB req\n", __func__); p->u.vsb.modulation = c->modulation; break; } return 0; } /** * dtv_get_frontend - calls a callback for retrieving DTV parameters * @fe: struct dvb_frontend pointer * @c: struct dtv_frontend_properties pointer (DVBv5 cache) * @p_out struct dvb_frontend_parameters pointer (DVBv3 FE struct) * * This routine calls either the DVBv3 or DVBv5 get_frontend call. * If c is not null, it will update the DVBv5 cache struct pointed by it. * If p_out is not null, it will update the DVBv3 params pointed by it. */ static int dtv_get_frontend(struct dvb_frontend *fe, struct dtv_frontend_properties *c, struct dvb_frontend_parameters *p_out) { int r; if (fe->ops.get_frontend) { r = fe->ops.get_frontend(fe, c); if (unlikely(r < 0)) return r; if (p_out) dtv_property_legacy_params_sync(fe, c, p_out); return 0; } /* As everything is in cache, get_frontend fops are always supported */ return 0; } static int dvb_frontend_ioctl_legacy(struct file *file, unsigned int cmd, void *parg); static int dvb_frontend_ioctl_properties(struct file *file, unsigned int cmd, void *parg); static int dtv_property_process_get(struct dvb_frontend *fe, const struct dtv_frontend_properties *c, struct dtv_property *tvp, struct file *file) { int r, ncaps; switch(tvp->cmd) { case DTV_ENUM_DELSYS: ncaps = 0; while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) { tvp->u.buffer.data[ncaps] = fe->ops.delsys[ncaps]; ncaps++; } tvp->u.buffer.len = ncaps; break; case DTV_FREQUENCY: tvp->u.data = c->frequency; break; case DTV_MODULATION: tvp->u.data = c->modulation; break; case DTV_BANDWIDTH_HZ: tvp->u.data = c->bandwidth_hz; break; case DTV_INVERSION: tvp->u.data = c->inversion; break; case DTV_SYMBOL_RATE: tvp->u.data = c->symbol_rate; break; case DTV_INNER_FEC: tvp->u.data = c->fec_inner; break; case DTV_PILOT: tvp->u.data = c->pilot; break; case DTV_ROLLOFF: tvp->u.data = c->rolloff; break; case DTV_DELIVERY_SYSTEM: tvp->u.data = c->delivery_system; break; case DTV_VOLTAGE: tvp->u.data = c->voltage; break; case DTV_TONE: tvp->u.data = c->sectone; break; case DTV_API_VERSION: tvp->u.data = (DVB_API_VERSION << 8) | DVB_API_VERSION_MINOR; break; case DTV_CODE_RATE_HP: tvp->u.data = c->code_rate_HP; break; case DTV_CODE_RATE_LP: tvp->u.data = c->code_rate_LP; break; case DTV_GUARD_INTERVAL: tvp->u.data = c->guard_interval; break; case DTV_TRANSMISSION_MODE: tvp->u.data = c->transmission_mode; break; case DTV_HIERARCHY: tvp->u.data = c->hierarchy; break; case DTV_INTERLEAVING: tvp->u.data = c->interleaving; break; /* ISDB-T Support here */ case DTV_ISDBT_PARTIAL_RECEPTION: tvp->u.data = c->isdbt_partial_reception; break; case DTV_ISDBT_SOUND_BROADCASTING: tvp->u.data = c->isdbt_sb_mode; break; case DTV_ISDBT_SB_SUBCHANNEL_ID: tvp->u.data = c->isdbt_sb_subchannel; break; case DTV_ISDBT_SB_SEGMENT_IDX: tvp->u.data = c->isdbt_sb_segment_idx; break; case DTV_ISDBT_SB_SEGMENT_COUNT: tvp->u.data = c->isdbt_sb_segment_count; break; case DTV_ISDBT_LAYER_ENABLED: tvp->u.data = c->isdbt_layer_enabled; break; case DTV_ISDBT_LAYERA_FEC: tvp->u.data = c->layer[0].fec; break; case DTV_ISDBT_LAYERA_MODULATION: tvp->u.data = c->layer[0].modulation; break; case DTV_ISDBT_LAYERA_SEGMENT_COUNT: tvp->u.data = c->layer[0].segment_count; break; case DTV_ISDBT_LAYERA_TIME_INTERLEAVING: tvp->u.data = c->layer[0].interleaving; break; case DTV_ISDBT_LAYERB_FEC: tvp->u.data = c->layer[1].fec; break; case DTV_ISDBT_LAYERB_MODULATION: tvp->u.data = c->layer[1].modulation; break; case DTV_ISDBT_LAYERB_SEGMENT_COUNT: tvp->u.data = c->layer[1].segment_count; break; case DTV_ISDBT_LAYERB_TIME_INTERLEAVING: tvp->u.data = c->layer[1].interleaving; break; case DTV_ISDBT_LAYERC_FEC: tvp->u.data = c->layer[2].fec; break; case DTV_ISDBT_LAYERC_MODULATION: tvp->u.data = c->layer[2].modulation; break; case DTV_ISDBT_LAYERC_SEGMENT_COUNT: tvp->u.data = c->layer[2].segment_count; break; case DTV_ISDBT_LAYERC_TIME_INTERLEAVING: tvp->u.data = c->layer[2].interleaving; break; /* Multistream support */ case DTV_STREAM_ID: case DTV_DVBT2_PLP_ID_LEGACY: tvp->u.data = c->stream_id; break; /* ATSC-MH */ case DTV_ATSCMH_FIC_VER: tvp->u.data = fe->dtv_property_cache.atscmh_fic_ver; break; case DTV_ATSCMH_PARADE_ID: tvp->u.data = fe->dtv_property_cache.atscmh_parade_id; break; case DTV_ATSCMH_NOG: tvp->u.data = fe->dtv_property_cache.atscmh_nog; break; case DTV_ATSCMH_TNOG: tvp->u.data = fe->dtv_property_cache.atscmh_tnog; break; case DTV_ATSCMH_SGN: tvp->u.data = fe->dtv_property_cache.atscmh_sgn; break; case DTV_ATSCMH_PRC: tvp->u.data = fe->dtv_property_cache.atscmh_prc; break; case DTV_ATSCMH_RS_FRAME_MODE: tvp->u.data = fe->dtv_property_cache.atscmh_rs_frame_mode; break; case DTV_ATSCMH_RS_FRAME_ENSEMBLE: tvp->u.data = fe->dtv_property_cache.atscmh_rs_frame_ensemble; break; case DTV_ATSCMH_RS_CODE_MODE_PRI: tvp->u.data = fe->dtv_property_cache.atscmh_rs_code_mode_pri; break; case DTV_ATSCMH_RS_CODE_MODE_SEC: tvp->u.data = fe->dtv_property_cache.atscmh_rs_code_mode_sec; break; case DTV_ATSCMH_SCCC_BLOCK_MODE: tvp->u.data = fe->dtv_property_cache.atscmh_sccc_block_mode; break; case DTV_ATSCMH_SCCC_CODE_MODE_A: tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_a; break; case DTV_ATSCMH_SCCC_CODE_MODE_B: tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_b; break; case DTV_ATSCMH_SCCC_CODE_MODE_C: tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_c; break; case DTV_ATSCMH_SCCC_CODE_MODE_D: tvp->u.data = fe->dtv_property_cache.atscmh_sccc_code_mode_d; break; case DTV_LNA: tvp->u.data = c->lna; break; /* Fill quality measures */ case DTV_STAT_SIGNAL_STRENGTH: tvp->u.st = c->strength; break; case DTV_STAT_CNR: tvp->u.st = c->cnr; break; case DTV_STAT_PRE_ERROR_BIT_COUNT: tvp->u.st = c->pre_bit_error; break; case DTV_STAT_PRE_TOTAL_BIT_COUNT: tvp->u.st = c->pre_bit_count; break; case DTV_STAT_POST_ERROR_BIT_COUNT: tvp->u.st = c->post_bit_error; break; case DTV_STAT_POST_TOTAL_BIT_COUNT: tvp->u.st = c->post_bit_count; break; case DTV_STAT_ERROR_BLOCK_COUNT: tvp->u.st = c->block_error; break; case DTV_STAT_TOTAL_BLOCK_COUNT: tvp->u.st = c->block_count; break; default: dev_dbg(fe->dvb->device, "%s: FE property %d doesn't exist\n", __func__, tvp->cmd); return -EINVAL; } /* Allow the frontend to override outgoing properties */ if (fe->ops.get_property) { r = fe->ops.get_property(fe, tvp); if (r < 0) return r; } dtv_property_dump(fe, false, tvp); return 0; } static int dtv_set_frontend(struct dvb_frontend *fe); static bool is_dvbv3_delsys(u32 delsys) { bool status; status = (delsys == SYS_DVBT) || (delsys == SYS_DVBC_ANNEX_A) || (delsys == SYS_DVBS) || (delsys == SYS_ATSC); return status; } /** * emulate_delivery_system - emulate a DVBv5 delivery system with a DVBv3 type * @fe: struct frontend; * @delsys: DVBv5 type that will be used for emulation * * Provides emulation for delivery systems that are compatible with the old * DVBv3 call. Among its usages, it provices support for ISDB-T, and allows * using a DVB-S2 only frontend just like it were a DVB-S, if the frontent * parameters are compatible with DVB-S spec. */ static int emulate_delivery_system(struct dvb_frontend *fe, u32 delsys) { int i; struct dtv_frontend_properties *c = &fe->dtv_property_cache; c->delivery_system = delsys; /* * If the call is for ISDB-T, put it into full-seg, auto mode, TV */ if (c->delivery_system == SYS_ISDBT) { dev_dbg(fe->dvb->device, "%s: Using defaults for SYS_ISDBT\n", __func__); if (!c->bandwidth_hz) c->bandwidth_hz = 6000000; c->isdbt_partial_reception = 0; c->isdbt_sb_mode = 0; c->isdbt_sb_subchannel = 0; c->isdbt_sb_segment_idx = 0; c->isdbt_sb_segment_count = 0; c->isdbt_layer_enabled = 7; for (i = 0; i < 3; i++) { c->layer[i].fec = FEC_AUTO; c->layer[i].modulation = QAM_AUTO; c->layer[i].interleaving = 0; c->layer[i].segment_count = 0; } } dev_dbg(fe->dvb->device, "%s: change delivery system on cache to %d\n", __func__, c->delivery_system); return 0; } /** * dvbv5_set_delivery_system - Sets the delivery system for a DVBv5 API call * @fe: frontend struct * @desired_system: delivery system requested by the user * * A DVBv5 call know what's the desired system it wants. So, set it. * * There are, however, a few known issues with early DVBv5 applications that * are also handled by this logic: * * 1) Some early apps use SYS_UNDEFINED as the desired delivery system. * This is an API violation, but, as we don't want to break userspace, * convert it to the first supported delivery system. * 2) Some apps might be using a DVBv5 call in a wrong way, passing, for * example, SYS_DVBT instead of SYS_ISDBT. This is because early usage of * ISDB-T provided backward compat with DVB-T. */ static int dvbv5_set_delivery_system(struct dvb_frontend *fe, u32 desired_system) { int ncaps; u32 delsys = SYS_UNDEFINED; struct dtv_frontend_properties *c = &fe->dtv_property_cache; enum dvbv3_emulation_type type; /* * It was reported that some old DVBv5 applications were * filling delivery_system with SYS_UNDEFINED. If this happens, * assume that the application wants to use the first supported * delivery system. */ if (desired_system == SYS_UNDEFINED) desired_system = fe->ops.delsys[0]; /* * This is a DVBv5 call. So, it likely knows the supported * delivery systems. So, check if the desired delivery system is * supported */ ncaps = 0; while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) { if (fe->ops.delsys[ncaps] == desired_system) { c->delivery_system = desired_system; dev_dbg(fe->dvb->device, "%s: Changing delivery system to %d\n", __func__, desired_system); return 0; } ncaps++; } /* * The requested delivery system isn't supported. Maybe userspace * is requesting a DVBv3 compatible delivery system. * * The emulation only works if the desired system is one of the * delivery systems supported by DVBv3 API */ if (!is_dvbv3_delsys(desired_system)) { dev_dbg(fe->dvb->device, "%s: Delivery system %d not supported.\n", __func__, desired_system); return -EINVAL; } type = dvbv3_type(desired_system); /* * Get the last non-DVBv3 delivery system that has the same type * of the desired system */ ncaps = 0; while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) { if (dvbv3_type(fe->ops.delsys[ncaps]) == type) delsys = fe->ops.delsys[ncaps]; ncaps++; } /* There's nothing compatible with the desired delivery system */ if (delsys == SYS_UNDEFINED) { dev_dbg(fe->dvb->device, "%s: Delivery system %d not supported on emulation mode.\n", __func__, desired_system); return -EINVAL; } dev_dbg(fe->dvb->device, "%s: Using delivery system %d emulated as if it were %d\n", __func__, delsys, desired_system); return emulate_delivery_system(fe, desired_system); } /** * dvbv3_set_delivery_system - Sets the delivery system for a DVBv3 API call * @fe: frontend struct * * A DVBv3 call doesn't know what's the desired system it wants. It also * doesn't allow to switch between different types. Due to that, userspace * should use DVBv5 instead. * However, in order to avoid breaking userspace API, limited backward * compatibility support is provided. * * There are some delivery systems that are incompatible with DVBv3 calls. * * This routine should work fine for frontends that support just one delivery * system. * * For frontends that support multiple frontends: * 1) It defaults to use the first supported delivery system. There's an * userspace application that allows changing it at runtime; * * 2) If the current delivery system is not compatible with DVBv3, it gets * the first one that it is compatible. * * NOTE: in order for this to work with applications like Kaffeine that * uses a DVBv5 call for DVB-S2 and a DVBv3 call to go back to * DVB-S, drivers that support both DVB-S and DVB-S2 should have the * SYS_DVBS entry before the SYS_DVBS2, otherwise it won't switch back * to DVB-S. */ static int dvbv3_set_delivery_system(struct dvb_frontend *fe) { int ncaps; u32 delsys = SYS_UNDEFINED; struct dtv_frontend_properties *c = &fe->dtv_property_cache; /* If not set yet, defaults to the first supported delivery system */ if (c->delivery_system == SYS_UNDEFINED) c->delivery_system = fe->ops.delsys[0]; /* * Trivial case: just use the current one, if it already a DVBv3 * delivery system */ if (is_dvbv3_delsys(c->delivery_system)) { dev_dbg(fe->dvb->device, "%s: Using delivery system to %d\n", __func__, c->delivery_system); return 0; } /* * Seek for the first delivery system that it is compatible with a * DVBv3 standard */ ncaps = 0; while (ncaps < MAX_DELSYS && fe->ops.delsys[ncaps]) { if (dvbv3_type(fe->ops.delsys[ncaps]) != DVBV3_UNKNOWN) { delsys = fe->ops.delsys[ncaps]; break; } ncaps++; } if (delsys == SYS_UNDEFINED) { dev_dbg(fe->dvb->device, "%s: Couldn't find a delivery system that works with FE_SET_FRONTEND\n", __func__); return -EINVAL; } return emulate_delivery_system(fe, delsys); } static int dtv_property_process_set(struct dvb_frontend *fe, struct dtv_property *tvp, struct file *file) { int r = 0; struct dtv_frontend_properties *c = &fe->dtv_property_cache; /* Allow the frontend to validate incoming properties */ if (fe->ops.set_property) { r = fe->ops.set_property(fe, tvp); if (r < 0) return r; } dtv_property_dump(fe, true, tvp); switch(tvp->cmd) { case DTV_CLEAR: /* * Reset a cache of data specific to the frontend here. This does * not effect hardware. */ dvb_frontend_clear_cache(fe); break; case DTV_TUNE: /* interpret the cache of data, build either a traditional frontend * tunerequest so we can pass validation in the FE_SET_FRONTEND * ioctl. */ c->state = tvp->cmd; dev_dbg(fe->dvb->device, "%s: Finalised property cache\n", __func__); r = dtv_set_frontend(fe); break; case DTV_FREQUENCY: c->frequency = tvp->u.data; break; case DTV_MODULATION: c->modulation = tvp->u.data; break; case DTV_BANDWIDTH_HZ: c->bandwidth_hz = tvp->u.data; break; case DTV_INVERSION: c->inversion = tvp->u.data; break; case DTV_SYMBOL_RATE: c->symbol_rate = tvp->u.data; break; case DTV_INNER_FEC: c->fec_inner = tvp->u.data; break; case DTV_PILOT: c->pilot = tvp->u.data; break; case DTV_ROLLOFF: c->rolloff = tvp->u.data; break; case DTV_DELIVERY_SYSTEM: r = dvbv5_set_delivery_system(fe, tvp->u.data); break; case DTV_VOLTAGE: c->voltage = tvp->u.data; r = dvb_frontend_ioctl_legacy(file, FE_SET_VOLTAGE, (void *)c->voltage); break; case DTV_TONE: c->sectone = tvp->u.data; r = dvb_frontend_ioctl_legacy(file, FE_SET_TONE, (void *)c->sectone); break; case DTV_CODE_RATE_HP: c->code_rate_HP = tvp->u.data; break; case DTV_CODE_RATE_LP: c->code_rate_LP = tvp->u.data; break; case DTV_GUARD_INTERVAL: c->guard_interval = tvp->u.data; break; case DTV_TRANSMISSION_MODE: c->transmission_mode = tvp->u.data; break; case DTV_HIERARCHY: c->hierarchy = tvp->u.data; break; case DTV_INTERLEAVING: c->interleaving = tvp->u.data; break; /* ISDB-T Support here */ case DTV_ISDBT_PARTIAL_RECEPTION: c->isdbt_partial_reception = tvp->u.data; break; case DTV_ISDBT_SOUND_BROADCASTING: c->isdbt_sb_mode = tvp->u.data; break; case DTV_ISDBT_SB_SUBCHANNEL_ID: c->isdbt_sb_subchannel = tvp->u.data; break; case DTV_ISDBT_SB_SEGMENT_IDX: c->isdbt_sb_segment_idx = tvp->u.data; break; case DTV_ISDBT_SB_SEGMENT_COUNT: c->isdbt_sb_segment_count = tvp->u.data; break; case DTV_ISDBT_LAYER_ENABLED: c->isdbt_layer_enabled = tvp->u.data; break; case DTV_ISDBT_LAYERA_FEC: c->layer[0].fec = tvp->u.data; break; case DTV_ISDBT_LAYERA_MODULATION: c->layer[0].modulation = tvp->u.data; break; case DTV_ISDBT_LAYERA_SEGMENT_COUNT: c->layer[0].segment_count = tvp->u.data; break; case DTV_ISDBT_LAYERA_TIME_INTERLEAVING: c->layer[0].interleaving = tvp->u.data; break; case DTV_ISDBT_LAYERB_FEC: c->layer[1].fec = tvp->u.data; break; case DTV_ISDBT_LAYERB_MODULATION: c->layer[1].modulation = tvp->u.data; break; case DTV_ISDBT_LAYERB_SEGMENT_COUNT: c->layer[1].segment_count = tvp->u.data; break; case DTV_ISDBT_LAYERB_TIME_INTERLEAVING: c->layer[1].interleaving = tvp->u.data; break; case DTV_ISDBT_LAYERC_FEC: c->layer[2].fec = tvp->u.data; break; case DTV_ISDBT_LAYERC_MODULATION: c->layer[2].modulation = tvp->u.data; break; case DTV_ISDBT_LAYERC_SEGMENT_COUNT: c->layer[2].segment_count = tvp->u.data; break; case DTV_ISDBT_LAYERC_TIME_INTERLEAVING: c->layer[2].interleaving = tvp->u.data; break; /* Multistream support */ case DTV_STREAM_ID: case DTV_DVBT2_PLP_ID_LEGACY: c->stream_id = tvp->u.data; break; /* ATSC-MH */ case DTV_ATSCMH_PARADE_ID: fe->dtv_property_cache.atscmh_parade_id = tvp->u.data; break; case DTV_ATSCMH_RS_FRAME_ENSEMBLE: fe->dtv_property_cache.atscmh_rs_frame_ensemble = tvp->u.data; break; case DTV_LNA: c->lna = tvp->u.data; if (fe->ops.set_lna) r = fe->ops.set_lna(fe); if (r < 0) c->lna = LNA_AUTO; break; default: return -EINVAL; } return r; } static int dvb_frontend_ioctl(struct file *file, unsigned int cmd, void *parg) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct dvb_frontend_private *fepriv = fe->frontend_priv; int err = -EOPNOTSUPP; dev_dbg(fe->dvb->device, "%s: (%d)\n", __func__, _IOC_NR(cmd)); if (down_interruptible(&fepriv->sem)) return -ERESTARTSYS; if (fe->exit != DVB_FE_NO_EXIT) { up(&fepriv->sem); return -ENODEV; } if ((file->f_flags & O_ACCMODE) == O_RDONLY && (_IOC_DIR(cmd) != _IOC_READ || cmd == FE_GET_EVENT || cmd == FE_DISEQC_RECV_SLAVE_REPLY)) { up(&fepriv->sem); return -EPERM; } if ((cmd == FE_SET_PROPERTY) || (cmd == FE_GET_PROPERTY)) err = dvb_frontend_ioctl_properties(file, cmd, parg); else { c->state = DTV_UNDEFINED; err = dvb_frontend_ioctl_legacy(file, cmd, parg); } up(&fepriv->sem); return err; } static int dvb_frontend_ioctl_properties(struct file *file, unsigned int cmd, void *parg) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; int err = 0; struct dtv_properties *tvps = parg; struct dtv_property *tvp = NULL; int i; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (cmd == FE_SET_PROPERTY) { dev_dbg(fe->dvb->device, "%s: properties.num = %d\n", __func__, tvps->num); dev_dbg(fe->dvb->device, "%s: properties.props = %p\n", __func__, tvps->props); /* Put an arbitrary limit on the number of messages that can * be sent at once */ if ((tvps->num == 0) || (tvps->num > DTV_IOCTL_MAX_MSGS)) return -EINVAL; tvp = kmalloc(tvps->num * sizeof(struct dtv_property), GFP_KERNEL); if (!tvp) { err = -ENOMEM; goto out; } if (copy_from_user(tvp, (void __user *)tvps->props, tvps->num * sizeof(struct dtv_property))) { err = -EFAULT; goto out; } for (i = 0; i < tvps->num; i++) { err = dtv_property_process_set(fe, tvp + i, file); if (err < 0) goto out; (tvp + i)->result = err; } if (c->state == DTV_TUNE) dev_dbg(fe->dvb->device, "%s: Property cache is full, tuning\n", __func__); } else if (cmd == FE_GET_PROPERTY) { struct dtv_frontend_properties getp = fe->dtv_property_cache; dev_dbg(fe->dvb->device, "%s: properties.num = %d\n", __func__, tvps->num); dev_dbg(fe->dvb->device, "%s: properties.props = %p\n", __func__, tvps->props); /* Put an arbitrary limit on the number of messages that can * be sent at once */ if ((tvps->num == 0) || (tvps->num > DTV_IOCTL_MAX_MSGS)) return -EINVAL; tvp = kmalloc(tvps->num * sizeof(struct dtv_property), GFP_KERNEL); if (!tvp) { err = -ENOMEM; goto out; } if (copy_from_user(tvp, (void __user *)tvps->props, tvps->num * sizeof(struct dtv_property))) { err = -EFAULT; goto out; } /* * Let's use our own copy of property cache, in order to * avoid mangling with DTV zigzag logic, as drivers might * return crap, if they don't check if the data is available * before updating the properties cache. */ if (fepriv->state != FESTATE_IDLE) { err = dtv_get_frontend(fe, &getp, NULL); if (err < 0) goto out; } for (i = 0; i < tvps->num; i++) { err = dtv_property_process_get(fe, &getp, tvp + i, file); if (err < 0) goto out; (tvp + i)->result = err; } if (copy_to_user((void __user *)tvps->props, tvp, tvps->num * sizeof(struct dtv_property))) { err = -EFAULT; goto out; } } else err = -EOPNOTSUPP; out: kfree(tvp); return err; } static int dtv_set_frontend(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; struct dvb_frontend_tune_settings fetunesettings; u32 rolloff = 0; if (dvb_frontend_check_parameters(fe) < 0) return -EINVAL; /* * Initialize output parameters to match the values given by * the user. FE_SET_FRONTEND triggers an initial frontend event * with status = 0, which copies output parameters to userspace. */ dtv_property_legacy_params_sync(fe, c, &fepriv->parameters_out); /* * Be sure that the bandwidth will be filled for all * non-satellite systems, as tuners need to know what * low pass/Nyquist half filter should be applied, in * order to avoid inter-channel noise. * * ISDB-T and DVB-T/T2 already sets bandwidth. * ATSC and DVB-C don't set, so, the core should fill it. * * On DVB-C Annex A and C, the bandwidth is a function of * the roll-off and symbol rate. Annex B defines different * roll-off factors depending on the modulation. Fortunately, * Annex B is only used with 6MHz, so there's no need to * calculate it. * * While not officially supported, a side effect of handling it at * the cache level is that a program could retrieve the bandwidth * via DTV_BANDWIDTH_HZ, which may be useful for test programs. */ switch (c->delivery_system) { case SYS_ATSC: case SYS_DVBC_ANNEX_B: c->bandwidth_hz = 6000000; break; case SYS_DVBC_ANNEX_A: rolloff = 115; break; case SYS_DVBC_ANNEX_C: rolloff = 113; break; case SYS_DVBS: case SYS_TURBO: case SYS_ISDBS: rolloff = 135; break; case SYS_DVBS2: switch (c->rolloff) { case ROLLOFF_20: rolloff = 120; break; case ROLLOFF_25: rolloff = 125; break; default: case ROLLOFF_35: rolloff = 135; } break; default: break; } if (rolloff) c->bandwidth_hz = mult_frac(c->symbol_rate, rolloff, 100); /* force auto frequency inversion if requested */ if (dvb_force_auto_inversion) c->inversion = INVERSION_AUTO; /* * without hierarchical coding code_rate_LP is irrelevant, * so we tolerate the otherwise invalid FEC_NONE setting */ if (c->hierarchy == HIERARCHY_NONE && c->code_rate_LP == FEC_NONE) c->code_rate_LP = FEC_AUTO; /* get frontend-specific tuning settings */ memset(&fetunesettings, 0, sizeof(struct dvb_frontend_tune_settings)); if (fe->ops.get_tune_settings && (fe->ops.get_tune_settings(fe, &fetunesettings) == 0)) { fepriv->min_delay = (fetunesettings.min_delay_ms * HZ) / 1000; fepriv->max_drift = fetunesettings.max_drift; fepriv->step_size = fetunesettings.step_size; } else { /* default values */ switch (c->delivery_system) { case SYS_DVBS: case SYS_DVBS2: case SYS_ISDBS: case SYS_TURBO: case SYS_DVBC_ANNEX_A: case SYS_DVBC_ANNEX_C: fepriv->min_delay = HZ / 20; fepriv->step_size = c->symbol_rate / 16000; fepriv->max_drift = c->symbol_rate / 2000; break; case SYS_DVBT: case SYS_DVBT2: case SYS_ISDBT: case SYS_DTMB: fepriv->min_delay = HZ / 20; fepriv->step_size = fe->ops.info.frequency_stepsize * 2; fepriv->max_drift = (fe->ops.info.frequency_stepsize * 2) + 1; break; default: /* * FIXME: This sounds wrong! if freqency_stepsize is * defined by the frontend, why not use it??? */ fepriv->min_delay = HZ / 20; fepriv->step_size = 0; /* no zigzag */ fepriv->max_drift = 0; break; } } if (dvb_override_tune_delay > 0) fepriv->min_delay = (dvb_override_tune_delay * HZ) / 1000; fepriv->state = FESTATE_RETUNE; /* Request the search algorithm to search */ fepriv->algo_status |= DVBFE_ALGO_SEARCH_AGAIN; dvb_frontend_clear_events(fe); dvb_frontend_add_event(fe, 0); dvb_frontend_wakeup(fe); fepriv->status = 0; return 0; } static int dvb_frontend_ioctl_legacy(struct file *file, unsigned int cmd, void *parg) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dtv_frontend_properties *c = &fe->dtv_property_cache; int err = -EOPNOTSUPP; switch (cmd) { case FE_GET_INFO: { struct dvb_frontend_info* info = parg; memcpy(info, &fe->ops.info, sizeof(struct dvb_frontend_info)); dvb_frontend_get_frequency_limits(fe, &info->frequency_min, &info->frequency_max); /* * Associate the 4 delivery systems supported by DVBv3 * API with their DVBv5 counterpart. For the other standards, * use the closest type, assuming that it would hopefully * work with a DVBv3 application. * It should be noticed that, on multi-frontend devices with * different types (terrestrial and cable, for example), * a pure DVBv3 application won't be able to use all delivery * systems. Yet, changing the DVBv5 cache to the other delivery * system should be enough for making it work. */ switch (dvbv3_type(c->delivery_system)) { case DVBV3_QPSK: info->type = FE_QPSK; break; case DVBV3_ATSC: info->type = FE_ATSC; break; case DVBV3_QAM: info->type = FE_QAM; break; case DVBV3_OFDM: info->type = FE_OFDM; break; default: dev_err(fe->dvb->device, "%s: doesn't know how to handle a DVBv3 call to delivery system %i\n", __func__, c->delivery_system); fe->ops.info.type = FE_OFDM; } dev_dbg(fe->dvb->device, "%s: current delivery system on cache: %d, V3 type: %d\n", __func__, c->delivery_system, fe->ops.info.type); /* Set CAN_INVERSION_AUTO bit on in other than oneshot mode */ if (!(fepriv->tune_mode_flags & FE_TUNE_MODE_ONESHOT)) info->caps |= FE_CAN_INVERSION_AUTO; err = 0; break; } case FE_READ_STATUS: { enum fe_status *status = parg; /* if retune was requested but hasn't occurred yet, prevent * that user get signal state from previous tuning */ if (fepriv->state == FESTATE_RETUNE || fepriv->state == FESTATE_ERROR) { err=0; *status = 0; break; } if (fe->ops.read_status) err = fe->ops.read_status(fe, status); break; } case FE_READ_BER: if (fe->ops.read_ber) { if (fepriv->thread) err = fe->ops.read_ber(fe, (__u32 *) parg); else err = -EAGAIN; } break; case FE_READ_SIGNAL_STRENGTH: if (fe->ops.read_signal_strength) { if (fepriv->thread) err = fe->ops.read_signal_strength(fe, (__u16 *) parg); else err = -EAGAIN; } break; case FE_READ_SNR: if (fe->ops.read_snr) { if (fepriv->thread) err = fe->ops.read_snr(fe, (__u16 *) parg); else err = -EAGAIN; } break; case FE_READ_UNCORRECTED_BLOCKS: if (fe->ops.read_ucblocks) { if (fepriv->thread) err = fe->ops.read_ucblocks(fe, (__u32 *) parg); else err = -EAGAIN; } break; case FE_DISEQC_RESET_OVERLOAD: if (fe->ops.diseqc_reset_overload) { err = fe->ops.diseqc_reset_overload(fe); fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_DISEQC_SEND_MASTER_CMD: if (fe->ops.diseqc_send_master_cmd) { struct dvb_diseqc_master_cmd *cmd = parg; if (cmd->msg_len > sizeof(cmd->msg)) { err = -EINVAL; break; } err = fe->ops.diseqc_send_master_cmd(fe, cmd); fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_DISEQC_SEND_BURST: if (fe->ops.diseqc_send_burst) { err = fe->ops.diseqc_send_burst(fe, (enum fe_sec_mini_cmd)parg); fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_SET_TONE: if (fe->ops.set_tone) { err = fe->ops.set_tone(fe, (enum fe_sec_tone_mode)parg); fepriv->tone = (enum fe_sec_tone_mode)parg; fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_SET_VOLTAGE: if (fe->ops.set_voltage) { err = fe->ops.set_voltage(fe, (enum fe_sec_voltage)parg); fepriv->voltage = (enum fe_sec_voltage)parg; fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_DISHNETWORK_SEND_LEGACY_CMD: if (fe->ops.dishnetwork_send_legacy_command) { err = fe->ops.dishnetwork_send_legacy_command(fe, (unsigned long)parg); fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } else if (fe->ops.set_voltage) { /* * NOTE: This is a fallback condition. Some frontends * (stv0299 for instance) take longer than 8msec to * respond to a set_voltage command. Those switches * need custom routines to switch properly. For all * other frontends, the following should work ok. * Dish network legacy switches (as used by Dish500) * are controlled by sending 9-bit command words * spaced 8msec apart. * the actual command word is switch/port dependent * so it is up to the userspace application to send * the right command. * The command must always start with a '0' after * initialization, so parg is 8 bits and does not * include the initialization or start bit */ unsigned long swcmd = ((unsigned long) parg) << 1; ktime_t nexttime; ktime_t tv[10]; int i; u8 last = 1; if (dvb_frontend_debug) printk("%s switch command: 0x%04lx\n", __func__, swcmd); nexttime = ktime_get_boottime(); if (dvb_frontend_debug) tv[0] = nexttime; /* before sending a command, initialize by sending * a 32ms 18V to the switch */ fe->ops.set_voltage(fe, SEC_VOLTAGE_18); dvb_frontend_sleep_until(&nexttime, 32000); for (i = 0; i < 9; i++) { if (dvb_frontend_debug) tv[i+1] = ktime_get_boottime(); if ((swcmd & 0x01) != last) { /* set voltage to (last ? 13V : 18V) */ fe->ops.set_voltage(fe, (last) ? SEC_VOLTAGE_13 : SEC_VOLTAGE_18); last = (last) ? 0 : 1; } swcmd = swcmd >> 1; if (i != 8) dvb_frontend_sleep_until(&nexttime, 8000); } if (dvb_frontend_debug) { printk("%s(%d): switch delay (should be 32k followed by all 8k\n", __func__, fe->dvb->num); for (i = 1; i < 10; i++) printk("%d: %d\n", i, (int) ktime_us_delta(tv[i], tv[i-1])); } err = 0; fepriv->state = FESTATE_DISEQC; fepriv->status = 0; } break; case FE_DISEQC_RECV_SLAVE_REPLY: if (fe->ops.diseqc_recv_slave_reply) err = fe->ops.diseqc_recv_slave_reply(fe, (struct dvb_diseqc_slave_reply*) parg); break; case FE_ENABLE_HIGH_LNB_VOLTAGE: if (fe->ops.enable_high_lnb_voltage) err = fe->ops.enable_high_lnb_voltage(fe, (long) parg); break; case FE_SET_FRONTEND: err = dvbv3_set_delivery_system(fe); if (err) break; err = dtv_property_cache_sync(fe, c, parg); if (err) break; err = dtv_set_frontend(fe); break; case FE_GET_EVENT: err = dvb_frontend_get_event (fe, parg, file->f_flags); break; case FE_GET_FRONTEND: { struct dtv_frontend_properties getp = fe->dtv_property_cache; /* * Let's use our own copy of property cache, in order to * avoid mangling with DTV zigzag logic, as drivers might * return crap, if they don't check if the data is available * before updating the properties cache. */ err = dtv_get_frontend(fe, &getp, parg); break; } case FE_SET_FRONTEND_TUNE_MODE: fepriv->tune_mode_flags = (unsigned long) parg; err = 0; break; } return err; } static unsigned int dvb_frontend_poll(struct file *file, struct poll_table_struct *wait) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dvb_frontend_private *fepriv = fe->frontend_priv; dev_dbg_ratelimited(fe->dvb->device, "%s:\n", __func__); poll_wait (file, &fepriv->events.wait_queue, wait); if (fepriv->events.eventw != fepriv->events.eventr) return (POLLIN | POLLRDNORM | POLLPRI); return 0; } static int dvb_frontend_open(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dvb_frontend_private *fepriv = fe->frontend_priv; struct dvb_adapter *adapter = fe->dvb; int ret; dev_dbg(fe->dvb->device, "%s:\n", __func__); if (fe->exit == DVB_FE_DEVICE_REMOVED) return -ENODEV; if (adapter->mfe_shared) { mutex_lock (&adapter->mfe_lock); if (adapter->mfe_dvbdev == NULL) adapter->mfe_dvbdev = dvbdev; else if (adapter->mfe_dvbdev != dvbdev) { struct dvb_device *mfedev = adapter->mfe_dvbdev; struct dvb_frontend *mfe = mfedev->priv; struct dvb_frontend_private *mfepriv = mfe->frontend_priv; int mferetry = (dvb_mfe_wait_time << 1); mutex_unlock (&adapter->mfe_lock); while (mferetry-- && (mfedev->users != -1 || mfepriv->thread != NULL)) { if(msleep_interruptible(500)) { if(signal_pending(current)) return -EINTR; } } mutex_lock (&adapter->mfe_lock); if(adapter->mfe_dvbdev != dvbdev) { mfedev = adapter->mfe_dvbdev; mfe = mfedev->priv; mfepriv = mfe->frontend_priv; if (mfedev->users != -1 || mfepriv->thread != NULL) { mutex_unlock (&adapter->mfe_lock); return -EBUSY; } adapter->mfe_dvbdev = dvbdev; } } } if (dvbdev->users == -1 && fe->ops.ts_bus_ctrl) { if ((ret = fe->ops.ts_bus_ctrl(fe, 1)) < 0) goto err0; /* If we took control of the bus, we need to force reinitialization. This is because many ts_bus_ctrl() functions strobe the RESET pin on the demod, and if the frontend thread already exists then the dvb_init() routine won't get called (which is what usually does initial register configuration). */ fepriv->reinitialise = 1; } if ((ret = dvb_generic_open (inode, file)) < 0) goto err1; if ((file->f_flags & O_ACCMODE) != O_RDONLY) { /* normal tune mode when opened R/W */ fepriv->tune_mode_flags &= ~FE_TUNE_MODE_ONESHOT; fepriv->tone = -1; fepriv->voltage = -1; #ifdef CONFIG_MEDIA_CONTROLLER_DVB if (fe->dvb->mdev && fe->dvb->mdev->enable_source) { ret = fe->dvb->mdev->enable_source(dvbdev->entity, &fepriv->pipe); if (ret) { dev_err(fe->dvb->device, "Tuner is busy. Error %d\n", ret); goto err2; } } #endif ret = dvb_frontend_start (fe); if (ret) goto err3; /* empty event queue */ fepriv->events.eventr = fepriv->events.eventw = 0; } dvb_frontend_private_get(fepriv); if (adapter->mfe_shared) mutex_unlock (&adapter->mfe_lock); return ret; err3: #ifdef CONFIG_MEDIA_CONTROLLER_DVB if (fe->dvb->mdev && fe->dvb->mdev->disable_source) fe->dvb->mdev->disable_source(dvbdev->entity); err2: #endif dvb_generic_release(inode, file); err1: if (dvbdev->users == -1 && fe->ops.ts_bus_ctrl) fe->ops.ts_bus_ctrl(fe, 0); err0: if (adapter->mfe_shared) mutex_unlock (&adapter->mfe_lock); return ret; } static int dvb_frontend_release(struct inode *inode, struct file *file) { struct dvb_device *dvbdev = file->private_data; struct dvb_frontend *fe = dvbdev->priv; struct dvb_frontend_private *fepriv = fe->frontend_priv; int ret; dev_dbg(fe->dvb->device, "%s:\n", __func__); if ((file->f_flags & O_ACCMODE) != O_RDONLY) { fepriv->release_jiffies = jiffies; mb(); } ret = dvb_generic_release (inode, file); if (dvbdev->users == -1) { wake_up(&fepriv->wait_queue); #ifdef CONFIG_MEDIA_CONTROLLER_DVB if (fe->dvb->mdev && fe->dvb->mdev->disable_source) fe->dvb->mdev->disable_source(dvbdev->entity); #endif if (fe->exit != DVB_FE_NO_EXIT) wake_up(&dvbdev->wait_queue); if (fe->ops.ts_bus_ctrl) fe->ops.ts_bus_ctrl(fe, 0); } dvb_frontend_private_put(fepriv); return ret; } static const struct file_operations dvb_frontend_fops = { .owner = THIS_MODULE, .unlocked_ioctl = dvb_generic_ioctl, .poll = dvb_frontend_poll, .open = dvb_frontend_open, .release = dvb_frontend_release, .llseek = noop_llseek, }; int dvb_frontend_suspend(struct dvb_frontend *fe) { int ret = 0; dev_dbg(fe->dvb->device, "%s: adap=%d fe=%d\n", __func__, fe->dvb->num, fe->id); if (fe->ops.tuner_ops.suspend) ret = fe->ops.tuner_ops.suspend(fe); else if (fe->ops.tuner_ops.sleep) ret = fe->ops.tuner_ops.sleep(fe); if (fe->ops.sleep) ret = fe->ops.sleep(fe); return ret; } EXPORT_SYMBOL(dvb_frontend_suspend); int dvb_frontend_resume(struct dvb_frontend *fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; int ret = 0; dev_dbg(fe->dvb->device, "%s: adap=%d fe=%d\n", __func__, fe->dvb->num, fe->id); fe->exit = DVB_FE_DEVICE_RESUME; if (fe->ops.init) ret = fe->ops.init(fe); if (fe->ops.tuner_ops.resume) ret = fe->ops.tuner_ops.resume(fe); else if (fe->ops.tuner_ops.init) ret = fe->ops.tuner_ops.init(fe); if (fe->ops.set_tone && fepriv->tone != -1) fe->ops.set_tone(fe, fepriv->tone); if (fe->ops.set_voltage && fepriv->voltage != -1) fe->ops.set_voltage(fe, fepriv->voltage); fe->exit = DVB_FE_NO_EXIT; fepriv->state = FESTATE_RETUNE; dvb_frontend_wakeup(fe); return ret; } EXPORT_SYMBOL(dvb_frontend_resume); int dvb_register_frontend(struct dvb_adapter* dvb, struct dvb_frontend* fe) { struct dvb_frontend_private *fepriv; const struct dvb_device dvbdev_template = { .users = ~0, .writers = 1, .readers = (~0)-1, .fops = &dvb_frontend_fops, #if defined(CONFIG_MEDIA_CONTROLLER_DVB) .name = fe->ops.info.name, #endif .kernel_ioctl = dvb_frontend_ioctl }; dev_dbg(dvb->device, "%s:\n", __func__); if (mutex_lock_interruptible(&frontend_mutex)) return -ERESTARTSYS; fe->frontend_priv = kzalloc(sizeof(struct dvb_frontend_private), GFP_KERNEL); if (fe->frontend_priv == NULL) { mutex_unlock(&frontend_mutex); return -ENOMEM; } fepriv = fe->frontend_priv; kref_init(&fepriv->refcount); sema_init(&fepriv->sem, 1); init_waitqueue_head (&fepriv->wait_queue); init_waitqueue_head (&fepriv->events.wait_queue); mutex_init(&fepriv->events.mtx); fe->dvb = dvb; fepriv->inversion = INVERSION_OFF; dev_info(fe->dvb->device, "DVB: registering adapter %i frontend %i (%s)...\n", fe->dvb->num, fe->id, fe->ops.info.name); dvb_register_device (fe->dvb, &fepriv->dvbdev, &dvbdev_template, fe, DVB_DEVICE_FRONTEND, 0); /* * Initialize the cache to the proper values according with the * first supported delivery system (ops->delsys[0]) */ fe->dtv_property_cache.delivery_system = fe->ops.delsys[0]; dvb_frontend_clear_cache(fe); mutex_unlock(&frontend_mutex); return 0; } EXPORT_SYMBOL(dvb_register_frontend); int dvb_unregister_frontend(struct dvb_frontend* fe) { struct dvb_frontend_private *fepriv = fe->frontend_priv; dev_dbg(fe->dvb->device, "%s:\n", __func__); mutex_lock(&frontend_mutex); dvb_frontend_stop (fe); dvb_unregister_device (fepriv->dvbdev); /* fe is invalid now */ mutex_unlock(&frontend_mutex); dvb_frontend_private_put(fepriv); return 0; } EXPORT_SYMBOL(dvb_unregister_frontend); #ifdef CONFIG_MEDIA_ATTACH void dvb_frontend_detach(struct dvb_frontend* fe) { void *ptr; if (fe->ops.release_sec) { fe->ops.release_sec(fe); dvb_detach(fe->ops.release_sec); } if (fe->ops.tuner_ops.release) { fe->ops.tuner_ops.release(fe); dvb_detach(fe->ops.tuner_ops.release); } if (fe->ops.analog_ops.release) { fe->ops.analog_ops.release(fe); dvb_detach(fe->ops.analog_ops.release); } ptr = (void*)fe->ops.release; if (ptr) { fe->ops.release(fe); dvb_detach(ptr); } } #else void dvb_frontend_detach(struct dvb_frontend* fe) { if (fe->ops.release_sec) fe->ops.release_sec(fe); if (fe->ops.tuner_ops.release) fe->ops.tuner_ops.release(fe); if (fe->ops.analog_ops.release) fe->ops.analog_ops.release(fe); if (fe->ops.release) fe->ops.release(fe); } #endif EXPORT_SYMBOL(dvb_frontend_detach);
/***************************************************************************/ /* * linux/arch/m68knommu/platform/523x/config.c * * Sub-architcture dependent initialization code for the Freescale * 523x CPUs. * * Copyright (C) 1999-2005, Greg Ungerer (gerg@snapgear.com) * Copyright (C) 2001-2003, SnapGear Inc. (www.snapgear.com) */ /***************************************************************************/ #include <linux/kernel.h> #include <linux/param.h> #include <linux/init.h> #include <linux/io.h> #include <asm/machdep.h> #include <asm/coldfire.h> #include <asm/mcfsim.h> #include <asm/mcfgpio.h> /***************************************************************************/ struct mcf_gpio_chip mcf_gpio_chips[] = { MCFGPS(PIRQ, 1, 7, MCFEPORT_EPDDR, MCFEPORT_EPDR, MCFEPORT_EPPDR), MCFGPF(ADDR, 13, 3), MCFGPF(DATAH, 16, 8), MCFGPF(DATAL, 24, 8), MCFGPF(BUSCTL, 32, 8), MCFGPF(BS, 40, 4), MCFGPF(CS, 49, 7), MCFGPF(SDRAM, 56, 6), MCFGPF(FECI2C, 64, 4), MCFGPF(UARTH, 72, 2), MCFGPF(UARTL, 80, 8), MCFGPF(QSPI, 88, 5), MCFGPF(TIMER, 96, 8), MCFGPF(ETPU, 104, 3), }; unsigned int mcf_gpio_chips_size = ARRAY_SIZE(mcf_gpio_chips); /***************************************************************************/ #if IS_ENABLED(CONFIG_SPI_COLDFIRE_QSPI) static void __init m523x_qspi_init(void) { u16 par; /* setup QSPS pins for QSPI with gpio CS control */ writeb(0x1f, MCFGPIO_PAR_QSPI); /* and CS2 & CS3 as gpio */ par = readw(MCFGPIO_PAR_TIMER); par &= 0x3f3f; writew(par, MCFGPIO_PAR_TIMER); } #endif /* IS_ENABLED(CONFIG_SPI_COLDFIRE_QSPI) */ /***************************************************************************/ static void __init m523x_fec_init(void) { u16 par; u8 v; /* Set multi-function pins to ethernet use */ par = readw(MCF_IPSBAR + 0x100082); writew(par | 0xf00, MCF_IPSBAR + 0x100082); v = readb(MCF_IPSBAR + 0x100078); writeb(v | 0xc0, MCF_IPSBAR + 0x100078); } /***************************************************************************/ void __init config_BSP(char *commandp, int size) { mach_sched_init = hw_timer_init; m523x_fec_init(); #if IS_ENABLED(CONFIG_SPI_COLDFIRE_QSPI) m523x_qspi_init(); #endif } /***************************************************************************/
@echo off rem Licensed to the Apache Software Foundation (ASF) under one or more rem contributor license agreements. See the NOTICE file distributed with rem this work for additional information regarding copyright ownership. rem The ASF licenses this file to You under the Apache License, Version 2.0 rem (the "License"); you may not use this file except in compliance with rem the License. You may obtain a copy of the License at rem rem http://www.apache.org/licenses/LICENSE-2.0 rem rem Unless required by applicable law or agreed to in writing, software rem distributed under the License is distributed on an "AS IS" BASIS, rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. rem See the License for the specific language governing permissions and rem limitations under the License. rem ============================================ rem Non-GUI version of JMETER.BAT (WinNT/2K only) rem rem Drop a JMX file on this batch script, and it rem will run it in non-GUI mode, with a log file rem formed from the input file name but with the rem extension .jtl rem rem Only the first parameter is used. rem Only works for Win2k. rem rem ============================================ if "%OS%"=="Windows_NT" goto WinNT echo "Sorry, this command file requires Windows NT/ 2000 / XP" pause goto END :WinNT rem Check file is supplied if a == a%1 goto winNT2 rem Allow special name LAST if LAST == %1 goto winNT3 rem Check it has extension .jmx if "%~x1" == ".jmx" goto winNT3 :winNT2 echo Please supply a script name with the extension .jmx pause goto END :winNT3 rem Change to script directory pushd %~dp1 rem use same directory to find jmeter script call "%~dp0"jmeter -n -t "%~nx1" -j "%~n1.log" -l "%~n1.jtl" %2 %3 %4 %5 %6 %7 %8 %9 popd :END
VectorCanvas.prototype.createPath = function (config) { var node; if (this.mode === 'svg') { node = this.createSvgNode('path'); node.setAttribute('d', config.path); if (this.params.borderColor !== null) { node.setAttribute('stroke', this.params.borderColor); } if (this.params.borderWidth > 0) { node.setAttribute('stroke-width', this.params.borderWidth); node.setAttribute('stroke-linecap', 'round'); node.setAttribute('stroke-linejoin', 'round'); } if (this.params.borderOpacity > 0) { node.setAttribute('stroke-opacity', this.params.borderOpacity); } node.setFill = function (color) { this.setAttribute('fill', color); if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getAttribute('fill'); }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.setAttribute('fill-opacity', opacity); }; } else { node = this.createVmlNode('shape'); node.coordorigin = '0 0'; node.coordsize = this.width + ' ' + this.height; node.style.width = this.width + 'px'; node.style.height = this.height + 'px'; node.fillcolor = JQVMap.defaultFillColor; node.stroked = false; node.path = VectorCanvas.pathSvgToVml(config.path); var scale = this.createVmlNode('skew'); scale.on = true; scale.matrix = '0.01,0,0,0.01,0,0'; scale.offset = '0,0'; node.appendChild(scale); var fill = this.createVmlNode('fill'); node.appendChild(fill); node.setFill = function (color) { this.getElementsByTagName('fill')[0].color = color; if (this.getAttribute('original') === null) { this.setAttribute('original', color); } }; node.getFill = function () { return this.getElementsByTagName('fill')[0].color; }; node.getOriginalFill = function () { return this.getAttribute('original'); }; node.setOpacity = function (opacity) { this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%'; }; } return node; };
class Scriptcs < Formula desc "Tools to write and execute C#" homepage "https://github.com/scriptcs/scriptcs" url "https://github.com/scriptcs/scriptcs/archive/v0.15.0.tar.gz" sha256 "658d4ef2c23253ba1d2717c947d2985cb506ce69425280ee8e62cc50d15d6803" bottle do cellar :any sha256 "dfead67e3f9fbdb499b480eb2b29d651010b1815ef5fe0425affd4ce07295739" => :yosemite sha256 "eec5baf497fc37444fc37adf7c7c761011bb50059f21ccaf10620f0887e759f6" => :mavericks sha256 "206b8fd283ab15e49c91941c2dad77950adb5a9642bb8563a530f4a79d2ccaf3" => :mountain_lion end depends_on "mono" => :recommended def install script_file = "scriptcs.sh" system "./build.sh" libexec.install Dir["src/ScriptCs/bin/Release/*"] (libexec/script_file).write <<-EOS.undent #!/bin/bash mono #{libexec}/scriptcs.exe $@ EOS (libexec/script_file).chmod 0755 bin.install_symlink libexec/script_file => "scriptcs" end test do test_file = "tests.csx" (testpath/test_file).write('Console.WriteLine("{0}, {1}!", "Hello", "world");') assert_equal "Hello, world!", `scriptcs #{test_file}`.strip end end
/* * Copyright (c) 2005-2009 Brocade Communications Systems, Inc. * All rights reserved * www.brocade.com * * Linux driver for Brocade Fibre Channel Host Bus Adapter. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) Version 2 as * published by the Free Software Foundation * * 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. */ #ifndef __BFA_PORT_PRIV_H__ #define __BFA_PORT_PRIV_H__ #include <defs/bfa_defs_pport.h> #include <bfi/bfi_pport.h> #include "bfa_intr_priv.h" /** * Link notification data structure */ struct bfa_fcport_ln_s { struct bfa_fcport_s *fcport; bfa_sm_t sm; struct bfa_cb_qe_s ln_qe; /* BFA callback queue elem for ln */ enum bfa_pport_linkstate ln_event; /* ln event for callback */ }; /** * BFA FC port data structure */ struct bfa_fcport_s { struct bfa_s *bfa; /* parent BFA instance */ bfa_sm_t sm; /* port state machine */ wwn_t nwwn; /* node wwn of physical port */ wwn_t pwwn; /* port wwn of physical oprt */ enum bfa_pport_speed speed_sup; /* supported speeds */ enum bfa_pport_speed speed; /* current speed */ enum bfa_pport_topology topology; /* current topology */ u8 myalpa; /* my ALPA in LOOP topology */ u8 rsvd[3]; u32 mypid:24; u32 rsvd_b:8; struct bfa_pport_cfg_s cfg; /* current port configuration */ struct bfa_qos_attr_s qos_attr; /* QoS Attributes */ struct bfa_qos_vc_attr_s qos_vc_attr; /* VC info from ELP */ struct bfa_reqq_wait_s reqq_wait; /* to wait for room in reqq */ struct bfa_reqq_wait_s svcreq_wait; /* to wait for room in reqq */ struct bfa_reqq_wait_s stats_reqq_wait; /* to wait for room in reqq (stats) */ void *event_cbarg; void (*event_cbfn) (void *cbarg, bfa_pport_event_t event); union { union bfi_fcport_i2h_msg_u i2hmsg; } event_arg; void *bfad; /* BFA driver handle */ struct bfa_fcport_ln_s ln; /* Link Notification */ struct bfa_cb_qe_s hcb_qe; /* BFA callback queue elem */ struct bfa_timer_s timer; /* timer */ u32 msgtag; /* fimrware msg tag for reply */ u8 *stats_kva; u64 stats_pa; union bfa_fcport_stats_u *stats; union bfa_fcport_stats_u *stats_ret; /* driver stats location */ bfa_status_t stats_status; /* stats/statsclr status */ bfa_boolean_t stats_busy; /* outstanding stats/statsclr */ bfa_boolean_t stats_qfull; bfa_cb_pport_t stats_cbfn; /* driver callback function */ void *stats_cbarg; /* *!< user callback arg */ bfa_boolean_t diag_busy; /* diag busy status */ bfa_boolean_t beacon; /* port beacon status */ bfa_boolean_t link_e2e_beacon; /* link beacon status */ }; #define BFA_FCPORT_MOD(__bfa) (&(__bfa)->modules.fcport) /* * public functions */ void bfa_fcport_isr(struct bfa_s *bfa, struct bfi_msg_s *msg); #endif /* __BFA_PORT_PRIV_H__ */
/** * jQuery plugin wrapper for TinySort * Does not use the first argument in tinysort.js since that is handled internally by the jQuery selector. * Sub-selections (option.selector) do not use the jQuery selector syntax but regular CSS3 selector syntax. * @summary jQuery plugin wrapper for TinySort * @version 2.2.2 * @requires tinysort * @license MIT/GPL * @author Ron Valstar (http://www.sjeiti.com/) * @copyright Ron Valstar <ron@ronvalstar.nl> */ !function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery","tinysort"],a):jQuery&&!jQuery.fn.tsort&&a(jQuery,tinysort)}(function(a,b){"use strict";a.tinysort={defaults:b.defaults},a.fn.extend({tinysort:function(){var a,c,d=Array.prototype.slice.call(arguments);d.unshift(this),a=b.apply(null,d),c=a.length;for(var e=0,f=this.length;f>e;e++)c>e?this[e]=a[e]:delete this[e];return this.length=c,this}}),a.fn.tsort=a.fn.tinysort});
#include QMK_KEYBOARD_H const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { [0] = LAYOUT_all( KC_ESC, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, KC_MINS, KC_EQL, KC_BSPC, KC_BSLS, KC_INS, KC_TAB, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_LBRC, KC_RBRC, KC_BSLS, KC_DEL, KC_LCTL, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCLN, KC_QUOT, KC_BSLS, KC_ENT, KC_PGUP, KC_LSFT, KC_NUBS, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLSH, KC_RSFT, KC_UP, KC_PGDN, KC_CAPS, KC_LGUI, KC_LALT, KC_SPC, KC_RALT, KC_RCTRL,MO(2), KC_LEFT, KC_DOWN, KC_RGHT), [1] = LAYOUT_all( KC_GRV, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, KC_F11, KC_F12, _______, _______, KC_PSCR, _______, _______, _______, _______, _______, _______, _______, _______, KC_UP, _______, _______, _______, _______, _______, KC_INS, _______, _______, _______, _______, _______, _______, _______, KC_LEFT, KC_DOWN, KC_RGHT, _______, _______, _______, _______, KC_HOME, _______, _______, _______, _______, _______, _______, _______, _______, _______, KC_VOLD, KC_VOLU, KC_MUTE, _______, _______, KC_END, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), [2] = LAYOUT_all( _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), [3] = LAYOUT_all( _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______, _______), };
/* SPDX-License-Identifier: GPL-2.0-only */ /* * PCM3008 ALSA SoC Layer * * Author: Hugo Villeneuve * Copyright (C) 2008 Lyrtech inc */ #ifndef __LINUX_SND_SOC_PCM3008_H #define __LINUX_SND_SOC_PCM3008_H struct pcm3008_setup_data { unsigned dem0_pin; unsigned dem1_pin; unsigned pdad_pin; unsigned pdda_pin; }; #endif
/* Copyright 1996,2002 Gregory D. Hager, Alfred A. Rizzi, Noah J. Cowan, Jason Lapenta, Scott Smedley This file is part of the DT3155 Device Driver. The DT3155 Device Driver 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 DT3155 Device Driver 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 DT3155 Device Driver; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- Changes -- Date Programmer Description of changes made ------------------------------------------------------------------- 24-Jul-2002 SS GPL licence. */ /* This code is a modified version of examples provided by Data Translations.*/ #ifndef DT3155_IO_INC #define DT3155_IO_INC /* macros to access registers */ #define WriteMReg(Address, Data) (*((u32 *)(Address)) = Data) #define ReadMReg(Address, Data) (Data = *((u32 *)(Address))) /***************** 32 bit register globals **************/ /* offsets for 32-bit memory mapped registers */ #define EVEN_DMA_START 0x000 #define ODD_DMA_START 0x00C #define EVEN_DMA_STRIDE 0x018 #define ODD_DMA_STRIDE 0x024 #define EVEN_PIXEL_FMT 0x030 #define ODD_PIXEL_FMT 0x034 #define FIFO_TRIGGER 0x038 #define XFER_MODE 0x03C #define CSR1 0x040 #define RETRY_WAIT_CNT 0x044 #define INT_CSR 0x048 #define EVEN_FLD_MASK 0x04C #define ODD_FLD_MASK 0x050 #define MASK_LENGTH 0x054 #define FIFO_FLAG_CNT 0x058 #define IIC_CLK_DUR 0x05C #define IIC_CSR1 0x060 #define IIC_CSR2 0x064 #define EVEN_DMA_UPPR_LMT 0x08C #define ODD_DMA_UPPR_LMT 0x090 #define CLK_DUR_VAL 0x01010101 /******** Assignments and Typedefs for 32 bit Memory Mapped Registers ********/ typedef union fifo_trigger_tag { u32 reg; struct { u32 PACKED:6; u32 :9; u32 PLANER:7; u32 :9; } fld; } FIFO_TRIGGER_R; typedef union xfer_mode_tag { u32 reg; struct { u32 :2; u32 FIELD_TOGGLE:1; u32 :5; u32 :2; u32 :22; } fld; } XFER_MODE_R; typedef union csr1_tag { u32 reg; struct { u32 CAP_CONT_EVE:1; u32 CAP_CONT_ODD:1; u32 CAP_SNGL_EVE:1; u32 CAP_SNGL_ODD:1; u32 FLD_DN_EVE :1; u32 FLD_DN_ODD :1; u32 SRST :1; u32 FIFO_EN :1; u32 FLD_CRPT_EVE:1; u32 FLD_CRPT_ODD:1; u32 ADDR_ERR_EVE:1; u32 ADDR_ERR_ODD:1; u32 CRPT_DIS :1; u32 RANGE_EN :1; u32 :16; } fld; } CSR1_R; typedef union retry_wait_cnt_tag { u32 reg; struct { u32 RTRY_WAIT_CNT:8; u32 :24; } fld; } RETRY_WAIT_CNT_R; typedef union int_csr_tag { u32 reg; struct { u32 FLD_END_EVE :1; u32 FLD_END_ODD :1; u32 FLD_START :1; u32 :5; u32 FLD_END_EVE_EN:1; u32 FLD_END_ODD_EN:1; u32 FLD_START_EN :1; u32 :21; } fld; } INT_CSR_R; typedef union mask_length_tag { u32 reg; struct { u32 MASK_LEN_EVE:5; u32 :11; u32 MASK_LEN_ODD:5; u32 :11; } fld; } MASK_LENGTH_R; typedef union fifo_flag_cnt_tag { u32 reg; struct { u32 AF_COUNT:7; u32 :9; u32 AE_COUNT:7; u32 :9; } fld; } FIFO_FLAG_CNT_R; typedef union iic_clk_dur { u32 reg; struct { u32 PHASE_1:8; u32 PHASE_2:8; u32 PHASE_3:8; u32 PHASE_4:8; } fld; } IIC_CLK_DUR_R; typedef union iic_csr1_tag { u32 reg; struct { u32 AUTO_EN :1; u32 BYPASS :1; u32 SDA_OUT :1; u32 SCL_OUT :1; u32 :4; u32 AUTO_ABORT :1; u32 DIRECT_ABORT:1; u32 SDA_IN :1; u32 SCL_IN :1; u32 :4; u32 AUTO_ADDR :8; u32 RD_DATA :8; } fld; } IIC_CSR1_R; /********************************** * iic_csr2_tag */ typedef union iic_csr2_tag { u32 reg; struct { u32 DIR_WR_DATA :8; u32 DIR_SUB_ADDR:8; u32 DIR_RD :1; u32 DIR_ADDR :7; u32 NEW_CYCLE :1; u32 :7; } fld; } IIC_CSR2_R; /* use for both EVEN and ODD DMA UPPER LIMITS */ /* * dma_upper_lmt_tag */ typedef union dma_upper_lmt_tag { u32 reg; struct { u32 DMA_UPPER_LMT_VAL:24; u32 :8; } fld; } DMA_UPPER_LMT_R; /* * Global declarations of local copies of boards' 32 bit registers */ extern u32 even_dma_start_r; /* bit 0 should always be 0 */ extern u32 odd_dma_start_r; /* .. */ extern u32 even_dma_stride_r; /* bits 0&1 should always be 0 */ extern u32 odd_dma_stride_r; /* .. */ extern u32 even_pixel_fmt_r; extern u32 odd_pixel_fmt_r; extern FIFO_TRIGGER_R fifo_trigger_r; extern XFER_MODE_R xfer_mode_r; extern CSR1_R csr1_r; extern RETRY_WAIT_CNT_R retry_wait_cnt_r; extern INT_CSR_R int_csr_r; extern u32 even_fld_mask_r; extern u32 odd_fld_mask_r; extern MASK_LENGTH_R mask_length_r; extern FIFO_FLAG_CNT_R fifo_flag_cnt_r; extern IIC_CLK_DUR_R iic_clk_dur_r; extern IIC_CSR1_R iic_csr1_r; extern IIC_CSR2_R iic_csr2_r; extern DMA_UPPER_LMT_R even_dma_upper_lmt_r; extern DMA_UPPER_LMT_R odd_dma_upper_lmt_r; /***************** 8 bit I2C register globals ***********/ #define CSR2 0x010 /* indices of 8-bit I2C mapped reg's*/ #define EVEN_CSR 0x011 #define ODD_CSR 0x012 #define CONFIG 0x013 #define DT_ID 0x01F #define X_CLIP_START 0x020 #define Y_CLIP_START 0x022 #define X_CLIP_END 0x024 #define Y_CLIP_END 0x026 #define AD_ADDR 0x030 #define AD_LUT 0x031 #define AD_CMD 0x032 #define DIG_OUT 0x040 #define PM_LUT_ADDR 0x050 #define PM_LUT_DATA 0x051 /******** Assignments and Typedefs for 8 bit I2C Registers********************/ typedef union i2c_csr2_tag { u8 reg; struct { u8 CHROM_FIL:1; u8 SYNC_SNTL:1; u8 HZ50:1; u8 SYNC_PRESENT:1; u8 BUSY_EVE:1; u8 BUSY_ODD:1; u8 DISP_PASS:1; } fld; } I2C_CSR2; typedef union i2c_even_csr_tag { u8 reg; struct { u8 DONE_EVE :1; u8 SNGL_EVE :1; u8 ERROR_EVE:1; u8 :5; } fld; } I2C_EVEN_CSR; typedef union i2c_odd_csr_tag { u8 reg; struct { u8 DONE_ODD:1; u8 SNGL_ODD:1; u8 ERROR_ODD:1; u8 :5; } fld; } I2C_ODD_CSR; typedef union i2c_config_tag { u8 reg; struct { u8 ACQ_MODE:2; u8 EXT_TRIG_EN:1; u8 EXT_TRIG_POL:1; u8 H_SCALE:1; u8 CLIP:1; u8 PM_LUT_SEL:1; u8 PM_LUT_PGM:1; } fld; } I2C_CONFIG; typedef union i2c_ad_cmd_tag { /* bits can have 3 different meanings depending on value of AD_ADDR */ u8 reg; /* Bt252 Command Register if AD_ADDR = 00h */ struct { u8 :2; u8 SYNC_LVL_SEL:2; u8 SYNC_CNL_SEL:2; u8 DIGITIZE_CNL_SEL1:2; } bt252_command; /* Bt252 IOUT0 register if AD_ADDR = 01h */ struct { u8 IOUT_DATA:8; } bt252_iout0; /* BT252 IOUT1 register if AD_ADDR = 02h */ struct { u8 IOUT_DATA:8; } bt252_iout1; } I2C_AD_CMD; /***** Global declarations of local copies of boards' 8 bit I2C registers ***/ extern I2C_CSR2 i2c_csr2; extern I2C_EVEN_CSR i2c_even_csr; extern I2C_ODD_CSR i2c_odd_csr; extern I2C_CONFIG i2c_config; extern u8 i2c_dt_id; extern u8 i2c_x_clip_start; extern u8 i2c_y_clip_start; extern u8 i2c_x_clip_end; extern u8 i2c_y_clip_end; extern u8 i2c_ad_addr; extern u8 i2c_ad_lut; extern I2C_AD_CMD i2c_ad_cmd; extern u8 i2c_dig_out; extern u8 i2c_pm_lut_addr; extern u8 i2c_pm_lut_data; /* Functions for Global use */ /* access 8-bit IIC registers */ extern int ReadI2C(u8 *lpReg, u_short wIregIndex, u8 *byVal); extern int WriteI2C(u8 *lpReg, u_short wIregIndex, u8 byVal); #endif
// Copyright 2014 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 "components/invalidation/invalidation_notifier.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "components/invalidation/fake_invalidation_handler.h" #include "components/invalidation/fake_invalidation_state_tracker.h" #include "components/invalidation/invalidation_state_tracker.h" #include "components/invalidation/invalidator_test_template.h" #include "components/invalidation/push_client_channel.h" #include "jingle/notifier/base/fake_base_task.h" #include "jingle/notifier/base/notifier_options.h" #include "jingle/notifier/listener/fake_push_client.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace syncer { namespace { class InvalidationNotifierTestDelegate { public: InvalidationNotifierTestDelegate() {} ~InvalidationNotifierTestDelegate() { DestroyInvalidator(); } void CreateInvalidator( const std::string& invalidator_client_id, const std::string& initial_state, const base::WeakPtr<InvalidationStateTracker>& invalidation_state_tracker) { DCHECK(!invalidator_.get()); scoped_ptr<notifier::PushClient> push_client( new notifier::FakePushClient()); scoped_ptr<SyncNetworkChannel> network_channel( new PushClientChannel(push_client.Pass())); invalidator_.reset( new InvalidationNotifier(network_channel.Pass(), invalidator_client_id, UnackedInvalidationsMap(), initial_state, invalidation_state_tracker, base::MessageLoopProxy::current(), "fake_client_info")); } Invalidator* GetInvalidator() { return invalidator_.get(); } void DestroyInvalidator() { // Stopping the invalidation notifier stops its scheduler, which deletes // any pending tasks without running them. Some tasks "run and delete" // another task, so they must be run in order to avoid leaking the inner // task. Stopping does not schedule any tasks, so it's both necessary and // sufficient to drain the task queue before stopping the notifier. message_loop_.RunUntilIdle(); invalidator_.reset(); } void WaitForInvalidator() { message_loop_.RunUntilIdle(); } void TriggerOnInvalidatorStateChange(InvalidatorState state) { invalidator_->OnInvalidatorStateChange(state); } void TriggerOnIncomingInvalidation( const ObjectIdInvalidationMap& invalidation_map) { invalidator_->OnInvalidate(invalidation_map); } private: base::MessageLoop message_loop_; scoped_ptr<InvalidationNotifier> invalidator_; }; INSTANTIATE_TYPED_TEST_CASE_P( InvalidationNotifierTest, InvalidatorTest, InvalidationNotifierTestDelegate); } // namespace } // namespace syncer
from django.db import models, DEFAULT_DB_ALIAS, connection from django.contrib.auth.models import User from django.conf import settings class Animal(models.Model): name = models.CharField(max_length=150) latin_name = models.CharField(max_length=150) count = models.IntegerField() weight = models.FloatField() # use a non-default name for the default manager specimens = models.Manager() def __unicode__(self): return self.name class Plant(models.Model): name = models.CharField(max_length=150) class Meta: # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" class Stuff(models.Model): name = models.CharField(max_length=20, null=True) owner = models.ForeignKey(User, null=True) def __unicode__(self): return unicode(self.name) + u' is owned by ' + unicode(self.owner) class Absolute(models.Model): name = models.CharField(max_length=40) load_count = 0 def __init__(self, *args, **kwargs): super(Absolute, self).__init__(*args, **kwargs) Absolute.load_count += 1 class Parent(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ('id',) class Child(Parent): data = models.CharField(max_length=10) # Models to regression test #7572 class Channel(models.Model): name = models.CharField(max_length=255) class Article(models.Model): title = models.CharField(max_length=255) channels = models.ManyToManyField(Channel) class Meta: ordering = ('id',) # Models to regression test #11428 class Widget(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name class WidgetProxy(Widget): class Meta: proxy = True # Check for forward references in FKs and M2Ms with natural keys class TestManager(models.Manager): def get_by_natural_key(self, key): return self.get(name=key) class Store(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name def natural_key(self): return (self.name,) class Person(models.Model): objects = TestManager() name = models.CharField(max_length=255) class Meta: ordering = ('name',) def __unicode__(self): return self.name # Person doesn't actually have a dependency on store, but we need to define # one to test the behaviour of the dependency resolution algorithm. def natural_key(self): return (self.name,) natural_key.dependencies = ['fixtures_regress.store'] class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey(Person) stores = models.ManyToManyField(Store) class Meta: ordering = ('name',) def __unicode__(self): return u'%s by %s (available at %s)' % ( self.name, self.author.name, ', '.join(s.name for s in self.stores.all()) ) class NKManager(models.Manager): def get_by_natural_key(self, data): return self.get(data=data) class NKChild(Parent): data = models.CharField(max_length=10, unique=True) objects = NKManager() def natural_key(self): return self.data def __unicode__(self): return u'NKChild %s:%s' % (self.name, self.data) class RefToNKChild(models.Model): text = models.CharField(max_length=10) nk_fk = models.ForeignKey(NKChild, related_name='ref_fks') nk_m2m = models.ManyToManyField(NKChild, related_name='ref_m2ms') def __unicode__(self): return u'%s: Reference to %s [%s]' % ( self.text, self.nk_fk, ', '.join(str(o) for o in self.nk_m2m.all()) ) # ome models with pathological circular dependencies class Circle1(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle2'] class Circle2(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle1'] class Circle3(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle3'] class Circle4(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle5'] class Circle5(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle6'] class Circle6(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.circle4'] class ExternalDependency(models.Model): name = models.CharField(max_length=255) def natural_key(self): return self.name natural_key.dependencies = ['fixtures_regress.book'] # Model for regression test of #11101 class Thingy(models.Model): name = models.CharField(max_length=255)
//// [inheritedConstructorWithRestParams2.ts] class IBaseBase<T, U> { constructor(x: U) { } } interface IBase<T, U> extends IBaseBase<T, U> { } class BaseBase2 { constructor(x: number) { } } declare class BaseBase<T, U> extends BaseBase2 implements IBase<T, U> { constructor(x: T, ...y: U[]); constructor(x1: T, x2: T, ...y: U[]); constructor(x1: T, x2: U, y: T); } class Base extends BaseBase<string, number> { } class Derived extends Base { } // Ok new Derived("", ""); new Derived("", 3); new Derived("", 3, 3); new Derived("", 3, 3, 3); new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", ""); //// [inheritedConstructorWithRestParams2.js] 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 IBaseBase = (function () { function IBaseBase(x) { } return IBaseBase; })(); var BaseBase2 = (function () { function BaseBase2(x) { } return BaseBase2; })(); var Base = (function (_super) { __extends(Base, _super); function Base() { _super.apply(this, arguments); } return Base; })(BaseBase); var Derived = (function (_super) { __extends(Derived, _super); function Derived() { _super.apply(this, arguments); } return Derived; })(Base); // Ok new Derived("", ""); new Derived("", 3); new Derived("", 3, 3); new Derived("", 3, 3, 3); new Derived("", 3, ""); new Derived("", "", 3); new Derived("", "", 3, 3); // Errors new Derived(3); new Derived("", 3, "", 3); new Derived("", 3, "", "");
// Copyright 2014 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 "mojo/public/cpp/environment/async_waiter.h" namespace mojo { AsyncWaiter::AsyncWaiter(Handle handle, MojoHandleSignals signals, const Callback& callback) : waiter_(Environment::GetDefaultAsyncWaiter()), id_(0), callback_(callback) { id_ = waiter_->AsyncWait(handle.value(), signals, MOJO_DEADLINE_INDEFINITE, &AsyncWaiter::WaitComplete, this); } AsyncWaiter::~AsyncWaiter() { if (id_) waiter_->CancelWait(id_); } // static void AsyncWaiter::WaitComplete(void* waiter, MojoResult result) { static_cast<AsyncWaiter*>(waiter)->WaitCompleteInternal(result); } void AsyncWaiter::WaitCompleteInternal(MojoResult result) { id_ = 0; callback_.Run(result); } } // namespace mojo
<html> <head> <style> #sitemast { position: absolute; width:1.5em; font-size:400%; } #sitemast a {color: green; background: green; padding: 0; text-decoration: none } </style> </head> <body> You should see a single green stripe below. The test has failed if you don't see a perfect rectangle. <div id="sitemast"> <a><span>A </span> A<br><span>A </span> A A</a> </div>
/* Copyright 2016 The Kubernetes 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 watch import ( "time" "k8s.io/kubernetes/pkg/api" "k8s.io/kubernetes/pkg/api/meta" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/wait" ) // ConditionFunc returns true if the condition has been reached, false if it has not been reached yet, // or an error if the condition cannot be checked and should terminate. In general, it is better to define // level driven conditions over edge driven conditions (pod has ready=true, vs pod modified and ready changed // from false to true). type ConditionFunc func(event Event) (bool, error) // Until reads items from the watch until each provided condition succeeds, and then returns the last watch // encountered. The first condition that returns an error terminates the watch (and the event is also returned). // If no event has been received, the returned event will be nil. // Conditions are satisfied sequentially so as to provide a useful primitive for higher level composition. // A zero timeout means to wait forever. func Until(timeout time.Duration, watcher Interface, conditions ...ConditionFunc) (*Event, error) { ch := watcher.ResultChan() defer watcher.Stop() var after <-chan time.Time if timeout > 0 { after = time.After(timeout) } else { ch := make(chan time.Time) defer close(ch) after = ch } var lastEvent *Event for _, condition := range conditions { // check the next condition against the previous event and short circuit waiting for the next watch if lastEvent != nil { done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { continue } } ConditionSucceeded: for { select { case event, ok := <-ch: if !ok { return lastEvent, wait.ErrWaitTimeout } lastEvent = &event // TODO: check for watch expired error and retry watch from latest point? done, err := condition(event) if err != nil { return lastEvent, err } if done { break ConditionSucceeded } case <-after: return lastEvent, wait.ErrWaitTimeout } } } return lastEvent, nil } // ListerWatcher is any object that knows how to perform an initial list and start a watch on a resource. type ListerWatcher interface { // List should return a list type object; the Items field will be extracted, and the // ResourceVersion field will be used to start the watch in the right place. List(options api.ListOptions) (runtime.Object, error) // Watch should begin a watch at the specified version. Watch(options api.ListOptions) (Interface, error) } // TODO: check for watch expired error and retry watch from latest point? Same issue exists for Until. func ListWatchUntil(timeout time.Duration, lw ListerWatcher, conditions ...ConditionFunc) (*Event, error) { if len(conditions) == 0 { return nil, nil } list, err := lw.List(api.ListOptions{}) if err != nil { return nil, err } initialItems, err := meta.ExtractList(list) if err != nil { return nil, err } // use the initial items as simulated "adds" var lastEvent *Event currIndex := 0 passedConditions := 0 for _, condition := range conditions { // check the next condition against the previous event and short circuit waiting for the next watch if lastEvent != nil { done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { passedConditions = passedConditions + 1 continue } } ConditionSucceeded: for currIndex < len(initialItems) { lastEvent = &Event{Type: Added, Object: initialItems[currIndex]} currIndex++ done, err := condition(*lastEvent) if err != nil { return lastEvent, err } if done { passedConditions = passedConditions + 1 break ConditionSucceeded } } } if passedConditions == len(conditions) { return lastEvent, nil } remainingConditions := conditions[passedConditions:] metaObj, err := meta.ListAccessor(list) if err != nil { return nil, err } currResourceVersion := metaObj.GetResourceVersion() watch, err := lw.Watch(api.ListOptions{ResourceVersion: currResourceVersion}) if err != nil { return nil, err } return Until(timeout, watch, remainingConditions...) }
/****************************************************************************** * * Copyright(c) 2009-2012 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * 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. * * The full GNU General Public License is included in this distribution in the * file called LICENSE. * * Contact Information: * wlanfae <wlanfae@realtek.com> * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, * Hsinchu 300, Taiwan. * * Larry Finger <Larry.Finger@lwfinger.net> * * Created on 2010/ 5/18, 1:41 *****************************************************************************/ #ifndef __RTL92DE_TABLE__H_ #define __RTL92DE_TABLE__H_ /*Created on 2011/ 1/14, 1:35*/ #define PHY_REG_2T_ARRAYLENGTH 380 extern u32 rtl8192de_phy_reg_2tarray[PHY_REG_2T_ARRAYLENGTH]; #define PHY_REG_ARRAY_PG_LENGTH 624 extern u32 rtl8192de_phy_reg_array_pg[PHY_REG_ARRAY_PG_LENGTH]; #define RADIOA_2T_ARRAYLENGTH 378 extern u32 rtl8192de_radioa_2tarray[RADIOA_2T_ARRAYLENGTH]; #define RADIOB_2T_ARRAYLENGTH 384 extern u32 rtl8192de_radiob_2tarray[RADIOB_2T_ARRAYLENGTH]; #define RADIOA_2T_INT_PA_ARRAYLENGTH 378 extern u32 rtl8192de_radioa_2t_int_paarray[RADIOA_2T_INT_PA_ARRAYLENGTH]; #define RADIOB_2T_INT_PA_ARRAYLENGTH 384 extern u32 rtl8192de_radiob_2t_int_paarray[RADIOB_2T_INT_PA_ARRAYLENGTH]; #define MAC_2T_ARRAYLENGTH 160 extern u32 rtl8192de_mac_2tarray[MAC_2T_ARRAYLENGTH]; #define AGCTAB_ARRAYLENGTH 386 extern u32 rtl8192de_agctab_array[AGCTAB_ARRAYLENGTH]; #define AGCTAB_5G_ARRAYLENGTH 194 extern u32 rtl8192de_agctab_5garray[AGCTAB_5G_ARRAYLENGTH]; #define AGCTAB_2G_ARRAYLENGTH 194 extern u32 rtl8192de_agctab_2garray[AGCTAB_2G_ARRAYLENGTH]; #endif
// to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = require('./_iobject') , defined = require('./_defined'); module.exports = function(it){ return IObject(defined(it)); };
// Copyright 2008 The Closure Library Authors. 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. goog.provide('goog.ui.SubMenuTest'); goog.setTestOnly('goog.ui.SubMenuTest'); goog.require('goog.a11y.aria'); goog.require('goog.a11y.aria.State'); goog.require('goog.dom'); goog.require('goog.dom.classlist'); goog.require('goog.events'); goog.require('goog.events.Event'); goog.require('goog.events.KeyCodes'); goog.require('goog.events.KeyHandler'); goog.require('goog.functions'); goog.require('goog.positioning'); goog.require('goog.positioning.Overflow'); goog.require('goog.style'); goog.require('goog.testing.MockClock'); goog.require('goog.testing.events'); goog.require('goog.testing.jsunit'); goog.require('goog.ui.Component'); goog.require('goog.ui.Menu'); goog.require('goog.ui.MenuItem'); goog.require('goog.ui.SubMenu'); goog.require('goog.ui.SubMenuRenderer'); var menu; var clonedMenuDom; var mockClock; // mock out goog.positioning.positionAtCoordinate so that // the menu always fits. (we don't care about testing the // dynamic menu positioning if the menu doesn't fit in the window.) var oldPositionFn = goog.positioning.positionAtCoordinate; goog.positioning.positionAtCoordinate = function( absolutePos, movableElement, movableElementCorner, opt_margin, opt_overflow) { return oldPositionFn.call( null, absolutePos, movableElement, movableElementCorner, opt_margin, goog.positioning.Overflow.IGNORE); }; function setUp() { clonedMenuDom = goog.dom.getElement('demoMenu').cloneNode(true); menu = new goog.ui.Menu(); } function tearDown() { document.body.style.direction = 'ltr'; menu.dispose(); var element = goog.dom.getElement('demoMenu'); element.parentNode.replaceChild(clonedMenuDom, element); goog.dom.removeChildren(goog.dom.getElement('sandbox')); if (mockClock) { mockClock.uninstall(); mockClock = null; } } function assertKeyHandlingIsCorrect(keyToOpenSubMenu, keyToCloseSubMenu) { menu.setFocusable(true); menu.decorate(goog.dom.getElement('demoMenu')); var KeyCodes = goog.events.KeyCodes; var plainItem = menu.getChildAt(0); plainItem.setMnemonic(KeyCodes.F); var subMenuItem1 = menu.getChildAt(1); subMenuItem1.setMnemonic(KeyCodes.S); var subMenuItem1Menu = subMenuItem1.getMenu(); menu.setHighlighted(plainItem); var fireKeySequence = goog.testing.events.fireKeySequence; assertTrue( 'Expected OpenSubMenu key to not be handled', fireKeySequence(plainItem.getElement(), keyToOpenSubMenu)); assertFalse(subMenuItem1Menu.isVisible()); assertFalse( 'Expected F key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.F)); assertFalse( 'Expected DOWN key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.DOWN)); assertEquals(subMenuItem1, menu.getChildAt(1)); assertFalse( 'Expected OpenSubMenu key to be handled', fireKeySequence(subMenuItem1.getElement(), keyToOpenSubMenu)); assertTrue(subMenuItem1Menu.isVisible()); assertFalse( 'Expected CloseSubMenu key to be handled', fireKeySequence(subMenuItem1.getElement(), keyToCloseSubMenu)); assertFalse(subMenuItem1Menu.isVisible()); assertFalse( 'Expected UP key to be handled', fireKeySequence(subMenuItem1.getElement(), KeyCodes.UP)); assertFalse( 'Expected S key to be handled', fireKeySequence(plainItem.getElement(), KeyCodes.S)); assertTrue(subMenuItem1Menu.isVisible()); } function testKeyHandling_ltr() { assertKeyHandlingIsCorrect( goog.events.KeyCodes.RIGHT, goog.events.KeyCodes.LEFT); } function testKeyHandling_rtl() { document.body.style.direction = 'rtl'; assertKeyHandlingIsCorrect( goog.events.KeyCodes.LEFT, goog.events.KeyCodes.RIGHT); } function testNormalLtrSubMenu() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, false); } function testNormalRtlSubMenu() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, true); } function testLtrSubMenuAlignedToStart() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, false); } function testNullContentElement() { var subMenu = new goog.ui.SubMenu(); subMenu.setContent('demo'); } function testRtlSubMenuAlignedToStart() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, true); } function testSetContentKeepsArrow_ltr() { document.body.style.direction = 'ltr'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); subMenu.setContent('test'); assertArrowDirection(subMenu, true); assertRenderDirection(subMenu, true); assertArrowPosition(subMenu, false); } function testSetContentKeepsArrow_rtl() { document.body.style.direction = 'rtl'; menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setAlignToEnd(false); subMenu.setContent('test'); assertArrowDirection(subMenu, false); assertRenderDirection(subMenu, false); assertArrowPosition(subMenu, true); } function testExitDocument() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); var innerMenu = subMenu.getMenu(); assertTrue('Top-level menu was not in document', menu.isInDocument()); assertTrue('Submenu was not in document', subMenu.isInDocument()); assertTrue('Inner menu was not in document', innerMenu.isInDocument()); menu.exitDocument(); assertFalse('Top-level menu was in document', menu.isInDocument()); assertFalse('Submenu was in document', subMenu.isInDocument()); assertFalse('Inner menu was in document', innerMenu.isInDocument()); } function testDisposal() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); var innerMenu = subMenu.getMenu(); menu.dispose(); assert('Top-level menu was not disposed', menu.getDisposed()); assert('Submenu was not disposed', subMenu.getDisposed()); assert('Inner menu was not disposed', innerMenu.getDisposed()); } function testShowAndDismissSubMenu() { var openEventDispatched = false; var closeEventDispatched = false; function handleEvent(e) { switch (e.type) { case goog.ui.Component.EventType.OPEN: openEventDispatched = true; break; case goog.ui.Component.EventType.CLOSE: closeEventDispatched = true; break; default: fail('Invalid event type: ' + e.type); } } menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); goog.events.listen( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertFalse('No OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.showSubMenu(); assertTrue( 'Submenu must have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertTrue('Popup menu must be visible', subMenu.getMenu().isVisible()); assertTrue('OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.dismissSubMenu(); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertTrue('CLOSE event must have been dispatched', closeEventDispatched); goog.events.unlisten( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); } function testDismissWhenSubMenuNotVisible() { var openEventDispatched = false; var closeEventDispatched = false; function handleEvent(e) { switch (e.type) { case goog.ui.Component.EventType.OPEN: openEventDispatched = true; break; case goog.ui.Component.EventType.CLOSE: closeEventDispatched = true; break; default: fail('Invalid event type: ' + e.type); } } menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); goog.events.listen( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertFalse('No OPEN event must have been dispatched', openEventDispatched); assertFalse('No CLOSE event must have been dispatched', closeEventDispatched); subMenu.showSubMenu(); subMenu.getMenu().setVisible(false); subMenu.dismissSubMenu(); assertFalse( 'Submenu must not have "-open" CSS class', goog.dom.classlist.contains(subMenu.getElement(), 'goog-submenu-open')); assertFalse(subMenu.menuIsVisible_); assertFalse('Popup menu must not be visible', subMenu.getMenu().isVisible()); assertTrue('CLOSE event must have been dispatched', closeEventDispatched); goog.events.unlisten( subMenu, [goog.ui.Component.EventType.OPEN, goog.ui.Component.EventType.CLOSE], handleEvent); } function testCloseSubMenuBehavior() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.getElement().id = 'subMenu'; var innerMenu = subMenu.getMenu(); innerMenu.getChildAt(0).getElement().id = 'child1'; subMenu.setHighlighted(true); subMenu.showSubMenu(); function MyFakeEvent(keyCode, opt_eventType) { this.type = opt_eventType || goog.events.KeyHandler.EventType.KEY; this.keyCode = keyCode; this.propagationStopped = false; this.preventDefault = goog.nullFunction; this.stopPropagation = function() { this.propagationStopped = true; }; } // Focus on the first item in the submenu and verify the activedescendant is // set correctly. subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.DOWN)); assertEquals( 'First item in submenu must be the aria-activedescendant', 'child1', goog.a11y.aria.getState( menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT)); // Dismiss the submenu and verify the activedescendant is updated correctly. subMenu.handleKeyEvent(new MyFakeEvent(goog.events.KeyCodes.LEFT)); assertEquals( 'Submenu must be the aria-activedescendant', 'subMenu', goog.a11y.aria.getState( menu.getElement(), goog.a11y.aria.State.ACTIVEDESCENDANT)); } function testLazyInstantiateSubMenu() { menu.decorate(goog.dom.getElement('demoMenu')); var subMenu = menu.getChildAt(1); subMenu.setHighlighted(true); var lazyMenu; var key = goog.events.listen( subMenu, goog.ui.Component.EventType.OPEN, function(e) { lazyMenu = new goog.ui.Menu(); lazyMenu.addItem(new goog.ui.MenuItem('foo')); lazyMenu.addItem(new goog.ui.MenuItem('bar')); subMenu.setMenu(lazyMenu, /* opt_internal */ false); }); subMenu.showSubMenu(); assertNotNull('Popup menu must have been created', lazyMenu); assertEquals( 'Popup menu must be a child of the submenu', subMenu, lazyMenu.getParent()); assertTrue('Popup menu must have been rendered', lazyMenu.isInDocument()); assertTrue('Popup menu must be visible', lazyMenu.isVisible()); menu.dispose(); assertTrue('Submenu must have been disposed of', subMenu.isDisposed()); assertFalse( 'Popup menu must not have been disposed of', lazyMenu.isDisposed()); lazyMenu.dispose(); goog.events.unlistenByKey(key); } function testReusableMenu() { var subMenuOne = new goog.ui.SubMenu('SubMenu One'); var subMenuTwo = new goog.ui.SubMenu('SubMenu Two'); menu.addItem(subMenuOne); menu.addItem(subMenuTwo); menu.render(goog.dom.getElement('sandbox')); // It is possible for the same popup menu to be shared between different // submenus. var sharedMenu = new goog.ui.Menu(); sharedMenu.addItem(new goog.ui.MenuItem('Hello')); sharedMenu.addItem(new goog.ui.MenuItem('World')); assertNull('Shared menu must not have a parent', sharedMenu.getParent()); subMenuOne.setMenu(sharedMenu); assertEquals( 'SubMenuOne must point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertEquals( 'SubMenuOne must be the shared menu\'s parent', subMenuOne, sharedMenu.getParent()); subMenuTwo.setMenu(sharedMenu); assertEquals( 'SubMenuTwo must point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertEquals( 'SubMenuTwo must be the shared menu\'s parent', subMenuTwo, sharedMenu.getParent()); assertEquals( 'SubMenuOne must still point to the shared menu', sharedMenu, subMenuOne.getMenu()); menu.setHighlighted(subMenuOne); subMenuOne.showSubMenu(); assertEquals( 'SubMenuOne must point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertEquals( 'SubMenuOne must be the shared menu\'s parent', subMenuOne, sharedMenu.getParent()); assertEquals( 'SubMenuTwo must still point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertTrue('Shared menu must be visible', sharedMenu.isVisible()); menu.setHighlighted(subMenuTwo); subMenuTwo.showSubMenu(); assertEquals( 'SubMenuTwo must point to the shared menu', sharedMenu, subMenuTwo.getMenu()); assertEquals( 'SubMenuTwo must be the shared menu\'s parent', subMenuTwo, sharedMenu.getParent()); assertEquals( 'SubMenuOne must still point to the shared menu', sharedMenu, subMenuOne.getMenu()); assertTrue('Shared menu must be visible', sharedMenu.isVisible()); } /** * If you remove a submenu in the interval between when a mouseover event * is fired on it, and showSubMenu() is called, showSubMenu causes a null * value to be dereferenced. This test validates that the fix for this works. * (See bug 1823144). */ function testDeleteItemDuringSubmenuDisplayInterval() { mockClock = new goog.testing.MockClock(true); var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); // Trigger mouseover, and remove item before showSubMenu can be called. var e = new goog.events.Event(); submenu.handleMouseOver(e); menu.removeItem(submenu); mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS); // (No JS error should occur.) } function testShowSubMenuAfterRemoval() { var submenu = new goog.ui.SubMenu('submenu'); menu.addItem(submenu); menu.removeItem(submenu); submenu.showSubMenu(); // (No JS error should occur.) } /** * Tests that if a sub menu is selectable, then it can handle actions. */ function testSubmenuSelectable() { var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); submenu.setSelectable(true); var numClicks = 0; var menuClickedFn = function(e) { numClicks++; }; goog.events.listen( submenu, goog.ui.Component.EventType.ACTION, menuClickedFn); submenu.performActionInternal(null); submenu.performActionInternal(null); assertEquals('The submenu should have fired an event', 2, numClicks); submenu.setSelectable(false); submenu.performActionInternal(null); assertEquals( 'The submenu should not have fired any further events', 2, numClicks); } /** * Tests that if a sub menu is checkable, then it can handle actions. */ function testSubmenuCheckable() { var submenu = new goog.ui.SubMenu('submenu'); submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); submenu.setCheckable(true); var numClicks = 0; var menuClickedFn = function(e) { numClicks++; }; goog.events.listen( submenu, goog.ui.Component.EventType.ACTION, menuClickedFn); submenu.performActionInternal(null); submenu.performActionInternal(null); assertEquals('The submenu should have fired an event', 2, numClicks); submenu.setCheckable(false); submenu.performActionInternal(null); assertEquals( 'The submenu should not have fired any further events', 2, numClicks); } /** * Tests that entering a child menu cancels the dismiss timer for the submenu. */ function testEnteringChildCancelsDismiss() { var submenu = new goog.ui.SubMenu('submenu'); submenu.isInDocument = goog.functions.TRUE; submenu.addItem(new goog.ui.MenuItem('submenu item 1')); menu.addItem(submenu); mockClock = new goog.testing.MockClock(true); submenu.getMenu().setVisible(true); // This starts the dismiss timer. submenu.setHighlighted(false); // This should cancel the dismiss timer. submenu.getMenu().dispatchEvent(goog.ui.Component.EventType.ENTER); // Tick the length of the dismiss timer. mockClock.tick(goog.ui.SubMenu.MENU_DELAY_MS); // Check that the menu is now highlighted and still visible. assertTrue(submenu.getMenu().isVisible()); assertTrue(submenu.isHighlighted()); } /** * Asserts that this sub menu renders in the right direction relative to * the parent menu. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} left True for left-pointing, false for right-pointing. */ function assertRenderDirection(subMenu, left) { subMenu.getParent().setHighlighted(subMenu); subMenu.showSubMenu(); var menuItemPosition = goog.style.getPageOffset(subMenu.getElement()); var menuPosition = goog.style.getPageOffset(subMenu.getMenu().getElement()); assert(Math.abs(menuItemPosition.y - menuPosition.y) < 5); assertEquals( 'Menu at: ' + menuPosition.x + ', submenu item at: ' + menuItemPosition.x, left, menuPosition.x < menuItemPosition.x); } /** * Asserts that this sub menu has a properly-oriented arrow. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} left True for left-pointing, false for right-pointing. */ function assertArrowDirection(subMenu, left) { assertEquals( left ? goog.ui.SubMenuRenderer.LEFT_ARROW_ : goog.ui.SubMenuRenderer.RIGHT_ARROW_, getArrowElement(subMenu).innerHTML); } /** * Asserts that the arrow position is correct. * @param {goog.ui.SubMenu} subMenu The sub menu. * @param {boolean} leftAlign True for left-aligned, false for right-aligned. */ function assertArrowPosition(subMenu, left) { var arrow = getArrowElement(subMenu); var expectedLeft = left ? 0 : arrow.offsetParent.offsetWidth - arrow.offsetWidth; var actualLeft = arrow.offsetLeft; assertTrue( 'Expected left offset: ' + expectedLeft + '\n' + 'Actual left offset: ' + actualLeft + '\n', Math.abs(expectedLeft - actualLeft) < 5); } /** * Gets the arrow element of a sub menu. * @param {goog.ui.SubMenu} subMenu The sub menu. * @return {Element} The arrow. */ function getArrowElement(subMenu) { return subMenu.getContentElement().lastChild; }