answer stringlengths 15 1.25M |
|---|
// <API key>: Apache-2.0 WITH LLVM-exception
#include "../ClangTidy.h"
#include "../ClangTidyModule.h"
#include "../<API key>.h"
#include "UseToStringCheck.h"
using namespace clang::ast_matchers;
namespace clang {
namespace tidy {
namespace boost {
class BoostModule : public ClangTidyModule {
public:
void addCheckFactories(<API key> &CheckFactories) override {
CheckFactories.registerCheck<UseToStringCheck>("boost-use-to-string");
}
};
// Register the BoostModule using this statically initialized variable.
static <API key>::Add<BoostModule> X("boost-module",
"Add boost checks.");
} // namespace boost
// This anchor is used to force the linker to link in the generated object file
// and thus register the BoostModule.
volatile int <API key> = 0;
} // namespace tidy
} // namespace clang |
// Type definitions for hapi 15.0
<reference types="node" />
import http = require("http");
import stream = require("stream");
import Events = require("events");
import url = require("url");
export interface IDictionary<T> {
[key: string]: T;
}
export interface IHeaderOptions {
append?: boolean | undefined;
separator?: string | undefined;
override?: boolean | undefined;
duplicate?: boolean | undefined;
}
export interface IBoom extends Error {
/** if true, indicates this is a Boom object instance. */
isBoom: boolean;
/** convenience bool indicating status code >= 500. */
isServer: boolean;
/** the error message. */
message: string;
/** the formatted response.Can be directly manipulated after object construction to return a custom error response.Allowed root keys: */
output: {
/** the HTTP status code (typically 4xx or 5xx). */
statusCode: number;
/** an object containing any HTTP headers where each key is a header name and value is the header content. */
headers: IDictionary<string>;
/** the formatted object used as the response payload (stringified).Can be directly manipulated but any changes will be lost if reformat() is called.Any content allowed and by default includes the following content: */
payload: {
/** the HTTP status code, derived from error.output.statusCode. */
statusCode: number;
/** the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from statusCode. */
error: string;
/** the error message derived from error.message. */
message: string;
};
};
/** reformat()rebuilds error.output using the other object properties. */
reformat(): void;
}
/** cache functionality via the "CatBox" module. */
export interface ICatBoxCacheOptions {
/** a prototype function or catbox engine object. */
engine: any;
/** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well. */
name?: string | undefined;
/** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
shared?: boolean | undefined;
}
/** policy configuration for the "CatBox" module and server method options. */
export interface <API key> {
/** the cache name configured in server.cache. Defaults to the default cache. */
cache?: string | undefined;
/** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */
segment?: string | undefined;
/** if true, allows multiple cache provisions to share the same segment. Default to false. */
shared?: boolean | undefined;
/** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */
expiresIn?: number | undefined;
/** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. */
expiresAt?: number | undefined;
/** a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: - id - the id string or object provided to the get() method. - next - the method called when the new item is returned with the signature function(err, value, ttl) where: - err - an error condition. - value - the new value generated. - ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. */
generateFunc?: Function | undefined;
/** number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. */
staleIn?: number | undefined;
/** number of milliseconds to wait before checking if an item is stale. */
staleTimeout?: number | undefined;
/** number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */
generateTimeout?: number | undefined;
/** if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true */
dropOnError?: boolean | undefined;
/** if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. */
generateOnReadError?: boolean | undefined;
/** if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. */
<API key>?: boolean | undefined;
/** number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). */
<API key>?: number | undefined;
}
/** Any connections configuration server defaults can be included to override and customize the individual connection. */
export interface <API key> extends <API key> {
/** - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'.*/
host?: string | undefined;
/** - sets the host name or IP address the connection will listen on.If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0').Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine.*/
address?: string | undefined;
/** - the TCP port the connection will listen to.Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port).If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe.*/
port?: string | number | undefined;
uri?: string | undefined;
/** - optional node.js HTTP (or HTTPS) http.Server object or any compatible object.If the listener needs to be manually started, set autoListen to false.If the listener uses TLS, set tls to true.*/
listener?: any;
/** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/
autoListen?: boolean | undefined;
/** caching headers configuration: */
cache?: {
/** - an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive.Defaults to [200]. */
statuses: number[];
} | undefined;
/** - a string or string array of labels used to server.select() specific connections matching the specified labels.Defaults to an empty array [](no labels).*/
labels?: string | string[] | undefined;
/** - used to create an HTTPS connection.The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS documentation.Set to true when passing a listener object that has been configured to use TLS directly. */
tls?: boolean | { key?: string | undefined; cert?: string | undefined; pfx?: string | undefined; } | Object | undefined;
}
export interface <API key> {
/** <API key> connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */
app?: any;
/** if false, response content encoding is disabled. Defaults to true */
compression?: boolean | undefined;
/** connection load limits configuration where: */
load?: {
/** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxHeapUsedBytes?: number | undefined;
/** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxRssBytes?: number | undefined;
/** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
maxEventLoopDelay?: number | undefined;
} | undefined;
/** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */
plugins?: any;
/** controls how incoming request URIs are matched against the routing table: */
router?: {
/** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */
isCaseSensitive: boolean;
/** removes trailing slashes on incoming paths. Defaults to false. */
stripTrailingSlash: boolean;
} | undefined;
/** a route options object used to set the default configuration for every route. */
routes?: <API key> | undefined;
state?: IServerState | undefined;
}
/** Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on.*/
export interface IServerOptions {
/** <API key> configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */
app?: any;
/** sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, and Riak). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned:
a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')).
a configuration object with the following options:
enginea prototype function or catbox engine object.
namean identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisions as well.
sharedif true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false.
other options passed to the catbox strategy used.
an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. */
cache?: string | ICatBoxCacheOptions | ICatBoxCacheOptions[] | any | undefined;
/** sets the default connections configuration which can be overridden by each connection where: */
connections?: <API key> | undefined;
/** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object*/
debug?: boolean | {
/** - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */
log: string[];
/** - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error.*/
request: string[];
} | undefined;
/** file system related settings*/
files?: {
/** sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000.*/
etagsCacheMaxSize?: number | undefined;
} | undefined;
/** process load monitoring*/
load?: {
/** the frequency of sampling in milliseconds. Defaults to 0 (no sampling).*/
sampleInterval?: number | undefined;
} | undefined;
mime?: any;
/** if true, does not load the inert (file and directory support), h2o2 (proxy support), and vision (views support) plugins automatically. The plugins can be loaded manually after construction. Defaults to false (plugins loaded). */
minimal?: boolean | undefined;
/** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}.*/
plugins?: IDictionary<any> | undefined;
}
export interface IServerViewCompile {
(template: string, options: any): void;
(template: string, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: boolean) => void) => void) => void): void;
}
export interface <API key> {
/** path - the root file path used to resolve and load the templates identified when calling reply.view().Defaults to current working directory.*/
path?: string | undefined;
/**partialsPath - the root file path where partials are located.Partials are small segments of template code that can be nested and reused throughout other templates.Defaults to no partials support (empty path).
*/
partialsPath?: string | undefined;
/**helpersPath - the directory path where helpers are located.Helpers are functions used within templates to perform transformations and other data manipulations using the template context or other inputs.Each '.js' file in the helpers directory is loaded and the file name is used as the helper name.The files must export a single method with the signature function(context) and return a string.Sub - folders are not supported and are ignored.Defaults to no helpers support (empty path).Note that jade does not support loading helpers this way.*/
helpersPath?: string | undefined;
/**relativeTo - a base path used as prefix for path and partialsPath.No default.*/
relativeTo?: string | undefined;
/**layout - if set to true or a layout filename, layout support is enabled.A layout is a single template file used as the parent template for other view templates in the same engine.If true, the layout template name must be 'layout.ext' where 'ext' is the engine's extension. Otherwise, the provided filename is suffixed with the engine's extension and loaded.Disable layout when using Jade as it will handle including any layout files independently.Defaults to false.*/
layout?: boolean | string | undefined;
/**layoutPath - the root file path where layout templates are located (using the relativeTo prefix if present). Defaults to path.*/
layoutPath?: string | undefined;
/**layoutKeyword - the key used by the template engine to denote where primary template content should go.Defaults to 'content'.*/
layoutKeywork?: string | undefined;
/**encoding - the text encoding used by the templates when reading the files and outputting the result.Defaults to 'utf8'.*/
encoding?: string | undefined;
/**isCached - if set to false, templates will not be cached (thus will be read from file on every use).Defaults to true.*/
isCached?: boolean | undefined;
/**allowAbsolutePaths - if set to true, allows absolute template paths passed to reply.view().Defaults to false.*/
allowAbsolutePaths?: boolean | undefined;
/**allowInsecureAccess - if set to true, allows template paths passed to reply.view() to contain '../'.Defaults to false.*/
allowInsecureAccess?: boolean | undefined;
/**compileOptions - options object passed to the engine's compile function. Defaults to empty options {}.*/
compileOptions?: any;
/**runtimeOptions - options object passed to the returned function from the compile operation.Defaults to empty options {}.*/
runtimeOptions?: any;
/**contentType - the content type of the engine results.Defaults to 'text/html'.*/
contentType?: string | undefined;
/**compileMode - specify whether the engine compile() method is 'sync' or 'async'.Defaults to 'sync'.*/
compileMode?: string | undefined;
/**context - a global context used with all templates.The global context option can be either an object or a function that takes no arguments and returns a context object.When rendering views, the global context will be merged with any context object specified on the handler or using reply.view().When multiple context objects are used, values from the global context always have lowest precedence.*/
context?: any;
}
export interface <API key> extends <API key> {
/**- the npm module used for rendering the templates.The module object must contain: "module", the rendering function. The required function signature depends on the compileMode settings.
* If the compileMode is 'sync', the signature is compile(template, options), the return value is a function with signature function(context, options), and the method is allowed to throw errors.If the compileMode is 'async', the signature is compile(template, options, callback) where callback has the signature function(err, compiled) where compiled is a function with signature function(context, options, callback) and callback has the signature function(err, rendered).*/
module: {
compile?(template: any, options: any): (context: any, options: any) => void;
compile?(template: any, options: any, callback: (err: any, compiled: (context: any, options: any, callback: (err: any, rendered: any) => void) => void) => void): void;
};
}
/**Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.
*/
export interface <API key> extends <API key> {
/** - required object where each key is a file extension (e.g. 'html', 'hbr'), mapped to the npm module used for rendering the templates.Alternatively, the extension can be mapped to an object with the following options:*/
engines: IDictionary<any> | <API key>;
/** defines the default filename extension to append to template names when multiple engines are configured and not explicit extension is provided for a given template. No default value.*/
defaultExtension?: string | undefined;
}
export interface IReplyMethods {
/** Returns control back to the framework without setting a response. If called in the handler, the response defaults to an empty payload with status code 200.
* The data argument is only used for passing back authentication data and is ignored elsewhere. */
continue(credentialData?: any): void;
/** Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. The response flow control rules do not apply. */
file(/** the file path. */
path: string,
/** optional settings: */
options?: {
/** - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string | undefined;
/** specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string | undefined;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false. */
lookupCompressed: boolean;
}): void;
/** Concludes the handler activity by returning control over to the router with a templatized view response.
the response flow control rules apply. */
view(/** the template filename and path, relative to the templates path configured via the server views manager. */
template: string,
/** optional object used by the template to render context-specific result. Defaults to no context {}. */
context?: {},
/** optional object used to override the server's views manager configuration for this response. Cannot override isCached, partialsPath, or helpersPath which are only loaded at initialization. */
options?: any): Response;
/** Sets a header on the response */
header(name: string, value: string, options?: IHeaderOptions): Response;
/** Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed
The response flow control rules do not apply. */
close(options?: {
/** if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. */
end?: boolean | undefined;
}): void;
/** Proxies the request to an upstream endpoint.
the response flow control rules do not apply. */
proxy(/** an object including the same keys and restrictions defined by the route proxy handler options. */
options: IProxyHandlerConfig): void;
/** Redirects the client to the specified uri. Same as calling reply().redirect(uri).
* The response flow control rules apply. */
redirect(uri: string): ResponseRedirect;
/** Replies with the specified response */
response(result: any): Response;
/** Sets a cookie on the response */
state(name: string, value: any, options?: any): void;
/** Clears a cookie on the response */
unstate(name: string, options?: any): void;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IReply extends IReplyMethods {
<T>(
err: Error,
result?: string | number | boolean | Buffer | stream.Stream | Promise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
<T>(result: string | number | boolean | Buffer | stream.Stream | Promise<T> | T): Response;
}
/** Concludes the handler activity by setting a response and returning control over to the framework where:
erran optional error response.
result an optional response payload.
Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first.
FLOW CONTROL:
When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */
export interface IStrictReply<T> extends IReplyMethods {
(err: Error,
result?: Promise<T> | T,
/** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */
credentialData?: any): IBoom;
/** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */
(result: Promise<T> | T): Response;
}
export interface ISessionHandler {
(request: Request, reply: IReply): void;
}
export interface <API key> {
<T>(request: Request, reply: IStrictReply<T>): void;
}
export interface IRequestHandler<T> {
(request: Request): T;
}
export interface IFailAction {
(source: string, error: any, next: () => void): void;
}
/** generates a reverse proxy handler */
export interface IProxyHandlerConfig {
/** the upstream service host to proxy requests to. The same path on the client request will be used as the path on the host.*/
host?: string | undefined;
/** the upstream service port. */
port?: number | undefined;
/** The protocol to use when making a request to the proxied host:
'http'
'https'*/
protocol?: string | undefined;
/** an absolute URI used instead of the incoming host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri.*/
uri?: string | undefined;
/** if true, forwards the headers sent from the client to the upstream service being proxied to, headers sent from the upstream service will also be forwarded to the client. Defaults to false.*/
passThrough?: boolean | undefined;
/** <API key> - if false, any locally defined state is removed from incoming requests before being passed upstream. This is a security feature to prevent local state (e.g. authentication cookies) from leaking upstream to other servers along with the cookies intended for those servers. This value can be overridden on a per state basis via the server.state() passThrough option. Defaults to false.*/
<API key>?: boolean | undefined;
/**acceptEncoding - if false, does not pass-through the 'Accept-Encoding' HTTP header which is useful when using an onResponse post-processing to avoid receiving an encoded response (e.g. gzipped). Can only be used together with passThrough. Defaults to true (passing header).*/
acceptEncoding?: boolean | undefined;
/** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. When set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true.*/
rejectUnauthorized?: boolean | undefined;
/**if true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto' headers when making a request to the proxied upstream endpoint. Defaults to false.*/
xforward?: boolean | undefined;
/** the maximum number of HTTP redirections allowed, to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false.*/
redirects?: boolean | number | undefined;
/**number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes).*/
timeout?: number | undefined;
/** a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function(request, callback) where:
request - is the incoming request object.
callback - is function(err, uri, headers) where:
err - internal error condition.
uri - the absolute proxy URI.
headers - optional object where each key is an HTTP request header and the value is the header content.*/
mapUri?(request: Request, callback: (err: any, uri: string, headers?: { [key: string]: string }) => void): void;
/** a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function(err, res, request, reply, settings, ttl) where: - err - internal or upstream error returned from attempting to contact the upstream proxy. - res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - request - is the incoming request object. - reply - the reply interface function. - settings - the proxy handler configuration. - ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'.*/
onResponse?(
err: any,
res: http.ServerResponse,
req: Request,
reply: IReply,
settings: IProxyHandlerConfig,
ttl: number): void;
/** if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided).*/
ttl?: number | undefined;
agent?: http.Agent | undefined;
/** sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity.*/
maxSockets?: boolean | number | undefined;
}
/** TODO: fill in joi definition */
export interface IJoi { }
/** a validation function using the signature function(value, options, next) */
export interface IValidationFunction {
(
/** the object containing the path parameters. */
value: any,
/** the server validation options. */
options: any,
/** the callback function called when validation is completed. */
next: (err: any, value: any) => void): void;
}
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
export interface IRouteFailFunction {
/** a custom error handler function with the signature 'function(request, reply, source, error)` */
(/** - the [request object]. */
request: Request,
/** the continuation reply interface. */
reply: IReply,
/** the source of the invalid field (e.g. 'path', 'query', 'payload'). */
source: string,
/** the error object prepared for the client response (including the validation function error under error.data). */
error: any): void;
}
/** Each route can be customize to change the default behavior of the request lifecycle using the following options: */
export interface <API key> {
/** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */
app?: any;
/** authentication configuration.Value can be: false to disable authentication if a default strategy is set.
a string with the name of an authentication strategy registered with server.auth.strategy().
an object */
auth?: boolean | string |
{
/** the authentication mode.Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication.Available values:
'required'authentication is required.
'optional'authentication is optional (must be valid if present).
'try'same as 'optional' but allows for invalid authentication. */
mode?: string | undefined;
/** a string array of strategy names in order they should be attempted.If only one strategy is used, strategy can be used instead with the single string value.Defaults to the default authentication strategy which is available only when a single strategy is configured. */
strategies?: string | string[] | undefined;
/** if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed.Requires a strategy with payload authentication support (e.g.Hawk).Cannot be set to a value other than 'required' when the scheme sets the options.payload to true.Available values:
falseno payload authentication.This is the default value.
'required'payload authentication required.This is the default value when the scheme sets options.payload to true.
'optional'payload authentication performed only when the client includes payload authentication information (e.g.hash attribute in Hawk). */
payload?: string | undefined;
/** the application scope required to access the route.Value can be a scope string or an array of scope strings.The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.Set to false to remove scope requirements.Defaults to no scope required. */
scope?: string | string[] | boolean | undefined;
/** the required authenticated entity type.If set, must match the entity value of the authentication credentials.Available values:
anythe authentication can be on behalf of a user or application.This is the default value.
userthe authentication must be on behalf of a user.
appthe authentication must be on behalf of an application. */
entity?: string | undefined;
/**
* an object or array of objects specifying the route access rules. Each rule is evaluated against an incoming
* request and access is granted if at least one rule matches. Each rule object must include at least one of:
*/
access?: <API key> | <API key>[] | undefined;
} | undefined;
/** an object passed back to the provided handler (via this) when called. */
bind?: any;
/** if the route method is 'GET', the route can be configured to include caching directives in the response using the following options */
cache?: <API key> | undefined;
/** the Cross- Origin Resource Sharing protocol allows browsers to make cross- origin API calls.CORS is required by web applications running inside a browser which are loaded from a different domain than the API server.CORS headers are disabled by default. To enable, set cors to true, or to an object with the following options: */
cors?: {
/** a strings array of allowed origin servers ('<API key>').The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '' character, or a single `''origin string. Defaults to any origin['*']`. */
origin?: string[] | undefined;
/** if true, matches the value of the incoming 'Origin' header to the list of origin values ('*' matches anything) and if a match is found, uses that as the value of the '<API key>' response header.When false, the origin config is returned as- is.Defaults to true. */
matchOrigin?: boolean | undefined;
/** if false, prevents the connection from returning the full list of non- wildcard origin values if the incoming origin header does not match any of the values.Has no impact if matchOrigin is set to false.Defaults to true. */
isOriginExposed?: boolean | undefined;
/** number of seconds the browser should cache the CORS response ('<API key>').The greater the value, the longer it will take before the browser checks for changes in policy.Defaults to 86400 (one day). */
maxAge?: number | undefined;
/** a strings array of allowed headers ('<API key>').Defaults to ['Authorization', 'Content-Type', 'If-None-Match']. */
headers?: string[] | undefined;
/** a strings array of additional headers to headers.Use this to keep the default headers in place. */
additionalHeaders?: string[] | undefined;
/** a strings array of allowed HTTP methods ('<API key>').Defaults to ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'OPTIONS']. */
methods?: string[] | undefined;
/** a strings array of additional methods to methods.Use this to keep the default methods in place. */
additionalMethods?: string[] | undefined;
/** a strings array of exposed headers ('<API key>').Defaults to ['WWW-Authenticate', '<API key>']. */
exposedHeaders?: string[] | undefined;
/** a strings array of additional headers to exposedHeaders.Use this to keep the default headers in place. */
<API key>?: string[] | undefined;
/** if true, allows user credentials to be sent ('<API key>').Defaults to false. */
credentials?: boolean | undefined;
/** if false, preserves existing CORS headers set manually before the response is sent.Defaults to true. */
override?: boolean | undefined;
} | undefined;
/** defines the behavior for serving static resources using the built-in route handlers for files and directories: */
files?: {/** determines the folder relative paths are resolved against when using the file and directory handlers. */
relativeTo: string;
} | undefined;
/** an alternative location for the route handler option. */
handler?: ISessionHandler | <API key> | string | IRouteHandlerConfig | undefined;
/** an optional unique identifier used to look up the route using server.lookup(). */
id?: number | undefined;
/** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */
json?: {
/** the replacer function or array.Defaults to no action. */
replacer?: Function | string[] | undefined;
/** number of spaces to indent nested object keys.Defaults to no indentation. */
space?: number | string | undefined;
/** string suffix added after conversion to JSON string.Defaults to no suffix. */
suffix?: string | undefined;
} | undefined;
/** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'.Does not work with stream responses. */
jsonp?: string | undefined;
/** determines how the request payload is processed: */
payload?: {
/** the type of payload representation requested. The value must be one of:
'data'the incoming payload is read fully into memory.If parse is true, the payload is parsed (JSON, formdecoded, multipart) based on the 'Content- Type' header.If parse is false, the raw Buffer is returned.This is the default value except when a proxy handler is used.
'stream'the incoming payload is made available via a Stream.Readable interface.If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams.File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties.
'file'the incoming payload in written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/ formdata' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleaup. */
output?: string | undefined;
/** can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are:
'application/json'
'application/<API key>'
'application/octet-stream'
'text/ *'
'multipart/form-data' */
parse?: string | boolean | undefined;
/** a string or an array of strings with the allowed mime types for the endpoint.Defaults to any of the supported mime types listed above.Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */
allow?: string | string[] | undefined;
/** a mime type string overriding the 'Content-Type' header value received.Defaults to no override. */
override?: string | undefined;
/** limits the size of incoming payloads to the specified byte count.Allowing very large payloads may cause the server to run out of memory.Defaults to 1048576 (1MB). */
maxBytes?: number | undefined;
/** payload reception timeout in milliseconds.Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response.Set to false to disable.Defaults to 10000 (10 seconds). */
timeout?: number | undefined;
/** the directory used for writing file uploads.Defaults to os.tmpDir(). */
uploads?: string | undefined;
/** determines how to handle payload parsing errors. Allowed values are:
'error'return a Bad Request (400) error response. This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action and continue processing the request. */
failAction?: string | undefined;
} | undefined;
/** pluginspecific configuration.plugins is an object where each key is a plugin name and the value is the plugin configuration. */
plugins?: IDictionary<any> | undefined;
/** an array with [route prerequisites] methods which are executed in serial or in parallel before the handler is called. */
pre?: any[] | undefined;
/** validation rules for the outgoing response payload (response body).Can only validate object response: */
response?: {
/** the default HTTP status code when the payload is empty. Value can be 200 or 204.
Note that a 200 status code is converted to a 204 only at the time or response transmission
(the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */
emptyStatusCode?: number | undefined;
/** the default response object validation rules (for all non-error responses) expressed as one of:
true - any payload allowed (no validation performed). This is the default.
false - no payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
value - the object containing the response object.
options - the server validation options.
next(err) - the callback function called when validation is completed. */
schema?: boolean | any | undefined;
/** HTTP status- codespecific validation rules.The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema.If a response status code is not present in the status object, the schema definition is used, expect for errors which are not validated by default. */
status?: { [statusCode: number]: boolean | any } | undefined;
/** the percent of responses validated (0100).Set to 0 to disable all validation.Defaults to 100 (all responses). */
sample?: number | undefined;
/** defines what to do when a response fails validation.Options are:
errorreturn an Internal Server Error (500) error response.This is the default value.
loglog the error but send the response. */
failAction?: string | undefined;
/** if true, applies the validation rule changes to the response.Defaults to false. */
modify?: boolean | undefined;
options?: any;
} | undefined;
/** sets common security headers (disabled by default).To enable set security to true or to an object with the following options */
security?: boolean | {
/** controls the '<API key>' header.If set to true the header will be set to max- age=15768000, if specified as a number the maxAge parameter will be set to that number.Defaults to true.You may also specify an object with the following fields: */
hsts?: boolean | number | {
/** the max- age portion of the header, as a number.Default is 15768000. */
maxAge?: number | undefined;
/** a boolean specifying whether to add the includeSubdomains flag to the header. */
includeSubdomains?: boolean | undefined;
/** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */
preload?: boolean | undefined;
} | undefined;
/** controls the 'X-Frame-Options' header.When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'.To use the 'allow-from' rule, you must set this to an object with the following fields: */
xframe?: {
/** either 'deny', 'sameorigin', or 'allow-from' */
rule: string;
/** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored.If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */
source: string;
} | undefined;
/** boolean that controls the 'X-XSS-PROTECTION' header for IE.Defaults to true which sets the header to equal '1; mode=block'.NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8.See here and here for more information.If you actively support old versions of IE, it may be wise to explicitly set this flag to false. */
xss?: boolean | undefined;
/** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context.Defaults to true setting the header to 'noopen'. */
noOpen?: boolean | undefined;
/** boolean controlling the '<API key>' header.Defaults to true setting the header to its only and default option, 'nosniff'. */
noSniff?: boolean | undefined;
} | undefined;
/** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265).state supports the following options: */
state?: {
/** determines if incoming 'Cookie' headers are parsed and stored in the request.state object.Defaults to true. */
parse: boolean;
/** determines how to handle cookie parsing errors.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'report the error but continue processing the request.
'ignore'take no action. */
failAction: string;
} | undefined;
/** request input validation rules for various request components.When using a Joi validation object, the values of the other inputs (i.e.headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')).Note that validation is performed in order(i.e.headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values.The validate object supports: */
validate?: {
/** validation rules for incoming request headers.Values allowed:
* trueany headers allowed (no validation performed).This is the default.
falseno headers allowed (this will cause all valid HTTP requests to fail).
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the request headers.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed.
*/
headers?: boolean | IJoi | IValidationFunction | undefined;
/** validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params.Values allowed:
trueany path parameters allowed (no validation performed).This is the default.
falseno path variables allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the path parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
params?: boolean | IJoi | IValidationFunction | undefined;
/** validation rules for an incoming request URI query component (the key- value part of the URI between '?' and '#').The query is parsed into its individual key- value pairs (using the qs module) and stored in request.query prior to validation.Values allowed:
trueany query parameters allowed (no validation performed).This is the default.
falseno query parameters allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the query parameters.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
query?: boolean | IJoi | IValidationFunction | undefined;
/** validation rules for an incoming request payload (request body).Values allowed:
trueany payload allowed (no validation performed).This is the default.
falseno payload allowed.
a Joi validation object.
a validation function using the signature function(value, options, next) where:
valuethe object containing the payload object.
optionsthe server validation options.
next(err, value)the callback function called when validation is completed. */
payload?: boolean | IJoi | IValidationFunction | undefined;
/** an optional object with error fields copied into every validation error response. */
errorFields?: any;
/** determines how to handle invalid requests.Allowed values are:
'error'return a Bad Request (400) error response.This is the default value.
'log'log the error but continue processing the request.
'ignore'take no action.
OR a custom error handler function with the signature 'function(request, reply, source, error)` where:
requestthe request object.
replythe continuation reply interface.
sourcethe source of the invalid field (e.g. 'path', 'query', 'payload').
errorthe error object prepared for the client response (including the validation function error under error.data). */
failAction?: string | IRouteFailFunction | undefined;
options?: any;
} | undefined;
/** define timeouts for processing durations: */
timeout?: {
/** response timeout in milliseconds.Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response.Disabled by default (false). */
server: boolean | number;
/** by default, node sockets automatically timeout after 2 minutes.Use this option to override this behavior.Defaults to undefined which leaves the node default unchanged.Set to false to disable socket timeouts. */
socket: boolean | number;
} | undefined;
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route description used for generating documentation (string).
*/
description?: string | undefined;
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route notes used for generating documentation (string or array of strings).
*/
notes?: string | string[] | undefined;
/** ONLY WHEN ADDING NEW ROUTES (not when setting defaults).
*route tags used for generating documentation (array of strings).
*/
tags?: string[] | undefined;
/** Enable logging of routes
*/
log?: boolean | undefined;
}
/**
* specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one rule matches
*/
export interface <API key> {
/**
* the application scope required to access the route. Value can be a scope string or an array of scope strings.
* The authenticated credentials object scope property must contain at least one of the scopes defined to access the route.
* If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character,
* that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials'
* scope must not include 'a', must include 'b', and must include on of 'c' or 'd'. You may also access properties
* on the request object (query and params} to populate a dynamic scope by using {} characters around the property name,
* such as 'user-{params.id}'. Defaults to false (no scope requirements).
*/
scope?: string | string[] | boolean | undefined;
/** the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values:
* any - the authentication can be on behalf of a user or application. This is the default value.
* user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy.
* app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy.
*/
entity?: string | undefined;
}
export type <API key> = {
/** determines the privacy flag included in clientside caching using the 'Cache-Control' header. Values are:
'Default': no privacy flag.This is the default setting.
'public': mark the response as suitable for public caching.
'private': mark the response as suitable only for private caching. */
privacy?: 'default' | 'public' | 'private' | undefined;
/** an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive. Defaults to [200]. */
statuses?: number[] | undefined;
/** a string with the value of the 'Cache-Control' header when caching is disabled. Defaults to 'no-cache'. */
otherwise?: string | undefined;
} & ({
/** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */
expiresIn: number;
} | {
/** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */
expiresAt: string;
} | {});
export interface IServerRealm {
/** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method */
modifiers: {
/** routes preferences: */
route: {
/** - the route path prefix used by any calls to server.route() from the server. */
prefix: string;
/** the route virtual host settings used by any calls to server.route() from the server. */
vhost: string;
};
};
/** the active plugin name (empty string if at the server root). */
plugin: string;
/** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */
plugins: IDictionary<any>;
/** settings overrides */
settings: {
files: {
relativeTo: any;
};
bind: any;
};
}
export interface IServerState {
/** - the cookie name string. */
name: string;
/** - are the optional cookie settings: */
options: {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/
ttl: number;
/** - sets the 'Secure' flag.Defaults to false.*/
isSecure: boolean;
/** - sets the 'HttpOnly' flag.Defaults to false.*/
isHttpOnly: boolean
/** - the path scope.Defaults to null (no path).*/
path: any;
/** - the domain scope.Defaults to null (no domain). */
domain: any;
/** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue(request: Request, next: (err: any, value: any) => void): void;
/** - encoding performs on the provided value before serialization. Options are:
'none' - no encoding. When used, the cookie value must be a string. This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON-stringified than encoded using Base64.
'form' - object value is encoded using the <API key> method.
'iron' - Encrypts and sign the value using iron.*/
encoding: string;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/
sign: {
/** - algorithm options.Defaults to require('iron').defaults.integrity.*/
integrity: any;
/** - password used for HMAC key generation.*/
password: string;
};
/** - password used for 'iron' encoding.*/
password: string;
/** - options for 'iron' encoding.Defaults to require('iron').defaults.*/
iron: any;
/** - if false, errors are ignored and treated as missing cookies.*/
ignoreErrors: boolean;
/** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/
clearInvalid: boolean;
/** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/
strictHeader: boolean;
/** - overrides the default proxy <API key> setting.*/
passThrough: any;
};
}
export interface IFileHandlerConfig {
/** a path string or function as described above.*/
path: string;
/** an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path*/
filename?: string | undefined;
/**- specifies whether to include the 'Content-Disposition' header with the response. Available values:
false - header is not included. This is the default value.
'attachment'
'inline'*/
mode?: boolean | string | undefined;
/** if true, looks for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.*/
lookupCompressed: boolean;
}
export interface IRouteHandlerConfig {
/** generates a static file endpoint for serving a single file. file can be set to:
a relative or absolute file path string (relative paths are resolved based on the route files configuration).
a function with the signature function(request) which returns the relative or absolute file path.
an object with the following options */
file?: string | IRequestHandler<void> | IFileHandlerConfig | undefined;
/** directory - generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options:
path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be:
a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string.
an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string).
a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response.
index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true.
listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false.
showHidden - optional boolean, determines if hidden files will be shown and served. Defaults to false.
redirectToSlash - optional boolean, determines if requests for a directory without a trailing slash are redirected to the same path with the missing slash. Useful for ensuring relative links inside the response are resolved correctly. Disabled when the server config router.stripTrailingSlash is true.Defaults to false.
lookupCompressed - optional boolean, instructs the file processor to look for the same filename with the '.gz' suffix for a pre-compressed version of the file to serve if the request supports content encoding. Defaults to false.
defaultExtension - optional string, appended to file requests if the requested file is not found. Defaults to no extension.*/
directory?: {
path: string | string[] | IRequestHandler<string> | IRequestHandler<string[]>;
index?: boolean | string | string[] | undefined;
listing?: boolean | undefined;
showHidden?: boolean | undefined;
redirectToSlash?: boolean | undefined;
lookupCompressed?: boolean | undefined;
defaultExtension?: string | undefined;
} | undefined;
proxy?: IProxyHandlerConfig | undefined;
view?: string | {
template: string;
context: {
payload: any;
params: any;
query: any;
pre: any;
}
} | undefined;
config?: {
handler: any;
bind: any;
app: any;
plugins: {
[name: string]: any;
};
pre: Array<() => void>;
validate: {
headers: any;
params: any;
query: any;
payload: any;
errorFields?: any;
failAction?: string | IFailAction | undefined;
};
payload: {
output: {
data: any;
stream: any;
file: any;
};
parse?: any;
allow?: string | string[] | undefined;
override?: string | undefined;
maxBytes?: number | undefined;
uploads?: number | undefined;
failAction?: string | undefined;
};
response: {
schema: any;
sample: number;
failAction: string;
};
cache: {
privacy: string;
expiresIn: number;
expiresAt: number;
};
auth: string | boolean | {
mode: string;
strategies: string[];
payload?: boolean | string | undefined;
tos?: boolean | string | undefined;
scope?: string | string[] | undefined;
entity: string;
};
cors?: boolean | undefined;
jsonp?: string | undefined;
description?: string | undefined;
notes?: string | string[] | undefined;
tags?: string[] | undefined;
} | undefined;
}
/** Route configuration
The route configuration object*/
export interface IRouteConfiguration {
/** - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option.The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.*/
path: string;
/** - (required) the HTTP method.Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'.Any HTTP method is allowed, except for 'HEAD'.Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match).
* Can be assigned an array of methods which has the same result as adding the same route with different methods manually.*/
method: string | string[];
/** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/
vhost?: string | undefined;
/** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/
handler?: ISessionHandler | <API key> | string | IRouteHandlerConfig | undefined;
/** - additional route options.*/
config?: <API key> | undefined;
}
export interface IRoute {
/** the route HTTP method. */
method: string;
/** the route path. */
path: string;
/** the route vhost option if configured. */
vhost?: string | string[] | undefined;
/** the [active realm] associated with the route.*/
realm: IServerRealm;
/** the [route options] object with all defaults applied. */
settings: <API key>;
}
export interface IServerAuthScheme {
/** authenticate(request, reply) - required function called on each incoming request configured with the authentication scheme where:
request - the request object.
reply - the reply interface the authentication method must call when done authenticating the request where:
reply(err, response, result) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
result - an object containing:
credentials - the authenticated credentials.
artifacts - optional authentication artifacts.
reply.continue(result) - is called if authentication succeeded where:
result - same object as result above.
When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route.
.If the err returned by the reply() method includes a message, no additional strategies will be attempted.
If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
var server = new Hapi.Server();
server.connection({ port: 80 });
var scheme = function (server, options) {
return {
authenticate: function (request, reply) {
var req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply(null, { credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);*/
authenticate(request: Request, reply: IReply): void;
authenticate<T>(request: Request, reply: IStrictReply<T>): void;
/** payload(request, reply) - optional function called to authenticate the request payload where:
request - the request object.
reply(err, response) - is called if authentication failed where:
err - any authentication error.
response - any authentication response action such as redirection. Ignored if err is present, otherwise required.
reply.continue() - is called if payload authentication succeeded.
When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.*/
payload?(request: Request, reply: IReply): void;
payload?<T>(request: Request, reply: IStrictReply<T>): void;
/** response(request, reply) - optional function called to decorate the response with authentication headers before the response headers or payload is written where:
request - the request object.
reply(err, response) - is called if an error occurred where:
err - any authentication error.
response - any authentication response to send instead of the current response. Ignored if err is present, otherwise required.
reply.continue() - is called if the operation succeeded.*/
response?(request: Request, reply: IReply): void;
response?<T>(request: Request, reply: IStrictReply<T>): void;
/** an optional object */
options?: {
/** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.*/
payload: boolean;
} | undefined;
}
/**the response object where:
statusCode - the HTTP status code.
headers - an object containing the headers set.
payload - the response payload string.
rawPayload - the raw response payload buffer.
raw - an object with the injection request and response objects:
req - the simulated node request object.
res - the simulated node response object.
result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string).
request - the request object.*/
export interface <API key> {
statusCode: number;
headers: IDictionary<string>;
payload: string;
rawPayload: Buffer;
raw: {
req: http.IncomingMessage;
res: http.ServerResponse
};
result: any;
request: Request;
}
export interface IServerInject {
(options: string | <API key>, callback: (res: <API key>) => void): void;
(options: string | <API key>): Promise<<API key>>;
}
export interface <API key> {
/** the request HTTP method (e.g. 'POST'). Defaults to 'GET'.*/
method: string;
/** the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers.*/
url: string;
/** an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default Shot headers.*/
headers?: IDictionary<string> | undefined;
/** n optional string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided.*/
payload?: string | {} | Buffer | undefined;
/** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials.*/
credentials?: any;
/** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.*/
artifacts?: any;
/** sets the initial value of request.app*/
app?: any;
/** sets the initial value of request.plugins*/
plugins?: any;
/** allows access to routes with config.isInternal set to true. Defaults to false.*/
allowInternals?: boolean | undefined;
/** sets the remote address for the incoming connection.*/
remoteAddress?: boolean | undefined;
/**object with options used to simulate client request stream conditions for testing:
error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
end - if false, does not end the stream. Defaults to true.*/
simulate?: {
error: boolean;
close: boolean;
end: boolean;
} | undefined;
}
/** host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.*/
export interface IConnectionTable {
info: any;
labels: any;
table: IRoute[];
}
export interface ICookieSettings {
/** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/
ttl?: number | undefined;
/** - sets the 'Secure' flag.Defaults to false.*/
isSecure?: boolean | undefined;
/** - sets the 'HttpOnly' flag.Defaults to false.*/
isHttpOnly?: boolean | undefined;
/** - the path scope.Defaults to null (no path).*/
path?: string | undefined;
/** - the domain scope.Defaults to null (no domain).*/
domain?: any;
/** - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value.The value can be a function with signature function(request, next) where:
request - the request object.
next - the continuation function using the function(err, value) signature.*/
autoValue?(request: Request, next: (err: any, value: any) => void): void;
/** - encoding performs on the provided value before serialization.Options are:
'none' - no encoding.When used, the cookie value must be a string.This is the default value.
'base64' - string value is encoded using Base64.
'base64json' - object value is JSON- stringified than encoded using Base64.
'form' - object value is encoded using the x- www - form - urlencoded method. */
encoding?: string | undefined;
/** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:
integrity - algorithm options.Defaults to require('iron').defaults.integrity.
password - password used for HMAC key generation. */
sign?: { integrity: any; password: string; } | undefined;
password?: string | undefined;
iron?: any;
ignoreErrors?: boolean | undefined;
clearInvalid?: boolean | undefined;
strictHeader?: boolean | undefined;
passThrough?: any;
}
/** method - the method function with the signature is one of:
function(arg1, arg2, ..., argn, next) where:
arg1, arg2, etc. - the method function arguments.
next - the function called when the method is done with the signature function(err, result, ttl) where:
err - error response if the method failed.
result - the return value.
ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
function(arg1, arg2, ..., argn) where:
arg1, arg2, etc. - the method function arguments.
the callback option is set to false.
the method must returns a value (result, Error, or a promise) or throw an Error.*/
export interface IServerMethod {
// (): void;
// (next: (err: any, result: any, ttl: number) => void): void;
// (arg1: any): void;
// (arg1: any, arg2: any, next: (err: any, result: any, ttl: number) => void): void;
// (arg1: any, arg2: any): void;
(...args: any[]): void;
}
/** options - optional configuration:
bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered.
cache - the same cache configuration used in server.cache().
callback - if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true.
generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/
export interface <API key> {
bind?: any;
cache?: <API key> | undefined;
callback?: boolean | undefined;
generateKey?(args: any[]): string;
}
/** Request object
The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle.
Request events
The request object supports the following events:
'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the request payload finished reading. The event method signature is function ().
'disconnect' - emitted when a request errors or aborts unexpectedly.
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
var hash = Crypto.createHash('sha1');
request.on('peek', function (chunk) {
hash.update(chunk);
});
request.once('finish', function () {
console.log(hash.digest('hex'));
});
request.once('disconnect', function () {
console.error('request aborted');
});
return reply.continue();
});*/
export class Request extends Events.EventEmitter {
/** <API key> state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** authentication information*/
auth: {
/** true is the request has been successfully authenticated, otherwise false.*/
isAuthenticated: boolean;
/** the credential object received during the authentication process. The presence of an object does not mean successful authentication. can be set in the validate function's callback.*/
credentials: any;
/** an artifact object received from the authentication strategy and used in <API key> actions.*/
artifacts: any;
/** the route authentication mode.*/
mode: any;
/** the authentication error is failed and mode set to 'try'.*/
error: any;
};
/** the connection used by this request*/
connection: ServerConnection;
/** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains.*/
domain: any;
/** the raw request headers (references request.raw.headers).*/
headers: IDictionary<string>;
/** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/
id: string;
/** request information */
info: {
/** the request preferred encoding. */
acceptEncoding: string;
/** if CORS is enabled for the route, contains the following: */
cors: {
isOriginMatch: boolean; /** true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */
};
/** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
host: string;
/** the hostname part of the 'Host' header (e.g. 'example.com').*/
hostname: string;
/** request reception timestamp. */
received: number;
/** content of the HTTP 'Referrer' (or 'Referer') header. */
referrer: string;
/** remote client IP address. */
remoteAddress: string;
/** remote client port. */
remotePort: number;
/** request response timestamp (0 is not responded yet). */
responded: number;
};
/** the request method in lower case (e.g. 'get', 'post'). */
method: string;
/** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */
mime: string;
/** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.*/
orig: {
params: any;
query: any;
payload: any;
};
/** an object where each key is a path parameter name with matching value as described in Path parameters.*/
params: IDictionary<string>;
/** an array containing all the path params values in the order they appeared in the path.*/
paramsArray: string[];
/** the request URI's path component. */
path: string;
/** the request payload based on the route payload.output and payload.parse settings.*/
payload: stream.Readable | Buffer | any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state.*/
plugins: any;
/** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses.*/
pre: IDictionary<any>;
/** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects).*/
response: Response;
preResponses: any;
/**an object containing the query parameters.*/
query: any;
/** an object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.*/
raw: {
req: http.IncomingMessage;
res: http.ServerResponse;
};
/** the route public interface.*/
route: IRoute;
/** the server object. */
server: Server;
/** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */
state: any;
/** complex object contining details on the url */
url: {
/** null when i tested */
auth: any;
/** null when i tested */
hash: any;
/** null when i tested */
host: any;
/** null when i tested */
hostname: any;
href: string;
path: string;
/** path without search*/
pathname: string;
/** null when i tested */
port: any;
/** null when i tested */
protocol: any;
/** querystring parameters*/
query: IDictionary<string>;
/** querystring parameters as a string*/
search: string;
/** null when i tested */
slashes: any;
};
/** request.setUrl(url)
Available only in 'onRequest' extension methods.
Changes the request URI before the router begins processing the request where:
url - the new request path value.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});*/
setUrl(url: string | url.Url): void;
/** request.setMethod(method)
Available only in 'onRequest' extension methods.
Changes the request method before the router begins processing the request where:
method - is the request HTTP method (e.g. 'GET').
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to 'GET'
request.setMethod('GET');
return reply.continue();
});*/
setMethod(method: string): void;
/** request.log(tags, [data, [timestamp]])
Always available.
Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request', function (request, event, tags) {
if (tags.error) {
console.log(event);
}
});
var handler = function (request, reply) {
request.log(['test', 'error'], 'Test event');
return reply();
};
*/
log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/
tags: string | string[],
/** an optional message string or object with the application data being logged.*/
data?: any,
/** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/
timestamp?: number): void;
/** request.getLog([tags], [internal])
Always available.
Returns an array containing the events matching any of the tags specified (logical OR)
request.getLog();
request.getLog('error');
request.getLog(['error', 'auth']);
request.getLog(['error'], true);
request.getLog(false);*/
getLog(/** is a single tag string or array of tag strings. If no tags specified, returns all events.*/
tags?: string,
/** filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined).*/
internal?: boolean): string[];
/** request.tail([name])
Available until immediately after the 'response' event is emitted.
Adds a request tail which has to complete before the request lifecycle is complete where:
name - an optional tail name used for logging purposes.
Returns a tail function which must be called when the tail activity is completed.
Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it).
When all tails completed, the server emits a 'tail' event.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
var get = function (request, reply) {
var dbTail = request.tail('write to database');
db.save('key', 'value', function () {
dbTail();
});
return reply('Success!');
};
server.route({ method: 'GET', path: '/', handler: get });
server.on('tail', function (request) {
console.log('Request completed including db activity');
});*/
tail(/** an optional tail name used for logging purposes.*/
name?: string): Function;
}
/** Response events
The response object supports the following events:
'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
var Crypto = require('crypto');
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onPreResponse', function (request, reply) {
var response = request.response;
if (response.isBoom) {
return reply();
}
var hash = Crypto.createHash('sha1');
response.on('peek', function (chunk) {
hash.update(chunk);
});
response.once('finish', function () {
console.log(hash.digest('hex'));
});
return reply.continue();
});*/
export class Response extends Events.EventEmitter {
isBoom: boolean;
/** the HTTP response status code. Defaults to 200 (except for errors).*/
statusCode: number;
/** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepare for transmission.*/
headers: IDictionary<string>;
/** the value provided using the reply interface.*/
source: any;
/** a string indicating the type of source with available values:
'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view).
'buffer' - a Buffer.
'view' - a view generated with reply.view().
'file' - a file generated with reply.file() of via the directory handler.
'stream' - a Stream.
'promise' - a Promise object. */
variety: string;
/** <API key> state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name].*/
app: any;
/** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */
plugins: any;
/** settings - response handling flags:
charset - the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'.
encoding - the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'.
passThrough - if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true.
stringify - options used for source value requiring stringification. Defaults to no replacer and no space padding.
ttl - if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override.
varyEtag - if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present.*/
settings: {
charset: string;
encoding: string;
passThrough: boolean;
stringify: any;
ttl: number;
varyEtag: boolean;
};
/** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
length - the header value. Must match the actual payload size.*/
bytes(length: number): Response;
/** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/
charset(charset: string): Response;
/** sets the HTTP status code where:
statusCode - the HTTP status code.*/
code(statusCode: number): Response;
/** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/
created(uri: string): Response;
/** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/
encoding(encoding: string): Response;
/** etag(tag, options) - sets the representation entity tag where:
tag - the entity tag string without the double-quote.
options - optional settings where:
weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false.
vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/
etag(tag: string, options: {
weak: boolean; vary: boolean;
}): Response;
/**header(name, value, options) - sets an HTTP header where:
name - the header name.
value - the header value.
options - optional settings where:
append - if true, the value is appended to any existing header value using separator. Defaults to false.
separator - string used as separator when appending to an exiting value. Defaults to ','.
override - if false, the header value is not set if an existing value present. Defaults to true.*/
header(name: string, value: string, options?: IHeaderOptions): Response;
/** hold() - puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. */
hold(): Response;
/** location(uri) - sets the HTTP 'Location' header where:
uri - an absolute or relative URI used as the 'Location' header value.*/
location(uri: string): Response;
/** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where:
uri - an absolute or relative URI used to redirect the client to another resource. */
redirect(uri: string): Response;
/** replacer(method) - sets the JSON.stringify() replacer argument where:
method - the replacer function or array. Defaults to none.*/
replacer(method: Function | Function[]): Response;
/** spaces(count) - sets the JSON.stringify() space argument where:
count - the number of spaces to indent nested object keys. Defaults to no indentation. */
spaces(count: number): Response;
/**state(name, value, [options]) - sets an HTTP cookie where:
name - the cookie name.
value - the cookie value. If no encoding is defined, must be a string.
options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
state(name: string, value: string, options?: any): Response;
/** send() - resume the response which will be transmitted in the next tick. Available only after response.hold() is called and until response.send() is invoked once. */
send(): void;
/** sets a string suffix when the response is process via JSON.stringify().*/
suffix(suffix: string): void;
/** overrides the default route cache expiration rule for this response instance where:
msec - the time-to-live value in milliseconds.*/
ttl(msec: number): void;
/** type(mimeType) - sets the HTTP 'Content-Type' header where:
mimeType - is the mime type. Should only be used to override the built-in default for each response type. */
type(mimeType: string): Response;
/** clears the HTTP cookie by setting an expired value where:
name - the cookie name.
options - optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/
unstate(name: string, options?: { [key: string]: string }): Response;
/** adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
header - the HTTP request header name.*/
vary(header: string): void;
}
/** When using the redirect() method, the response object provides these additional methods */
export class ResponseRedirect extends Response {
/** sets the status code to 302 or 307 (based on the rewritable() setting) where:
isTemporary - if false, sets status to permanent. Defaults to true.*/
temporary(isTemporary: boolean): void;
/** sets the status code to 301 or 308 (based on the rewritable() setting) where:
isPermanent - if true, sets status to temporary. Defaults to false. */
permanent(isPermanent: boolean): void;
/** sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments:
isRewritable - if false, sets to non-rewritable. Defaults to true.
Permanent Temporary
Rewritable 301 302(1)
Non-rewritable 308(2) 307
Notes: 1. Default value. 2. Proposed code, not supported by all clients. */
rewritable(isRewritable: boolean): void;
}
/** info about a server connection */
export interface <API key> {
/** - a unique connection identifier (using the format '{hostname}:{pid}:{now base36}').*/
id: string;
/** - the connection creation timestamp.*/
created: number;
/** - the connection start timestamp (0 when stopped).*/
started: number;
/** the connection port based on the following rules:
the configured port value before the server has been started.
the actual port assigned when no port is configured or set to 0 after the server has been started.*/
port: number;
/** - the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'.*/
host: string;
/** - the active IP address the connection was bound to after starting.Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket).*/
address: string;
/** - the protocol used:
'http' - HTTP.
'https' - HTTPS.
'socket' - UNIX domain socket or Windows named pipe.*/
protocol: string;
uri: string;
}
/**
* undocumented. The connection object constructed after calling server.connection();
* can be accessed via server.connections; or request.connection;
*/
export class ServerConnection extends Events.EventEmitter {
domain: any;
_events: { route: Function, domain: Function, _events: Function, _eventsCount: Function, _maxListeners: Function };
_eventsCount: number;
settings: <API key>;
server: Server;
/** ex: "tcp" */
type: string;
_started: boolean;
/** dictionary of sockets */
_connections: { [ip_port: string]: any };
_onConnection: Function;
registrations: any;
_extensions: any;
_requestCounter: { value: number; min: number; max: number };
_load: any;
states: {
settings: any; cookies: any; names: any[]
};
auth: { connection: ServerConnection; _schemes: any; _strategies: any; settings: any; api: any; };
_router: any;
MSPluginsCollection: any;
applicationCache: any;
addEventListener: any;
info: <API key>;
}
export type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse";
export type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop";
export class Server extends Events.EventEmitter {
constructor(options?: IServerOptions);
/** Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object.
var Hapi = require('hapi');
server = new Hapi.Server();
server.app.key = 'value';
var handler = function (request, reply) {
return reply(request.server.app.key);
}; */
app: any;
connections: ServerConnection[];
info: <API key>;
/** An object containing the process load metrics (when load.sampleInterval is enabled):
rss - RSS memory usage.
var Hapi = require('hapi');
var server = new Hapi.Server({ load: { sampleInterval: 1000 } });
console.log(server.load.rss);*/
load: {
/** - event loop delay milliseconds.*/
eventLoopDelay: number;
/** - V8 heap usage.*/
heapUsed: number;
};
/** When the server contains exactly one connection, listener is the node HTTP server object of the sole connection.
When the server contains more than one connection, each server.connections array member provides its own connection.listener.
var Hapi = require('hapi');
var SocketIO = require('socket.io');
var server = new Hapi.Server();
server.connection({ port: 80 });
var io = SocketIO.listen(server.listener);
io.sockets.on('connection', function(socket) {
socket.emit({ msg: 'welcome' });
});*/
listener: http.Server;
methods: IDictionary<Function>;
mime: any;
plugins: IDictionary<any>;
/** server.realm
The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties.
modifiers - when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes:
route - routes preferences:
prefix - the route path prefix used by any calls to server.route() from the server.
vhost - the route virtual host settings used by any calls to server.route() from the server.
plugin - the active plugin name (empty string if at the server root).
plugins - plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state.
settings - settings overrides:
files.relativeTo
bind
The server.realm object should be considered read-only and must not be changed directly except for the plugins property can be directly manipulated by the plugins (each setting its own under plugins[name]).
exports.register = function (server, options, next) {
console.log(server.realm.modifiers.route.prefix);
return next();
};*/
realm: IServerRealm;
/** server.root
The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()).*/
root: Server;
settings: IServerOptions;
version: string;
/** server.after(method, [dependencies])
Adds a method to be called after all the plugin dependencies have been registered and before the server starts (only called if the server is started) where:
after - the method with signature function(plugin, next) where:
server - server object the after() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error which is returned back via the server.start() callback.
dependencies - a string or array of string with the plugin names to call this method after their after() methods. There is no requirement for the other plugins to be registered. Setting dependencies only arranges the after methods in the specified order.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.after(function () {
// Perform some pre-start logic
});
server.start(function (err) {
// After method already executed
});
server.auth.default(options)*/
after(method: (plugin: any, next: (err: any) => void) => void, dependencies: string | string[]): void;
auth: {
/** server.auth.api
An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function.
When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object.
const server = new Hapi.Server();
server.connection({ port: 80 });
const scheme = function (server, options) {
return {
api: {
settings: {
x: 5
}
},
authenticate: function (request, reply) {
const req = request.raw.req;
const authorization = req.headers.authorization;
if (!authorization) {
return reply(Boom.unauthorized(null, 'Custom'));
}
return reply.continue({ credentials: { user: 'john' } });
}
};
};
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
console.log(server.auth.api.default.settings.x); // 5
*/
api: {
[index: string]: any;
}
/** server.auth.default(options)
Sets a default strategy which is applied to every route where:
options - a string with the default strategy name or an object with a specified strategy or strategies using the same format as the route auth handler options.
The default does not apply when the route config specifies auth as false, or has an authentication strategy configured. Otherwise, the route authentication config is applied to the defaults. Note that the default only applies at time of route configuration, not at runtime. Calling default() after adding a route will have no impact on routes added prior.
The default auth strategy configuration can be accessed via connection.auth.settings.default.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.auth.default('default');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply(request.auth.credentials.user);
}
});*/
default(options: string): void;
default(options: { strategy: string }): void;
default(options: { strategies: string[] }): void;
/** server.auth.scheme(name, scheme)
Registers an authentication scheme where:
name - the scheme name.
scheme - the method implementing the scheme with signature function(server, options) where:
server - a reference to the server object the scheme is added to.
options - optional scheme settings used to instantiate a strategy.*/
scheme(
name: string,
/**
* When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted if configured for the route. If the err returned by the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference.
* n the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'.
* server = new Hapi.Server();
* server.connection({ port: 80 });
* scheme = function (server, options) {
* urn {
* authenticate: function (request, reply) {
* req = request.raw.req;
* var authorization = req.headers.authorization;
* if (!authorization) {
* return reply(Boom.unauthorized(null, 'Custom'));
* }
* urn reply(null, { credentials: { user: 'john' } });
* }
* };
* };
*/
scheme: (server: Server, options: any) => IServerAuthScheme): void;
/**
* server.auth.strategy(name, scheme, [mode], [options])
* Registers an authentication strategy where:
* name - the strategy name.
* scheme - the scheme name (must be previously registered using server.auth.scheme()).
* mode - if true, the scheme is automatically assigned as a required strategy to any route without an auth config. Can only be assigned to a single server strategy. Value must be true (which is the same as 'required') or a valid authentication mode ('required', 'optional', 'try'). Defaults to false.
* options - scheme options based on the scheme requirements.
* var server = new Hapi.Server();
* server.connection({ port: 80 });
* server.auth.scheme('custom', scheme);
* server.auth.strategy('default', 'custom');
* server.route({
* method: 'GET',
* path: '/',
* config: {
* auth: 'default',
* handler: function (request, reply) {
* return reply(request.auth.credentials.user);
* }
* }
* });
*/
strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void;
strategy(name: string, scheme: string, mode?: boolean | string): void;
strategy(name: string, scheme: string, options?: any): void;
/** server.auth.test(strategy, request, next)
Tests a request against an authentication strategy where:
strategy - the strategy name registered with server.auth.strategy().
request - the request object.
next - the callback function with signature function(err, credentials) where:
err - the error if authentication failed.
credentials - the authentication credentials object if authentication was successful.
Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties.
var server = new Hapi.Server();
server.connection({ port: 80 });
server.auth.scheme('custom', scheme);
server.auth.strategy('default', 'custom');
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
request.server.auth.test('default', request, function (err, credentials) {
if (err) {
return reply({ status: false });
}
return reply({ status: true, user: credentials.name });
});
}
});*/
test(strategy: string, request: Request, next: (err: any, credentials: any) => void): void;
};
/** server.bind(context)
Sets a global context used as the default bind object when adding a route or an extension where:
context - the object used to bind this in handler and extension methods.
When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set.
var handler = function (request, reply) {
return reply(this.message);
};
exports.register = function (server, options, next) {
var bind = {
message: 'hello'
};
server.bind(bind);
server.route({ method: 'GET', path: '/', handler: handler });
return next();
};*/
bind(context: any): void;
cache(options: <API key>): void;
connection(options: <API key>): Server;
/** server.decorate(type, property, method, [options])
Extends various framework interfaces with custom methods where:
type - the interface being decorated. Supported types:
'reply' - adds methods to the reply interface.
'server' - adds methods to the Server object.
property - the object decoration key name.
method - the extension function.
options - if the type is 'request', supports the following optional settings:
'apply' - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration.
Note that decorations apply to the entire server and all its connections regardless of current selection.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.decorate('reply', 'success', function () {
return this.response({ status: 'ok' });
});
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
return reply.success();
}
});*/
decorate(type: string, property: string, method: Function, options?: { apply: boolean }): void;
/** server.dependency(dependencies, [after])
Used within a plugin to declares a required dependency on other plugins where:
dependencies - a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is started. Does not provide version dependency which should be implemented using npm peer dependencies.
after - an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where:
server - the server the dependency() method was called on.
next - the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where:
err - internal error condition, which is returned back via the server.start() callback.
exports.register = function (server, options, next) {
server.dependency('yar', after);
return next();
};
var after = function (server, next) {
// Additional plugin registration logic
return next();
};*/
dependency(dependencies: string | string[], after?: (server: Server, next: (err: any) => void) => void): void;
/** server.expose(key, value)
Used within a plugin to expose a property via server.plugins[name] where:
key - the key assigned (server.plugins[name][key]).
value - the value assigned.
exports.register = function (server, options, next) {
server.expose('util', function () { console.log('something'); });
return next();
};*/
expose(key: string, value: any): void;
/** server.expose(obj)
Merges a deep copy of an object into to the existing content of server.plugins[name] where:
obj - the object merged into the exposed properties container.
exports.register = function (server, options, next) {
server.expose({ util: function () { console.log('something'); } });
return next();
};*/
expose(obj: any): void;
/** server.ext(event, method, [options])
Registers an extension function in one of the available extension points where:
event - the event name.
method - a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is function(request, reply) where:
request - the request object. NOTE: Access the Response via request.response
reply - the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response.
this - the object provided via options.bind or the current active context set with server.bind().
options - an optional object with the following:
before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added.
after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added.
bind - a context object passed back to the provided method (via this) when called.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.ext('onRequest', function (request, reply) {
// Change all requests to '/test'
request.setUrl('/test');
return reply.continue();
});
var handler = function (request, reply) {
return reply({ status: 'ok' });
};
server.route({ method: 'GET', path: '/test', handler: handler });
server.start();
// All requests will get routed to '/test'*/
ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext<T>(event: RequestExtPoints, method: (request: Request, reply: IStrictReply<T>, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void;
/** server.handler(name, method)
Registers a new handler type to be used in routes where:
name - string name for the handler being registered. Cannot override the built-in handler types (directory, file, proxy, and view) or any previously registered type.
method - the function used to generate the route handler using the signature function(route, options) where:
route - the route public interface object.
options - the configuration object provided in the handler config.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
// Defines new handler for routes on this server
server.handler('test', function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
});
server.route({
method: 'GET',
path: '/',
handler: { test: { msg: 'test' } }
});
server.start();
The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ host: 'localhost', port: 8000 });
var handler = function (route, options) {
return function (request, reply) {
return reply('new handler: ' + options.msg);
}
};
// Change the default payload processing for this handler
handler.defaults = {
payload: {
output: 'stream',
parse: false
}
};
server.handler('test', handler);*/
handler<THandlerConfig>(name: string, method: (route: IRoute, options: THandlerConfig) => ISessionHandler): void;
/** server.initialize([callback])
Initializes the server (starts the caches, finalizes plugin registration) but does not start listening
on the connection ports, where:
- `callback` - the callback method when server initialization is completed or failed with the signature
`function(err)` where:
- `err` - any initialization error condition.
If no `callback` is provided, a `Promise` object is returned.
Note that if the method fails and the callback includes an error, the server is considered to be in
an undefined state and should be shut down. In most cases it would be impossible to fully recover as
the various plugins, caches, and other event listeners will get confused by repeated attempts to
start the server or make assumptions about the healthy state of the environment. It is recommended
to assert that no error has been returned after calling `initialize()` to abort the process when the
server fails to start properly. If you must try to resume after an error, call `server.stop()`
first to reset the server state.
*/
initialize(callback?: (error: any) => void): Promise<void>;
inject: IServerInject;
/** server.log(tags, [data, [timestamp]])
Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are:
tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
data - an optional message string or object with the application data being logged.
timestamp - an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('log', function (event, tags) {
if (tags.error) {
console.log(event);
}
});
server.log(['test', 'error'], 'Test event');*/
log(tags: string | string[], data?: string | any, timestamp?: number): void;
/**server.lookup(id)
When the server contains exactly one connection, looks up a route configuration where:
id - the route identifier as set in the route options.
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.lookup('root');
When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method.*/
lookup(id: string): IRoute;
/** server.match(method, path, [host])
When the server contains exactly one connection, looks up a route configuration where:
method - the HTTP method (e.g. 'GET', 'POST').
path - the requested path (must begin with '/').
host - optional hostname (to match against routes with vhost).
returns the route public interface object if found, otherwise null.
var server = new Hapi.Server();
server.connection();
server.route({
method: 'GET',
path: '/',
config: {
handler: function (request, reply) { return reply(); },
id: 'root'
}
});
var route = server.match('get', '/');
When the server contains more than one connection, each server.connections array member provides its own connection.match() method.*/
match(method: string, path: string, host?: string): IRoute;
/** server.method(name, method, [options])
Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module.
Methods are registered via server.method(name, method, [options])
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Simple arguments
var add = function (a, b, next) {
return next(null, a + b);
};
server.method('sum', add, { cache: { expiresIn: 2000 } });
server.methods.sum(4, 5, function (err, result) {
console.log(result);
});
// Object argument
var addArray = function (array, next) {
var sum = 0;
array.forEach(function (item) {
sum += item;
});
return next(null, sum);
};
server.method('sumObj', addArray, {
cache: { expiresIn: 2000 },
generateKey: function (array) {
return array.join(',');
}
});
server.methods.sumObj([5, 6], function (err, result) {
console.log(result);
});
// Synchronous method with cache
var addSync = function (a, b) {
return a + b;
};
server.method('sumSync', addSync, { cache: { expiresIn: 2000 }, callback: false });
server.methods.sumSync(4, 5, function (err, result) {
console.log(result);
}); */
method(/** a unique method name used to invoke the method via server.methods[name]. When configured with caching enabled, server.methods[name].cache.drop(arg1, arg2, ..., argn, callback) can be used to clear the cache for a given key. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get.*/
name: string,
method: IServerMethod,
options?: <API key>): void;
/**server.method(methods)
Registers a server method function as described in server.method() using a configuration object where:
methods - an object or an array of objects where each one contains:
name - the method name.
method - the method function.
options - optional settings.
var add = function (a, b, next) {
next(null, a + b);
};
server.method({
name: 'sum',
method: add,
options: {
cache: {
expiresIn: 2000
}
}
});*/
method(methods: {
name: string; method: IServerMethod; options?: <API key> | undefined
} | Array<{
name: string; method: IServerMethod; options?: <API key> | undefined
}>): void;
/**server.path(relativeTo)
Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where:
relativeTo - the path prefix added to any relative file path starting with '.'.
Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set.
exports.register = function (server, options, next) {
server.path(__dirname + '../static');
server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } });
next();
};*/
path(relativeTo: string): void;
/**
* server.register(plugins, [options], callback)
* Registers a plugin where:
* plugins - an object or array of objects where each one is either:
* a plugin registration function.
* an object with the following:
* register - the plugin registration function.
* options - optional options passed to the registration function when called.
* options - optional registration options (different from the options passed to the registration function):
* select - a string or array of string labels used to pre-select connections for plugin registration.
* routes - modifiers applied to each route added by the plugin:
* prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix.
* vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
* callback - the callback function with signature function(err) where:
* err - an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework.
*
* If no callback is provided, a Promise object is returned.
*/
register(
plugins: any | any[],
options: {
select?: string | string[] | undefined;
routes: {
prefix: string; vhost?: string | string[] | undefined
};
},
callback: (err: any) => void): void;
register(
plugins: any | any[],
options: {
select?: string | string[] | undefined;
routes: {
prefix: string; vhost?: string | string[] | undefined
};
}): Promise<any>;
register(plugins: any | any[], callback: (err: any) => void): void;
register(plugins: any | any[]): Promise<any>;
/**server.render(template, context, [options], callback)
Utilizes the server views manager to render a template where:
template - the template filename and path, relative to the views manager templates path (path or relativeTo).
context - optional object used by the template to render context-specific result. Defaults to no context ({}).
options - optional object used to override the views manager configuration.
callback - the callback function with signature function (err, rendered, config) where:
err - the rendering error if any.
rendered - the result view string.
config - the configuration used to render the template.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.views({
engines: { html: require('handlebars') },
path: __dirname + '/templates'
});
var context = {
title: 'Views Example',
message: 'Hello, World'
};
server.render('hello', context, function (err, rendered, config) {
console.log(rendered);
});*/
render(template: string, context: any, options: any, callback: (err: any, rendered: any, config: any) => void): void;
/** server.route(options)
Adds a connection route where:
options - a route configuration object or an array of configuration objects.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.route({ method: 'GET', path: '/', handler: function (request, reply) { return reply('ok'); } });
server.route([
{ method: 'GET', path: '/1', handler: function (request, reply) { return reply('ok'); } },
{ method: 'GET', path: '/2', handler: function (request, reply) { return reply('ok'); } }
]);*/
route(options: IRouteConfiguration): void;
route(options: IRouteConfiguration[]): void;
/**server.select(labels)
Selects a subset of the server's connections where:
labels - a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration.
Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, labels: ['a'] });
server.connection({ port: 8080, labels: ['b'] });
server.connection({ port: 8081, labels: ['c'] });
server.connection({ port: 8082, labels: ['c','d'] });
var a = server.select('a'); // The server with port 80
var ab = server.select(['a','b']); // A list of servers containing the server with port 80 and the server with port 8080
var c = server.select('c'); // A list of servers containing the server with port 8081 and the server with port 8082 */
select(labels: string | string[]): Server | Server[];
/** server.start([callback])
Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false), where:
callback - optional callback when server startup is completed or failed with the signature function(err) where:
err - any startup error condition.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.start(function (err) {
console.log('Server started at: ' + server.info.uri);
});*/
start(callback?: (err: any) => void): Promise<void>;
/** server.state(name, [options])
HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions
State defaults can be modified via the server connections.routes.state configuration option.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
// Set cookie definition
server.state('session', {
ttl: 24 * 60 * 60 * 1000, // One day
isSecure: true,
path: '/',
encoding: 'base64json'
});
// Set state in route handler
var handler = function (request, reply) {
var session = request.state.session;
if (!session) {
session = { user: 'joe' };
}
session.last = Date.now();
return reply('Success').state('session', session);
};
Registered cookies are automatically parsed when received. Parsing rules depends on the route state.parse configuration. If an incoming registered cookie fails parsing, it is not included in request.state, regardless of the state.failAction setting. When state.failAction is set to 'log' and an invalid cookie value is received, the server will emit a 'request-internal' event. To capture these errors subscribe to the 'request-internal' events and filter on 'error' and 'state' tags:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.on('request-internal', function (request, event, tags) {
if (tags.error && tags.state) {
console.error(event);
}
}); */
state(name: string, options?: ICookieSettings): void;
/** server.stop([options], [callback])
Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where:
options - optional object with:
timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds).
callback - optional callback method with signature function() which is called once all the connections have ended and it is safe to exit the process.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80 });
server.stop({ timeout: 60 * 1000 }, function () {
console.log('Server stopped');
});*/
stop(options?: { timeout: number }, callback?: () => void): Promise<void>;
/**server.table([host])
Returns a copy of the routing table where:
host - optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
The return value is an array where each item is an object containing:
info - the connection.info the connection the table was generated for.
labels - the connection labels.
table - an array of routes where each route contains:
settings - the route config with defaults applied.
method - the HTTP method in lower case.
path - the route path.
Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result.
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.table();
When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection:
var Hapi = require('hapi');
var server = new Hapi.Server();
server.connection({ port: 80, host: 'example.com' });
server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } });
var table = server.connections[0].table();
//[
// {
// method: 'get',
// path: '/example',
// settings: { ... }
// }
//]
*/
table(host?: any): IConnectionTable;
/**server.views(options)
Initializes the server views manager
var Hapi = require('hapi');
var server = new Hapi.Server();
server.views({
engines: {
html: require('handlebars'),
jade: require('jade')
},
path: '/static/templates'
});
When server.views() is called within a plugin, the views manager is only available to plugins methods.*/
views(options: <API key>): void;
} |
require 'minitest_helper'
describe "#builtin_templates" do
let(:connection) do
VCR.use_cassette('open_connection') do
Fog::Compute.new(:provider => 'XenServer',
:xenserver_url => '192.168.10.2',
:xenserver_username => 'root',
:xenserver_password => '123456')
end
end
it "should return all builtin templates" do
VCR.use_cassette('builtin_templates') do
connection.builtin_templates.size.must_equal 63
end
end
end |
{% extends "base.html" %}
{% block title %}{{ page.title }}{% endblock %}
{% block content %}
<section id="content" class="body">
<h1 class="entry-title">{{ page.title }}</h1>
{% if PDF_PROCESSOR %}
<a href="{{ SITEURL }}/pdf/{{ page.slug }}.pdf">
get the pdf
</a>
{% endif %}
{{ page.content }}
</section>
{% endblock %} |
// TWTRUser.h
#import <Foundation/Foundation.h>
/**
* Represents a user on Twitter.
*/
@interface TWTRUser : NSObject <NSCoding, NSCopying>
# pragma mark - Properties
/**
* The ID of the Twitter User.
*/
@property (nonatomic, copy, readonly) NSString *userID;
@property (nonatomic, copy, readonly) NSString *name;
@property (nonatomic, copy, readonly) NSString *screenName;
/**
* Whether the user has been verified by Twitter.
*/
@property (nonatomic, assign, readonly) BOOL isVerified;
/**
* Whether the user is protected.
*/
@property (nonatomic, assign, readonly) BOOL isProtected;
/**
* The HTTPS URL of the user's profile image.
*/
@property (nonatomic, copy, readonly) NSString *profileImageURL;
/**
* The URL of a smaller version of the user's profile image.
*/
@property (nonatomic, copy, readonly) NSString *profileImageMiniURL;
/**
* The URL of a larger version of the user's profile image.
*/
@property (nonatomic, copy, readonly) NSString *<API key>;
/**
* The formatted version of the user's `screenName` with the `@` sign for display purposes.
*/
@property (nonatomic, copy, readonly) NSString *formattedScreenName;
# pragma mark - Init
/**
* Creates a Twitter user object from the dictionary of Twitter API JSON response.
*
* @param dictionary A parsed dictionary of a single Twitter Tweet API JSON response.
*
* @return An initialized TWTRUser instance.
*/
- (instancetype)<API key>:(NSDictionary *)dictionary;
/**
* Creates an array of Twitter User instances from the array of Twitter API JSON response.
*
* @param array A parsed array of Twitter User API JSON responses.
*
* @return An array of initialized TWTRTweet instances.
*/
+ (NSArray *)usersWithJSONArray:(NSArray *)array;
@end |
require "spec_helper"
describe Mongoid::Errors::InvalidDatabase do
describe "#message" do
let(:error) do
described_class.new("Test")
end
it "contains the problem in the message" do
expect(error.message).to include(
"Database should be a Mongo::DB, not String."
)
end
it "contains the summary in the message" do
expect(error.message).to include(
"When setting a master database in the Mongoid configuration"
)
end
it "contains the resolution in the message" do
expect(error.message).to include(
"Make sure that when setting the configuration programatically"
)
end
end
end |
namespace System.Activities
{
using System;
using System.ComponentModel;
using System.Runtime;
static class <API key>
{
static bool IsDefined(VariableModifiers modifiers)
{
return (modifiers == VariableModifiers.None ||
((modifiers & (VariableModifiers.Mapped | VariableModifiers.ReadOnly)) == modifiers));
}
public static bool IsReadOnly(VariableModifiers modifiers)
{
return (modifiers & VariableModifiers.ReadOnly) == VariableModifiers.ReadOnly;
}
public static bool IsMappable(VariableModifiers modifiers)
{
return (modifiers & VariableModifiers.Mapped) == VariableModifiers.Mapped;
}
public static void Validate(VariableModifiers modifiers, string argumentName)
{
if (!IsDefined(modifiers))
{
throw FxTrace.Exception.AsError(
new <API key>(argumentName, (int)modifiers, typeof(VariableModifiers)));
}
}
}
} |
import {devModeEqual} from '@angular/core/src/change_detection/<API key>';
{
describe('ChangeDetectionUtil', () => {
describe('devModeEqual', () => {
it('should do the deep comparison of iterables', () => {
expect(devModeEqual([['one']], [['one']])).toBe(true);
expect(devModeEqual(['one'], ['one', 'two'])).toBe(false);
expect(devModeEqual(['one', 'two'], ['one'])).toBe(false);
expect(devModeEqual(['one'], 'one')).toBe(false);
expect(devModeEqual(['one'], {})).toBe(false);
expect(devModeEqual('one', ['one'])).toBe(false);
expect(devModeEqual({}, ['one'])).toBe(false);
});
it('should compare primitive numbers', () => {
expect(devModeEqual(1, 1)).toBe(true);
expect(devModeEqual(1, 2)).toBe(false);
expect(devModeEqual({}, 2)).toBe(false);
expect(devModeEqual(1, {})).toBe(false);
});
it('should compare primitive strings', () => {
expect(devModeEqual('one', 'one')).toBe(true);
expect(devModeEqual('one', 'two')).toBe(false);
expect(devModeEqual({}, 'one')).toBe(false);
expect(devModeEqual('one', {})).toBe(false);
});
it('should compare primitive booleans', () => {
expect(devModeEqual(true, true)).toBe(true);
expect(devModeEqual(true, false)).toBe(false);
expect(devModeEqual({}, true)).toBe(false);
expect(devModeEqual(true, {})).toBe(false);
});
it('should compare null', () => {
expect(devModeEqual(null, null)).toBe(true);
expect(devModeEqual(null, 1)).toBe(false);
expect(devModeEqual({}, null)).toBe(false);
expect(devModeEqual(null, {})).toBe(false);
});
it('should return true for other objects', () => {
expect(devModeEqual({}, {})).toBe(true);
});
});
});
} |
package org.galagosearch.core.retrieval.extents;
import java.io.IOException;
import junit.framework.TestCase;
import org.galagosearch.core.retrieval.structured.<API key>;
import org.galagosearch.core.retrieval.structured.<API key>;
import org.galagosearch.tupleflow.Parameters;
/**
*
* @author trevor
*/
public class <API key> extends TestCase {
int[] docsA = new int[]{5, 10, 15, 20};
double[] scoresA = new double[]{1.0, 2.0, 3.0, 4.0};
int[] docsB = new int[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
double[] scoresB = new double[]{2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int[] docsTogether = new int[]{10, 20};
double[] scoresTogether = new double[]{12, 24};
public <API key>(String testName) {
super(testName);
}
public void testNextCandidate() throws IOException {
FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
FakeScoreIterator[] iterators = { one, two };
Parameters filterParameters = new Parameters();
<API key> instance = new <API key>(filterParameters,
iterators);
assertEquals(5, instance.nextCandidate());
instance.movePast(10);
assertEquals(15, instance.nextCandidate());
}
public void testHasMatch() throws IOException {
FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
FakeScoreIterator[] iterators = { one, two };
Parameters anyParameters = new Parameters();
<API key> instance = new <API key>(anyParameters,
iterators);
assertFalse(instance.hasMatch(1));
assertFalse(instance.hasMatch(2));
assertFalse(instance.hasMatch(3));
assertFalse(instance.hasMatch(10));
instance.moveTo(10);
assertTrue(instance.hasMatch(10));
}
public void testScore() throws IOException {
FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
FakeScoreIterator[] iterators = { one, two };
Parameters anyParameters = new Parameters();
<API key> instance = new <API key>(anyParameters, iterators);
for (int i = 0; i < docsTogether.length; i++) {
assertFalse(instance.isDone());
instance.moveTo(docsTogether[i]);
assertTrue(instance.hasMatch(docsTogether[i]));
assertEquals(scoresTogether[i], instance.score(docsTogether[i], 100));
instance.movePast(docsTogether[i]);
}
assertTrue(instance.isDone());
}
public void testMovePast() throws Exception {
FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
FakeScoreIterator[] iterators = { one, two };
Parameters anyParameters = new Parameters();
<API key> instance = new <API key>(anyParameters, iterators);
instance.movePast(5);
assertEquals(10, instance.nextCandidate());
}
public void testMoveTo() throws Exception {
FakeScoreIterator one = new FakeScoreIterator(docsA, scoresA);
FakeScoreIterator two = new FakeScoreIterator(docsB, scoresB);
FakeScoreIterator[] iterators = { one, two };
Parameters anyParameters = new Parameters();
<API key> instance = new <API key>(anyParameters, iterators);
instance.moveTo(5);
assertEquals(6, instance.nextCandidate());
}
} |
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="../resources/css/base.css" />
<link rel="stylesheet" href="../common/css/style.css" />
</head>
<body>
<div class="instructions">Scroll the page</div>
<h2>THE END OF THE TETHER</h2>
<p>By Joseph Conrad</p>
<h3>Chapter I</h3>
<p>For a long time after the course of the steamer <em>Sofala</em> had been
altered for the land, the low swampy coast had retained its appearance
of a mere smudge of darkness beyond a belt of glitter. The sunrays
seemed to fall violently upon the calm sea--seemed to shatter themselves
upon an adamantine surface into sparkling dust, into a dazzling vapor
of light that blinded the eye and wearied the brain with its unsteady
brightness.</p>
<p>Captain Whalley did not look at it. When his Serang, approaching the
roomy cane arm-chair which he filled capably, had informed him in a low
voice that the course was to be altered, he had risen at once and had
remained on his feet, face forward, while the head of his ship swung
through a quarter of a circle. He had not uttered a single word, not
even the word to steady the helm. It was the Serang, an elderly, alert,
little Malay, with a very dark skin, who murmured the order to the
helmsman. And then slowly Captain Whalley sat down again in the
arm-chair on the bridge and fixed his eyes on the deck between his feet.</p>
<p>He could not hope to see anything new upon this lane of the sea. He had
been on these coasts for the last three years. From Low Cape to Malantan
the distance was fifty miles, six hours' steaming for the old ship with
the tide, or seven against. Then you steered straight for the land, and
by-and-by three palms would appear on the sky, tall and slim, and with
their disheveled heads in a bunch, as if in confidential criticism of
the dark mangroves. The Sofala would be headed towards the somber
strip of the coast, which at a given moment, as the ship closed with
it obliquely, would show several clean shining fractures--the brimful
estuary of a river. Then on through a brown liquid, three parts water
and one part black earth, on and on between the low shores, three parts
black earth and one part brackish water, the Sofala would plow her way
up-stream, as she had done once every month for these seven years or
more, long before he was aware of her existence, long before he had ever
thought of having anything to do with her and her invariable voyages.
The old ship ought to have known the road better than her men, who had
not been kept so long at it without a change; better than the faithful
Serang, whom he had brought over from his last ship to keep the
captain's watch; better than he himself, who had been her captain for
the last three years only. She could always be depended upon to make her
courses. Her compasses were never out. She was no trouble at all to
take about, as if her great age had given her knowledge, wisdom, and
steadiness. She made her landfalls to a degree of the bearing, and
almost to a minute of her allowed time. At any moment, as he sat on
the bridge without looking up, or lay sleepless in his bed, simply by
reckoning the days and the hours he could tell where he was--the precise
spot of the beat. He knew it well too, this monotonous huckster's
round, up and down the Straits; he knew its order and its sights and its
people. Malacca to begin with, in at daylight and out at dusk, to cross
over with a rigid phosphorescent wake this highway of the Far East.
Darkness and gleams on the water, clear stars on a black sky, perhaps
the lights of a home steamer keeping her unswerving course in the
middle, or maybe the elusive shadow of a native craft with her mat sails
flitting by silently--and the low land on the other side in sight
at daylight. At noon the three palms of the next place of call, up a
sluggish river. The only white man residing there was a retired young
sailor, with whom he had become friendly in the course of many voyages.
Sixty miles farther on there was another place of call, a deep bay with
only a couple of houses on the beach. And so on, in and out, picking
up coastwise cargo here and there, and finishing with a hundred miles'
steady steaming through the maze of an archipelago of small islands up
to a large native town at the end of the beat. There was a three days'
rest for the old ship before he started her again in inverse order,
seeing the same shores from another bearing, hearing the same voices
in the same places, back again to the Sofala's port of registry on
the great highway to the East, where he would take up a berth nearly
opposite the big stone pile of the harbor office till it was time to
start again on the old round of 1600 miles and thirty days. Not a very
enterprising life, this, for Captain Whalley, Henry Whalley, otherwise
Dare-devil Harry--Whalley of the Condor, a famous clipper in her day.
No. Not a very enterprising life for a man who had served famous firms,
who had sailed famous ships (more than one or two of them his own); who
had made famous passages, had been the pioneer of new routes and new
trades; who had steered across the unsurveyed tracts of the South Seas,
and had seen the sun rise on uncharted islands. Fifty years at sea, and
forty out in the East ("a pretty thorough apprenticeship," he used
to remark smilingly), had made him honorably known to a generation of
shipowners and merchants in all the ports from Bombay clear over to
where the East merges into the West upon the coast of the two Americas.
His fame remained writ, not very large but plain enough, on the
Admiralty charts. Was there not somewhere between Australia and China a
Whalley Island and a Condor Reef? On that dangerous coral formation the
celebrated clipper had hung stranded for three days, her captain and
crew throwing her cargo overboard with one hand and with the other, as
it were, keeping off her a flotilla of savage war-canoes. At that time
neither the island nor the reef had any official existence. Later the
officers of her Majesty's steam vessel Fusilier, dispatched to make a
survey of the route, recognized in the adoption of these two names the
enterprise of the man and the solidity of the ship. Besides, as anyone
who cares may see, the "General Directory," vol. ii. p. 410, begins the
description of the "Malotu or Whalley Passage" with the words: "This
advantageous route, first discovered in 1850 by Captain Whalley in the
ship Condor," &c., and ends by recommending it warmly to sailing vessels
leaving the China ports for the south in the months from December to
April inclusive.</p>
<p>This was the clearest gain he had out of life. Nothing could rob him
of this kind of fame. The piercing of the Isthmus of Suez, like the
breaking of a dam, had let in upon the East a flood of new ships, new
men, new methods of trade. It had changed the face of the Eastern seas
and the very spirit of their life; so that his early experiences meant
nothing whatever to the new generation of seamen.</p>
<p>In those bygone days he had handled many thousands of pounds of his
employers' money and of his own; he had attended faithfully, as by law
a shipmaster is expected to do, to the conflicting interests of owners,
charterers, and underwriters. He had never lost a ship or consented to
a shady transaction; and he had lasted well, outlasting in the end the
conditions that had gone to the making of his name. He had buried his
wife (in the Gulf of Petchili), had married off his daughter to the man
of her unlucky choice, and had lost more than an ample competence in the
crash of the notorious Travancore and Deccan Banking Corporation, whose
downfall had shaken the East like an earthquake. And he was sixty-five
years old.</p>
<h3>Chapter II</h3>
<p>His age sat lightly enough on him; and of his ruin he was not ashamed.
He had not been alone to believe in the stability of the Banking
Corporation. Men whose judgment in matters of finance was as expert as
his seamanship had commended the prudence of his investments, and had
themselves lost much money in the great failure. The only difference
between him and them was that he had lost his all. And yet not his all.
There had remained to him from his lost fortune a very pretty little
bark, Fair Maid, which he had bought to occupy his leisure of a retired
sailor--"to play with," as he expressed it himself.</p>
<p>He had formally declared himself tired of the sea the year preceding his
daughter's marriage. But after the young couple had gone to settle in
Melbourne he found out that he could not make himself happy on shore. He
was too much of a merchant sea-captain for mere yachting to satisfy him.
He wanted the illusion of affairs; and his acquisition of the Fair
Maid preserved the continuity of his life. He introduced her to his
acquaintances in various ports as "my last command." When he grew too
old to be trusted with a ship, he would lay her up and go ashore to be
buried, leaving directions in his will to have the bark towed out and
scuttled decently in deep water on the day of the funeral. His daughter
would not grudge him the satisfaction of knowing that no stranger would
handle his last command after him. With the fortune he was able to leave
her, the value of a 500-ton bark was neither here nor there. All this
would be said with a jocular twinkle in his eye: the vigorous old man
had too much vitality for the sentimentalism of regret; and a little
wistfully withal, because he was at home in life, taking a genuine
pleasure in its feelings and its possessions; in the dignity of his
reputation and his wealth, in his love for his daughter, and in his
satisfaction with the ship--the plaything of his lonely leisure.</p>
<p>He had the cabin arranged in accordance with his simple ideal of comfort
at sea. A big bookcase (he was a great reader) occupied one side of his
stateroom; the portrait of his late wife, a flat bituminous oil-painting
representing the profile and one long black ringlet of a young woman,
faced his bed-place. Three chronometers ticked him to sleep and greeted
him on waking with the tiny competition of their beats. He rose at five
every day. The officer of the morning watch, drinking his early cup
of coffee aft by the wheel, would hear through the wide orifice of the
copper ventilators all the splashings, blowings, and splutterings of
his captain's toilet. These noises would be followed by a sustained
deep murmur of the Lord's Prayer recited in a loud earnest voice. Five
minutes afterwards the head and shoulders of Captain Whalley emerged
out of the companion-hatchway. Invariably he paused for a while on the
stairs, looking all round at the horizon; upwards at the trim of the
sails; inhaling deep draughts of the fresh air. Only then he would step
out on the poop, acknowledging the hand raised to the peak of the cap
with a majestic and benign "Good morning to you." He walked the deck
till eight scrupulously. Sometimes, not above twice a year, he had to
use a thick cudgel-like stick on account of a stiffness in the hip--a
slight touch of rheumatism, he supposed. Otherwise he knew nothing of
the ills of the flesh. At the ringing of the breakfast bell he went
below to feed his canaries, wind up the chronometers, and take the
head of the table. From there he had before his eyes the big carbon
photographs of his daughter, her husband, and two fat-legged babies
--his grandchildren--set in black frames into the maplewood bulkheads
of the cuddy. After breakfast he dusted the glass over these portraits
himself with a cloth, and brushed the oil painting of his wife with a
plumate kept suspended from a small brass hook by the side of the heavy
gold frame. Then with the door of his stateroom shut, he would sit down
on the couch under the portrait to read a chapter out of a thick pocket
Bible--her Bible. But on some days he only sat there for half an hour
with his finger between the leaves and the closed book resting on his
knees. Perhaps he had remembered suddenly how fond of boat-sailing she
used to be.</p>
<p>She had been a real shipmate and a true woman too. It was like an
article of faith with him that there never had been, and never could be,
a brighter, cheerier home anywhere afloat or ashore than his home under
the poop-deck of the Condor, with the big main cabin all white and gold,
garlanded as if for a perpetual festival with an unfading wreath. She
had decorated the center of every panel with a cluster of home flowers.
It took her a twelvemonth to go round the cuddy with this labor of love.
To him it had remained a marvel of painting, the highest achievement of
taste and skill; and as to old Swinburne, his mate, every time he
came down to his meals he stood transfixed with admiration before the
progress of the work. You could almost smell these roses, he declared,
sniffing the faint flavor of turpentine which at that time pervaded the
saloon, and (as he confessed afterwards) made him somewhat less hearty
than usual in tackling his food. But there was nothing of the sort to
interfere with his enjoyment of her singing. "Mrs. Whalley is a regular
out-and-out nightingale, sir," he would pronounce with a judicial air
after listening profoundly over the skylight to the very end of the
piece. In fine weather, in the second dog-watch, the two men could hear
her trills and roulades going on to the accompaniment of the piano in
the cabin. On the very day they got engaged he had written to London
for the instrument; but they had been married for over a year before it
reached them, coming out round the Cape. The big case made part of the
first direct general cargo landed in Hong-kong harbor--an event that to
the men who walked the busy quays of to-day seemed as hazily remote as
the dark ages of history. But Captain Whalley could in a half hour of
solitude live again all his life, with its romance, its idyl, and its
sorrow. He had to close her eyes himself. She went away from under the
ensign like a sailor's wife, a sailor herself at heart. He had read
the service over her, out of her own prayer-book, without a break in his
voice. When he raised his eyes he could see old Swinburne facing him
with his cap pressed to his breast, and his rugged, weather-beaten,
impassive face streaming with drops of water like a lump of chipped red
granite in a shower. It was all very well for that old sea-dog to cry.
He had to read on to the end; but after the splash he did not remember
much of what happened for the next few days. An elderly sailor of the
crew, deft at needlework, put together a mourning frock for the child
out of one of her black skirts.</p>
<p>He was not likely to forget; but you cannot dam up life like a sluggish
stream. It will break out and flow over a man's troubles, it will close
upon a sorrow like the sea upon a dead body, no matter how much love has
gone to the bottom. And the world is not bad. People had been very
kind to him; especially Mrs. Gardner, the wife of the senior partner
in Gardner, Patteson, & Co., the owners of the Condor. It was she who
volunteered to look after the little one, and in due course took her to
England (something of a journey in those days, even by the overland
mail route) with her own girls to finish her education. It was ten years
before he saw her again.</p>
<p>As a little child she had never been frightened of bad weather; she
would beg to be taken up on deck in the bosom of his oilskin coat to
watch the big seas hurling themselves upon the Condor. The swirl and
crash of the waves seemed to fill her small soul with a breathless
delight. "A good boy spoiled," he used to say of her in joke. He had
named her Ivy because of the sound of the word, and obscurely fascinated
by a vague association of ideas. She had twined herself tightly round
his heart, and he intended her to cling close to her father as to a
tower of strength; forgetting, while she was little, that in the nature
of things she would probably elect to cling to someone else. But
he loved life well enough for even that event to give him a certain
satisfaction, apart from his more intimate feeling of loss.</p>
<p>After he had purchased the Fair Maid to occupy his loneliness, he
hastened to accept a rather unprofitable freight to Australia simply for
the opportunity of seeing his daughter in her own home. What made him
dissatisfied there was not to see that she clung now to somebody else,
but that the prop she had selected seemed on closer examination "a
rather poor stick"--even in the matter of health. He disliked his
son-in-law's studied civility perhaps more than his method of
handling the sum of money he had given Ivy at her marriage. But of his
apprehensions he said nothing. Only on the day of his departure, with
the hall-door open already, holding her hands and looking steadily into
her eyes, he had said, "You know, my dear, all I have is for you and the
chicks. Mind you write to me openly." She had answered him by an almost
imperceptible movement of her head. She resembled her mother in
the color of her eyes, and in character--and also in this, that she
understood him without many words.</p>
<p>Sure enough she had to write; and some of these letters made Captain
Whalley lift his white eye-brows. For the rest he considered he was
reaping the true reward of his life by being thus able to produce on
demand whatever was needed. He had not enjoyed himself so much in a
way since his wife had died. Characteristically enough his son-in-law's
punctuality in failure caused him at a distance to feel a sort of
kindness towards the man. The fellow was so perpetually being jammed on
a lee shore that to charge it all to his reckless navigation would be
manifestly unfair. No, no! He knew well what that meant. It was bad
luck. His own had been simply marvelous, but he had seen in his life too
many good men--seamen and others--go under with the sheer weight of bad
luck not to recognize the fatal signs. For all that, he was cogitating
on the best way of tying up very strictly every penny he had to leave,
when, with a preliminary rumble of rumors (whose first sound reached
him in Shanghai as it happened), the shock of the big failure came;
and, after passing through the phases of stupor, of incredulity, of
indignation, he had to accept the fact that he had nothing to speak of
to leave.</p>
<p>Upon that, as if he had only waited for this catastrophe, the unlucky
man, away there in Melbourne, gave up his unprofitable game, and sat
down--in an invalid's bath-chair at that too. "He will never walk
again," wrote the wife. For the first time in his life Captain Whalley
was a bit staggered.</p>
<p>The Fair Maid had to go to work in bitter earnest now. It was no longer
a matter of preserving alive the memory of Dare-devil Harry Whalley in
the Eastern Seas, or of keeping an old man in pocket-money and clothes,
with, perhaps, a bill for a few hundred first-class cigars thrown in at
the end of the year. He would have to buckle-to, and keep her going hard
on a scant allowance of gilt for the ginger-bread scrolls at her stem
and stern.</p>
<p>This necessity opened his eyes to the fundamental changes of the world.
Of his past only the familiar names remained, here and there, but
the things and the men, as he had known them, were gone. The name of
Gardner, Patteson, & Co. was still displayed on the walls of warehouses
by the waterside, on the brass plates and window-panes in the business
quarters of more than one Eastern port, but there was no longer a
Gardner or a Patteson in the firm. There was no longer for Captain
Whalley an arm-chair and a welcome in the private office, with a bit of
business ready to be put in the way of an old friend, for the sake of
bygone services. The husbands of the Gardner girls sat behind the desks
in that room where, long after he had left the employ, he had kept his
right of entrance in the old man's time. Their ships now had yellow
funnels with black tops, and a time-table of appointed routes like a
confounded service of tramways. The winds of December and June were all
one to them; their captains (excellent young men he doubted not) were,
to be sure, familiar with Whalley Island, because of late years the
Government had established a white fixed light on the north end (with
a red danger sector over the Condor Reef), but most of them would have
been extremely surprised to hear that a flesh-and-blood Whalley still
existed--an old man going about the world trying to pick up a cargo here
and there for his little bark.</p>
<p>And everywhere it was the same. Departed the men who would have nodded
appreciatively at the mention of his name, and would have thought
themselves bound in honor to do something for Dare-devil Harry Whalley.
Departed the opportunities which he would have known how to seize; and
gone with them the white-winged flock of clippers that lived in the
boisterous uncertain life of the winds, skimming big fortunes out of
the foam of the sea. In a world that pared down the profits to an
irreducible minimum, in a world that was able to count its disengaged
tonnage twice over every day, and in which lean charters were snapped up
by cable three months in advance, there were no chances of fortune for
an individual wandering haphazard with a little bark--hardly indeed any
room to exist.</p>
<p>He found it more difficult from year to year. He suffered greatly from
the smallness of remittances he was able to send his daughter. Meantime
he had given up good cigars, and even in the matter of inferior cheroots
limited himself to six a day. He never told her of his difficulties, and
she never enlarged upon her struggle to live. Their confidence in each
other needed no explanations, and their perfect understanding endured
without protestations of gratitude or regret. He would have been shocked
if she had taken it into her head to thank him in so many words, but
he found it perfectly natural that she should tell him she needed two
hundred pounds.</p>
<p>He had come in with the Fair Maid in ballast to look for a freight in
the Sofala's port of registry, and her letter met him there. Its tenor
was that it was no use mincing matters. Her only resource was in opening
a boarding-house, for which the prospects, she judged, were good. Good
enough, at any rate, to make her tell him frankly that with two hundred
pounds she could make a start. He had torn the envelope open, hastily,
on deck, where it was handed to him by the ship-chandler's runner, who
had brought his mail at the moment of anchoring. For the second time
in his life he was appalled, and remained stock-still at the cabin door
with the paper trembling between his fingers. Open a boarding-house! Two
hundred pounds for a start! The only resource! And he did not know where
to lay his hands on two hundred pence.</p>
<p>All that night Captain Whalley walked the poop of his anchored ship, as
though he had been about to close with the land in thick weather, and
uncertain of his position after a run of many gray days without a sight
of sun, moon, or stars. The black night twinkled with the guiding lights
of seamen and the steady straight lines of lights on shore; and all
around the Fair Maid the riding lights of ships cast trembling trails
upon the water of the roadstead. Captain Whalley saw not a gleam
anywhere till the dawn broke and he found out that his clothing was
soaked through with the heavy dew.</p>
<p>His ship was awake. He stopped short, stroked his wet beard, and
descended the poop ladder backwards, with tired feet. At the sight
of him the chief officer, lounging about sleepily on the quarterdeck,
remained open-mouthed in the middle of a great early-morning yawn.</p>
<p>"Good morning to you," pronounced Captain Whalley solemnly, passing into
the cabin. But he checked himself in the doorway, and without looking
back, "By the bye," he said, "there should be an empty wooden case put
away in the lazarette. It has not been broken up--has it?"</p>
<p>The mate shut his mouth, and then asked as if dazed, "What empty case,
sir?"</p>
<p>"A big flat packing-case belonging to that painting in my room. Let it
be taken up on deck and tell the carpenter to look it over. I may want
to use it before long."</p>
<p>The chief officer did not stir a limb till he had heard the door of the
captain's state-room slam within the cuddy. Then he beckoned aft the
second mate with his forefinger to tell him that there was something "in
the wind."</p>
<p>When the bell rang Captain Whalley's authoritative voice boomed out
through a closed door, "Sit down and don't wait for me." And his
impressed officers took their places, exchanging looks and whispers
across the table. What! No breakfast? And after apparently knocking
about all night on deck, too! Clearly, there was something in the wind.
In the skylight above their heads, bowed earnestly over the plates,
three wire cages rocked and rattled to the restless jumping of the
hungry canaries; and they could detect the sounds of their "old
man's" deliberate movements within his state-room. Captain Whalley was
methodically winding up the chronometers, dusting the portrait of
his late wife, getting a clean white shirt out of the drawers, making
himself ready in his punctilious unhurried manner to go ashore. He could
not have swallowed a single mouthful of food that morning. He had made
up his mind to sell the Fair Maid.</p>
<h3>Chapter III</h3>
<p>Just at that time the Japanese were casting far and wide for ships
of European build, and he had no difficulty in finding a purchaser, a
speculator who drove a hard bargain, but paid cash down for the Fair
Maid, with a view to a profitable resale. Thus it came about that
Captain Whalley found himself on a certain afternoon descending the
steps of one of the most important post-offices of the East with a slip
of bluish paper in his hand. This was the receipt of a registered letter
enclosing a draft for two hundred pounds, and addressed to Melbourne.
Captain Whalley pushed the paper into his waistcoat-pocket, took his
stick from under his arm, and walked down the street.</p>
<p>It was a recently opened and untidy thoroughfare with rudimentary
side-walks and a soft layer of dust cushioning the whole width of
the road. One end touched the slummy street of Chinese shops near the
harbor, the other drove straight on, without houses, for a couple of
miles, through patches of jungle-like vegetation, to the yard gates
of the new Consolidated Docks Company. The crude frontages of the new
Government buildings alternated with the blank fencing of vacant plots,
and the view of the sky seemed to give an added spaciousness to the
broad vista. It was empty and shunned by natives after business
hours, as though they had expected to see one of the tigers from the
neighborhood of the New Waterworks on the hill coming at a loping canter
down the middle to get a Chinese shopkeeper for supper. Captain Whalley
was not dwarfed by the solitude of the grandly planned street. He
had too fine a presence for that. He was only a lonely figure walking
purposefully, with a great white beard like a pilgrim, and with a thick
stick that resembled a weapon. On one side the new Courts of Justice had
a low and unadorned portico of squat columns half concealed by a few old
trees left in the approach. On the other the pavilion wings of the
new Colonial Treasury came out to the line of the street. But Captain
Whalley, who had now no ship and no home, remembered in passing that
on that very site when he first came out from England there had stood a
fishing village, a few mat huts erected on piles between a muddy tidal
creek and a miry pathway that went writhing into a tangled wilderness
without any docks or waterworks.</p>
<p>No ship--no home. And his poor Ivy away there had no home either. A
boarding-house is no sort of home though it may get you a living. His
feelings were horribly rasped by the idea of the boarding-house. In his
rank of life he had that truly aristocratic temperament characterized by
a scorn of vulgar gentility and by prejudiced views as to the derogatory
nature of certain occupations. For his own part he had always preferred
sailing merchant ships (which is a straightforward occupation) to buying
and selling merchandise, of which the essence is to get the better of
somebody in a bargain--an undignified trial of wits at best. His father
had been Colonel Whalley (retired) of the H. E. I. Company's service,
with very slender means besides his pension, but with distinguished
connections. He could remember as a boy how frequently waiters at the
inns, country tradesmen and small people of that sort, used to "My lord"
the old warrior on the strength of his appearance.</p>
<p>Captain Whalley himself (he would have entered the Navy if his father
had not died before he was fourteen) had something of a grand air which
would have suited an old and glorious admiral; but he became lost like
a straw in the eddy of a brook amongst the swarm of brown and yellow
humanity filling a thoroughfare, that by contrast with the vast and
empty avenue he had left seemed as narrow as a lane and absolutely
riotous with life. The walls of the houses were blue; the shops of the
Chinamen yawned like cavernous lairs; heaps of nondescript merchandise
overflowed the gloom of the long range of arcades, and the fiery
serenity of sunset took the middle of the street from end to end with a
glow like the reflection of a fire. It fell on the bright colors and the
dark faces of the bare-footed crowd, on the pallid yellow backs of the
half-naked jostling coolies, on the accouterments of a tall Sikh trooper
with a parted beard and fierce mustaches on sentry before the gate of
the police compound. Looming very big above the heads in a red haze of
dust, the tightly packed car of the cable tramway navigated cautiously
up the human stream, with the incessant blare of its horn, in the manner
of a steamer groping in a fog.</p>
<p>Captain Whalley emerged like a diver on the other side, and in the
desert shade between the walls of closed warehouses removed his hat to
cool his brow. A certain disrepute attached to the calling of a
landlady of a boarding-house. These women were said to be rapacious,
unscrupulous, untruthful; and though he contemned no class of his
<API key> forbid!--these were suspicions to which it was
unseemly that a Whalley should lay herself open. He had not expostulated
with her, however. He was confident she shared his feelings; he was
sorry for her; he trusted her judgment; he considered it a merciful
dispensation that he could help her once more,--but in his aristocratic
heart of hearts he would have found it more easy to reconcile himself to
the idea of her turning seamstress. Vaguely he remembered reading years
ago a touching piece called the "Song of the Shirt." It was all very
well making songs about poor women. The granddaughter of Colonel
Whalley, the landlady of a boarding-house! Pooh! He replaced his hat,
dived into two pockets, and stopping a moment to apply a flaring match
to the end of a cheap cheroot, blew an embittered cloud of smoke at a
world that could hold such surprises.</p>
<p>Of one thing he was certain--that she was the own child of a clever
mother. Now he had got over the wrench of parting with his ship, he
perceived clearly that such a step had been unavoidable. Perhaps he had
been growing aware of it all along with an unconfessed knowledge. But
she, far away there, must have had an intuitive perception of it, with
the pluck to face that truth and the courage to speak out--all the
qualities which had made her mother a woman of such excellent counsel.</p>
<p>It would have had to come to that in the end! It was fortunate she had
forced his hand. In another year or two it would have been an utterly
barren sale. To keep the ship going he had been involving himself deeper
every year. He was defenseless before the insidious work of adversity,
to whose more open assaults he could present a firm front; like a
cliff that stands unmoved the open battering of the sea, with a lofty
ignorance of the treacherous backwash undermining its base. As it was,
every liability satisfied, her request answered, and owing no man a
penny, there remained to him from the proceeds a sum of five hundred
pounds put away safely. In addition he had upon his person some forty
odd dollars--enough to pay his hotel bill, providing he did not linger
too long in the modest bedroom where he had taken refuge.</p>
<p>Scantily furnished, and with a waxed floor, it opened into one of
the side-verandas. The straggling building of bricks, as airy as a
bird-cage, resounded with the incessant flapping of rattan screens
worried by the wind between the white-washed square pillars of the
sea-front. The rooms were lofty, a ripple of sunshine flowed over the
ceilings; and the periodical invasions of tourists from some passenger
steamer in the harbor flitted through the wind-swept dusk of the
apartments with the tumult of their unfamiliar voices and impermanent
presences, like relays of migratory shades condemned to speed headlong
round the earth without leaving a trace. The babble of their irruptions
ebbed out as suddenly as it had arisen; the draughty corridors and
the long chairs of the verandas knew their sight-seeing hurry or
their prostrate repose no more; and Captain Whalley, substantial and
dignified, left well-nigh alone in the vast hotel by each light-hearted
skurry, felt more and more like a stranded tourist with no aim in view,
like a forlorn traveler without a home. In the solitude of his room he
smoked thoughtfully, gazing at the two sea-chests which held all that he
could call his own in this world. A thick roll of charts in a sheath
of sailcloth leaned in a corner; the flat packing-case containing the
portrait in oils and the three carbon photographs had been pushed under
the bed. He was tired of discussing terms, of assisting at surveys, of
all the routine of the business. What to the other parties was merely
the sale of a ship was to him a momentous event involving a radically
new view of existence. He knew that after this ship there would be no
other; and the hopes of his youth, the exercise of his abilities, every
feeling and achievement of his manhood, had been indissolubly connected
with ships. He had served ships; he had owned ships; and even the years
of his actual retirement from the sea had been made bearable by the idea
that he had only to stretch out his hand full of money to get a ship. He
had been at liberty to feel as though he were the owner of all the
ships in the world. The selling of this one was weary work; but when
she passed from him at last, when he signed the last receipt, it was as
though all the ships had gone out of the world together, leaving him on
the shore of inaccessible oceans with seven hundred pounds in his hands.</p>
<p>Striding firmly, without haste, along the quay, Captain Whalley averted
his glances from the familiar roadstead. Two generations of seamen born
since his first day at sea stood between him and all these ships at the
anchorage. His own was sold, and he had been asking himself, What next?</p>
<p>From the feeling of loneliness, of inward emptiness,--and of loss
too, as if his very soul had been taken out of him forcibly,--there had
sprung at first a desire to start right off and join his daughter.
"Here are the last pence," he would say to her; "take them, my dear. And
here's your old father: you must take him too."</p>
<p>His soul recoiled, as if afraid of what lay hidden at the bottom of
this impulse. Give up! Never! When one is thoroughly weary all sorts of
nonsense come into one's head. A pretty gift it would have been for a
poor woman--this seven hundred pounds with the incumbrance of a hale old
fellow more than likely to last for years and years to come. Was he not
as fit to die in harness as any of the youngsters in charge of these
anchored ships out yonder? He was as solid now as ever he had been. But
as to who would give him work to do, that was another matter. Were he,
with his appearance and antecedents, to go about looking for a junior's
berth, people, he was afraid, would not take him seriously; or else if
he succeeded in impressing them, he would maybe obtain their pity, which
would be like stripping yourself naked to be kicked. He was not anxious
to give himself away for less than nothing. He had no use for anybody's
pity. On the other hand, a command--the only thing he could try for with
due regard for common decency--was not likely to be lying in wait
for him at the corner of the next street. Commands don't go a-begging
nowadays. Ever since he had come ashore to carry out the business of
the sale he had kept his ears open, but had heard no hint of one being
vacant in the port. And even if there had been one, his successful past
itself stood in his way. He had been his own employer too long. The only
credential he could produce was the testimony of his whole life. What
better recommendation could anyone require? But vaguely he felt that
the unique document would be looked upon as an archaic curiosity of the
Eastern waters, a screed traced in obsolete words--in a half-forgotten
language.</p>
<h3>Chapter IV</h3>
<p>Revolving these thoughts, he strolled on near the railings of the quay,
broad-chested, without a stoop, as though his big shoulders had never
felt the burden of the loads that must be carried between the cradle
and the grave. No single betraying fold or line of care disfigured the
reposeful modeling of his face. It was full and untanned; and the upper
part emerged, massively quiet, out of the downward flow of silvery hair,
with the striking delicacy of its clear complexion and the powerful
width of the forehead. The first cast of his glance fell on you candid
and swift, like a boy's; but because of the ragged snowy thatch of the
eyebrows the affability of his attention acquired the character of a
dark and searching scrutiny. With age he had put on flesh a little, had
increased his girth like an old tree presenting no symptoms of decay;
and even the opulent, lustrous ripple of white hairs upon his chest
seemed an attribute of unquenchable vitality and vigor.</p>
<p>Once rather proud of his great bodily strength, and even of his personal
appearance, conscious of his worth, and firm in his rectitude, there had
remained to him, like the heritage of departed prosperity, the tranquil
bearing of a man who had proved himself fit in every sort of way for the
life of his choice. He strode on squarely under the projecting brim of
an ancient Panama hat. It had a low crown, a crease through its whole
diameter, a narrow black ribbon. Imperishable and a little discolored,
this headgear made it easy to pick him out from afar on thronged wharves
and in the busy streets. He had never adopted the comparatively modern
fashion of pipeclayed cork helmets. He disliked the form; and he hoped
he could manage to keep a cool head to the end of his life without all
these contrivances for hygienic ventilation. His hair was cropped close,
his linen always of immaculate whiteness; a suit of thin gray flannel,
worn threadbare but scrupulously brushed, floated about his burly limbs,
adding to his bulk by the looseness of its cut. The years had mellowed
the good-humored, imperturbable audacity of his prime into a temper
carelessly serene; and the leisurely tapping of his iron-shod stick
accompanied his footfalls with a self-confident sound on the flagstones.
It was impossible to connect such a fine presence and this unruffled
aspect with the belittling troubles of poverty; the man's whole
existence appeared to pass before you, facile and large, in the freedom
of means as ample as the clothing of his body.</p>
<p>The irrational dread of having to break into his five hundred pounds for
personal expenses in the hotel disturbed the steady poise of his mind.
There was no time to lose. The bill was running up. He nourished the
hope that this five hundred would perhaps be the means, if everything
else failed, of obtaining some work which, keeping his body and soul
together (not a matter of great outlay), would enable him to be of use
to his daughter. To his mind it was her own money which he employed, as
it were, in backing her father and solely for her benefit. Once at work,
he would help her with the greater part of his earnings; he was good for
many years yet, and this boarding-house business, he argued to himself,
whatever the prospects, could not be much of a gold-mine from the first
start. But what work? He was ready to lay hold of anything in an honest
way so that it came quickly to his hand; because the five hundred pounds
must be preserved intact for eventual use. That was the great point.
With the entire five hundred one felt a substance at one's back; but
it seemed to him that should he let it dwindle to four-fifty or even
four-eighty, all the efficiency would be gone out of the money, as though
there were some magic power in the round figure. But what sort of work?</p>
<p>Confronted by that haunting question as by an uneasy ghost, for whom he
had no exorcising formula, Captain Whalley stopped short on the apex
of a small bridge spanning steeply the bed of a canalized creek with
granite shores. Moored between the square blocks a seagoing Malay prau
floated half hidden under the arch of masonry, with her spars lowered
down, without a sound of life on board, and covered from stem to stern
with a ridge of palm-leaf mats. He had left behind him the overheated
pavements bordered by the stone frontages that, like the sheer face of
cliffs, followed the sweep of the quays; and an unconfined spaciousness
of orderly and sylvan aspect opened before him its wide plots of rolled
grass, like pieces of green carpet smoothly pegged out, its long ranges
of trees lined up in colossal porticos of dark shafts roofed with a
vault of branches.</p>
<p>Some of these avenues ended at the sea. It was a terraced shore; and
beyond, upon the level expanse, profound and glistening like the gaze
of a dark-blue eye, an oblique band of stippled purple lengthened itself
indefinitely through the gap between a couple of verdant twin islets.
The masts and spars of a few ships far away, hull down in the outer
roads, sprang straight from the water in a fine maze of rosy lines
penciled on the clear shadow of the eastern board. Captain Whalley gave
them a long glance. The ship, once his own, was anchored out there. It
was staggering to think that it was open to him no longer to take a boat
at the jetty and get himself pulled off to her when the evening came. To
no ship. Perhaps never more. Before the sale was concluded, and till the
purchase-money had been paid, he had spent daily some time on board the
Fair Maid. The money had been paid this very morning, and now, all at
once, there was positively no ship that he could go on board of when he
liked; no ship that would need his presence in order to do her work--to
live. It seemed an incredible state of affairs, something too bizarre
to last. And the sea was full of craft of all sorts. There was that prau
lying so still swathed in her shroud of sewn palm-leaves--she too had
her indispensable man. They lived through each other, this Malay he had
never seen, and this high-sterned thing of no size that seemed to be
resting after a long journey. And of all the ships in sight, near and
far, each was provided with a man, the man without whom the finest ship
is a dead thing, a floating and purposeless log.</p>
<p>After his one glance at the roadstead he went on, since there was
nothing to turn back for, and the time must be got through somehow. The
avenues of big trees ran straight over the Esplanade, cutting each other
at diverse angles, columnar below and luxuriant above. The interlaced
boughs high up there seemed to slumber; not a leaf stirred overhead:
and the reedy cast-iron lampposts in the middle of the road, gilt like
scepters, diminished in a long perspective, with their globes of white
porcelain atop, resembling a barbarous decoration of ostriches' eggs
displayed in a row. The flaming sky kindled a tiny crimson spark upon
the glistening surface of each glassy shell.</p>
<p>With his chin sunk a little, his hands behind his back, and the end of
his stick marking the gravel with a faint wavering line at his heels,
Captain Whalley reflected that if a ship without a man was like a body
without a soul, a sailor without a ship was of not much more account
in this world than an aimless log adrift upon the sea. The log might be
sound enough by itself, tough of fiber, and hard to destroy--but what of
that! And a sudden sense of irremediable idleness weighted his feet like
a great fatigue.</p>
<p>A succession of open carriages came bowling along the newly opened
sea-road. You could see across the wide grass-plots the discs of
vibration made by the spokes. The bright domes of the parasols swayed
lightly outwards like full-blown blossoms on the rim of a vase; and
the quiet sheet of dark-blue water, crossed by a bar of purple, made a
background for the spinning wheels and the high action of the horses,
whilst the turbaned heads of the Indian servants elevated above the line
of the sea horizon glided rapidly on the paler blue of the sky. In an
open space near the little bridge each turn-out trotted smartly in a
wide curve away from the sunset; then pulling up sharp, entered the main
alley in a long slow-moving file with the great red stillness of the sky
at the back. The trunks of mighty trees stood all touched with red on
the same side, the air seemed aflame under the high foliage, the
very ground under the hoofs of the horses was red. The wheels turned
solemnly; one after another the sunshades drooped, folding their colors
like gorgeous flowers shutting their petals at the end of the day. In
the whole half-mile of human beings no voice uttered a distinct word,
only a faint thudding noise went on mingled with slight jingling sounds,
and the motionless heads and shoulders of men and women sitting in
couples emerged stolidly above the lowered hoods--as if wooden. But one
carriage and pair coming late did not join the line.</p>
<p>It fled along in a noiseless roll; but on entering the avenue one of the
dark bays snorted, arching his neck and shying against the steel-tipped
pole; a flake of foam fell from the bit upon the point of a satiny
shoulder, and the dusky face of the coachman leaned forward at once over
the hands taking a fresh grip of the reins. It was a long dark-green
landau, having a dignified and buoyant motion between the sharply
curved C-springs, and a sort of strictly official majesty in its supreme
elegance. It seemed more roomy than is usual, its horses seemed slightly
bigger, the appointments a shade more perfect, the servants perched
somewhat higher on the box. The dresses of three women--two young
and pretty, and one, handsome, large, of mature age--seemed to fill
completely the shallow body of the carriage. The fourth face was that
of a man, heavy lidded, distinguished and sallow, with a somber, thick,
iron-gray imperial and mustaches, which somehow had the air of solid
appendages. His Excellency
<p>The rapid motion of that one equipage made all the others appear utterly
inferior, blighted, and reduced to crawl painfully at a snail's pace.
The landau distanced the whole file in a sort of sustained rush; the
features of the occupant whirling out of sight left behind an impression
of fixed stares and impassive vacancy; and after it had vanished in full
flight as it were, notwithstanding the long line of vehicles hugging the
curb at a walk, the whole lofty vista of the avenue seemed to lie open
and emptied of life in the enlarged impression of an august solitude.</p>
<p>Captain Whalley had lifted his head to look, and his mind, disturbed in
its meditation, turned with wonder (as men's minds will do) to matters
of no importance. It struck him that it was to this port, where he had
just sold his last ship, that he had come with the very first he had
ever owned, and with his head full of a plan for opening a new trade
with a distant part of the Archipelago. The then governor had given
him no end of encouragement. No Excellency he--this Mr. Denham--this
governor with his jacket off; a man who tended night and day, so to
speak, the growing prosperity of the settlement with the self-forgetful
devotion of a nurse for a child she loves; a lone bachelor who lived as
in a camp with the few servants and his three dogs in what was called
then the Government Bungalow: a low-roofed structure on the half-cleared
slope of a hill, with a new flagstaff in front and a police orderly on
the veranda. He remembered toiling up that hill under a heavy sun for
his audience; the unfurnished aspect of the cool shaded room; the long
table covered at one end with piles of papers, and with two guns, a
brass telescope, a small bottle of oil with a feather stuck in the neck
at the other--and the flattering attention given to him by the man in
power. It was an undertaking full of risk he had come to expound, but a
twenty minutes' talk in the Government Bungalow on the hill had made it
go smoothly from the start. And as he was retiring Mr. Denham, already
seated before the papers, called out after him, "Next month the Dido
starts for a cruise that way, and I shall request her captain officially
to give you a look in and see how you get on." The Dido was one of the
smart frigates on the China station--and five-and-thirty years make a
big slice of time. Five-and-thirty years ago an enterprise like his had
for the colony enough importance to be looked after by a Queen's ship.
A big slice of time. Individuals were of some account then. Men like
himself; men, too, like poor Evans, for instance, with his red face,
his coal-black whiskers, and his restless eyes, who had set up the first
patent slip for repairing small ships, on the edge of the forest, in
a lonely bay three miles up the coast. Mr. Denham had encouraged that
enterprise too, and yet somehow poor Evans had ended by dying at
home deucedly hard up. His son, they said, was squeezing oil out of
cocoa-nuts for a living on some God-forsaken islet of the Indian Ocean;
but it was from that patent slip in a lonely wooded bay that had sprung
the workshops of the Consolidated Docks Company, with its three
graving basins carved out of solid rock, its wharves, its jetties,
its electric-light plant, its steam-power houses--with its gigantic
sheer-legs, fit to lift the heaviest weight ever carried afloat, and
whose head could be seen like the top of a queer white monument peeping
over bushy points of land and sandy promontories, as you approached the
New Harbor from the west.</p>
<p>There had been a time when men counted: there were not so many carriages
in the colony then, though Mr. Denham, he fancied, had a buggy. And
Captain Whalley seemed to be swept out of the great avenue by the swirl
of a mental backwash. He remembered muddy shores, a harbor without
quays, the one solitary wooden pier (but that was a public work) jutting
out crookedly, the first coal-sheds erected on Monkey Point, that caught
fire mysteriously and smoldered for days, so that amazed ships came
into a roadstead full of sulphurous smoke, and the sun hung blood-red
at midday. He remembered the things, the faces, and something more
besides--like the faint flavor of a cup quaffed to the bottom, like a
subtle sparkle of the air that was not to be found in the atmosphere of
to-day.</p>
<p>In this evocation, swift and full of detail like a flash of magnesium
light into the niches of a dark memorial hall, Captain Whalley
contemplated things once important, the efforts of small men, the growth
of a great place, but now robbed of all consequence by the greatness
of accomplished facts, by hopes greater still; and they gave him for a
moment such an almost physical grip upon time, such a comprehension of
our unchangeable feelings, that he stopped short, struck the ground with
his stick, and ejaculated mentally, "What the devil am I doing here!" He
seemed lost in a sort of surprise; but he heard his name called out in
wheezy tones once, twice--and turned on his heels slowly.</p>
<p>He beheld then, waddling towards him autocratically, a man of an
old-fashioned and gouty aspect, with hair as white as his own, but with
shaved, florid cheeks, wearing a necktie--almost a neckcloth--whose
stiff ends projected far beyond his chin; with round legs, round arms,
a round body, a round face--generally producing the effect of his short
figure having been distended by means of an air-pump as much as the
seams of his clothing would stand. This was the Master-Attendant of the
port. A master-attendant is a superior sort of harbor-master; a person,
out in the East, of some consequence in his sphere; a Government
official, a magistrate for the waters of the port, and possessed of vast
but ill-defined disciplinary authority over seamen of all classes.
This particular Master-Attendant was reported to consider it miserably
inadequate, on the ground that it did not include the power of life
and death. This was a jocular exaggeration. Captain Eliott was fairly
satisfied with his position, and nursed no inconsiderable sense of such
power as he had. His conceited and tyrannical disposition did not allow
him to let it dwindle in his hands for want of use. The uproarious,
choleric frankness of his comments on people's character and conduct
caused him to be feared at bottom; though in conversation many pretended
not to mind him in the least, others would only smile sourly at the
mention of his name, and there were even some who dared to pronounce him
"a meddlesome old ruffian." But for almost all of them one of Captain
Eliott's outbreaks was nearly as distasteful to face as a chance of
annihilation.</p>
<style>
body {
padding: 15px;
}
.pointer {
padding: 15px;
background-color: rgba(0, 0, 0, 0.4);
color: white;
border-radius: 10px;
pointer-events: none;
opacity: 0;
transition: opacity 300ms;
-webkit-transition: opacity 300ms;
}
.pointer.show {
opacity: 1;
}
</style>
<div class="pointer"></div>
<script src="../../tether.js"></script>
<script>
new Tether({
element: '.pointer',
attachment: 'middle right',
targetAttachment: 'middle left',
targetModifier: 'scroll-handle',
target: document.body
});
var headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
var hideTimeout = null;
var pointer = document.querySelector('.pointer')
var getSection = function(){
var closest, closestTop;
for (var i=0; i < headers.length; i++){
var rect = headers[i].<API key>();
if (closestTop === undefined || (rect.top < 0 && rect.top > closestTop)){
closestTop = rect.top;
closest = headers[i];
}
}
return closest.innerHTML;
}
document.addEventListener('scroll', function(){
var percentage = Math.floor((100 * Math.max(0, pageYOffset)) / (document.body.scrollHeight - innerHeight)) + '%'
pointer.innerHTML = getSection() + ' - ' + percentage
pointer.classList.add('show');
if (hideTimeout)
clearTimeout(hideTimeout);
hideTimeout = setTimeout(function(){
pointer.classList.remove('show');
}, 1000);
});
</script>
</body>
</html> |
"use strict";
// Rule Definition
module.exports = function(context) {
var options = {
hoist: (context.options[0] && context.options[0].hoist) || "functions"
};
/**
* Checks if a variable of the class name in the class scope of ClassDeclaration.
*
* ClassDeclaration creates two variables of its name into its outer scope and its class scope.
* So we should ignore the variable in the class scope.
*
* @param {Object} variable The variable to check.
* @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
*/
function <API key>(variable) {
var block = variable.scope.block;
return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
}
/**
* Checks if a variable is inside the initializer of scopeVar.
*
* To avoid reporting at declarations such as `var a = function a() {};`.
* But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
*
* @param {Object} variable The variable to check.
* @param {Object} scopeVar The scope variable to look for.
* @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
*/
function isOnInitializer(variable, scopeVar) {
var outerScope = scopeVar.scope;
var outerDef = scopeVar.defs[0];
var outer = outerDef && outerDef.parent && outerDef.parent.range;
var innerScope = variable.scope;
var innerDef = variable.defs[0];
var inner = innerDef && innerDef.name.range;
return (
outer != null &&
inner != null &&
outer[0] < inner[0] &&
inner[1] < outer[1] &&
((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") &&
outerScope === innerScope.upper
);
}
/**
* Get a range of a variable's identifier node.
* @param {Object} variable The variable to get.
* @returns {Array|undefined} The range of the variable's identifier node.
*/
function getNameRange(variable) {
var def = variable.defs[0];
return def && def.name.range;
}
/**
* Checks if a variable is in TDZ of scopeVar.
* @param {Object} variable The variable to check.
* @param {Object} scopeVar The variable of TDZ.
* @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
*/
function isInTdz(variable, scopeVar) {
var outerDef = scopeVar.defs[0];
var inner = getNameRange(variable);
var outer = getNameRange(scopeVar);
return (
inner != null &&
outer != null &&
inner[1] < outer[0] &&
// Excepts FunctionDeclaration if is {"hoist":"function"}.
(options.hoist !== "functions" || outerDef == null || outerDef.node.type !== "FunctionDeclaration")
);
}
/**
* Checks if a variable is contained in the list of given scope variables.
* @param {Object} variable The variable to check.
* @param {Array} scopeVars The scope variables to look for.
* @returns {boolean} Whether or not the variable is contains in the list of scope variables.
*/
function <API key>(variable, scopeVars) {
return scopeVars.some(function(scopeVar) {
return (
scopeVar.identifiers.length > 0 &&
variable.name === scopeVar.name &&
!<API key>(scopeVar) &&
!isOnInitializer(variable, scopeVar) &&
!(options.hoist !== "all" && isInTdz(variable, scopeVar))
);
});
}
/**
* Checks if the given variables are shadowed in the given scope.
* @param {Array} variables The variables to look for
* @param {Object} scope The scope to be checked.
* @returns {Array} Variables which are not declared in the given scope.
*/
function checkShadowsInScope(variables, scope) {
var passedVars = [];
variables.forEach(function(variable) {
// "arguments" is a special case that has no identifiers (#1759)
if (variable.identifiers.length > 0 && <API key>(variable, scope.variables)) {
context.report(
variable.identifiers[0],
"{{name}} is already declared in the upper scope.",
{name: variable.name});
} else {
passedVars.push(variable);
}
});
return passedVars;
}
/**
* Checks the current context for shadowed variables.
* @param {Scope} scope - Fixme
* @returns {void}
*/
function checkForShadows(scope) {
var variables = scope.variables.filter(function(variable) {
return (
// Skip "arguments".
variable.identifiers.length > 0 &&
// Skip variables of a class name in the class scope of ClassDeclaration.
!<API key>(variable)
);
});
// iterate through the array of variables and find duplicates with the upper scope
var upper = scope.upper;
while (upper && variables.length) {
variables = checkShadowsInScope(variables, upper);
upper = upper.upper;
}
}
return {
"Program:exit": function() {
var globalScope = context.getScope(),
stack = globalScope.childScopes.slice(),
scope;
while (stack.length) {
scope = stack.pop();
stack.push.apply(stack, scope.childScopes);
checkForShadows(scope);
}
}
};
};
module.exports.schema = [
{
"type": "object",
"properties": {
"hoist": {
"enum": ["all", "functions", "never"]
}
}
}
]; |
<!
Copyright (c) Microsoft Corporation. All rights reserved
<!DOCTYPE html>
<html xmlns="http:
<head>
<title></title>
<link rel="stylesheet" href="/css/scenario.css" />
<script src="/js/playreadyeme.js"></script>
<script src="/js/scenario3_eme.js"></script>
</head>
<body class="win-type-body">
<div id="scenarioView">
<div>
<h2 id="sampleHeader" class="win-type-subheader">Description:</h2>
<div id="scenarioDescription">
<p>This example uses W3C standards based Encrypted Media Extensions(EME) to enable protected playback. This is useful for Hosted Web Applications where protected playback is configured the same way it would be in the browser.</p>
</div>
</div>
<div id="scenarioContent">
<div class="playreadyScenario">
<div class="scenarioField">
<label>License URL:</label>
<input type="text" id="inputLaUrl" data-win-bind="value: laURL;onchange: laUrlHandler" />
<span style="width:124px"></span>
<span style="width:124px"></span>
</div>
<div class="scenarioField">
<label>Content:</label>
<input type="text" id="inputContentUrl" data-win-bind="value: contentURL;onchange: contentUrlHandler" />
<button class="win-button" id="btnPlay" data-win-bind="onclick: playHandler">Play</button>
<button class="win-button" data-win-bind="onclick: stopHandler">Stop</button>
</div>
<div class="videoDiv">
<video data-win-bind="onerror: videoErrorHandler" id="video" />
</div>
</div>
</div>
</div>
</body>
</html> |
module Admin::AdminHelper
def user_status_badge user
klass = 'badge-success' if user.registration_status.active?
klass = ['registration-status', 'badge', klass].compact * ' '
content_tag(:span, user.registration_status.titlecase, class: klass)
end
def user_status_button user
action, klass = if user.registration_status.waiting_approval?
["Approve", "btn-success"]
elsif user.registration_status.suspended?
["Activate", "btn-success"]
else
["Suspend", "btn-danger"]
end
klass = ['status-action', 'btn', 'btn-mini', action.downcase, klass] * ' '
content_tag(:button, action, class: klass)
end
def user_admin_button user
action_text, action_class, klass = if user.is_admin?
["Remove from administrators", 'revoke', 'btn-danger']
else
["Make an administrator", 'grant', 'btn-success']
end
klass = ['admin-action', 'btn', 'btn-mini', action_class, klass] * ' '
content_tag(:button, action_text, class: klass)
end
end |
<?php
namespace spec\Sylius\Bundle\ShippingBundle\Form\Type;
use PhpSpec\ObjectBehavior;
class <API key> extends ObjectBehavior
{
function let()
{
$choices = array(
'flat_rate' => 'Flat rate per shipment',
'per_item_rate' => 'Per item rate'
);
$this->beConstructedWith($choices);
}
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\ShippingBundle\Form\Type\<API key>');
}
function it_is_a_form_type()
{
$this->shouldImplement('Symfony\Component\Form\FormTypeInterface');
}
/**
* @param Symfony\Component\OptionsResolver\<API key> $resolver
*/
function <API key>($resolver)
{
$choices = array(
'flat_rate' => 'Flat rate per shipment',
'per_item_rate' => 'Per item rate'
);
$resolver->setDefaults(array('choices' => $choices))->shouldBeCalled();
$this->setDefaultOptions($resolver);
}
} |
<reference path="../_references.ts"/>
/**
* Defined in host.
*/
declare var clusterUri: string;
module jsCommon {
/**
* Http Status code we are interested.
*/
export enum HttpStatusCode {
OK = 200,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
<API key> = 413,
}
/**
* Other HTTP Constants.
*/
export module HttpConstants {
export const <API key> = 'application/octet-stream';
export const MultiPartFormData = 'multipart/form-data';
}
/**
* Extensions to String class.
*/
export module StringExtensions {
export function format(...args: string[]) {
let s = args[0];
if (<API key>(s))
return s;
for (let i = 0; i < args.length - 1; i++) {
let reg = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(reg, args[i + 1]);
}
return s;
}
/**
* Compares two strings for equality, ignoring case.
*/
export function equalIgnoreCase(a: string, b: string): boolean {
return StringExtensions.normalizeCase(a) === StringExtensions.normalizeCase(b);
}
export function <API key>(a: string, b: string): boolean {
let <API key> = StringExtensions.normalizeCase(b);
return StringExtensions.normalizeCase(a).indexOf(<API key>) === 0;
}
/** Determines whether a string contains a specified substring (while ignoring case). */
export function containsIgnoreCase(source: string, substring: string): boolean {
if (source == null)
return false;
return source.toLowerCase().indexOf(substring.toLowerCase().toString()) !== -1;
}
/**
* Normalizes case for a string.
* Used by equalIgnoreCase method.
*/
export function normalizeCase(value: string): string {
Utility.<API key>(value, StringExtensions, 'normalizeCase', 'value');
return value.toUpperCase();
}
/**
* Is string null or empty or undefined?
* @return True if the value is null or undefined or empty string,
* otherwise false.
*/
export function isNullOrEmpty(value: string): boolean {
return (value == null) || (value.length === 0);
}
/**
* Returns true if the string is null, undefined, empty, or only includes white spaces.
* @return True if the str is null, undefined, empty, or only includes white spaces,
* otherwise false.
*/
export function <API key>(str: string): boolean {
return StringExtensions.isNullOrEmpty(str) || StringExtensions.isNullOrEmpty(str.trim());
}
/**
* Returns a value indicating whether the str contains any whitespace.
*/
export function containsWhitespace(str: string): boolean {
Utility.<API key>(str, this, 'containsWhitespace', 'str');
let expr: RegExp = /\s/;
return expr.test(str);
}
/**
* Returns a value indicating whether the str is a whitespace string.
*/
export function isWhitespace(str: string): boolean {
Utility.<API key>(str, this, 'isWhitespace', 'str');
return str.trim() === '';
}
/**
* Returns the string with any trailing whitespace from str removed.
*/
export function <API key>(str: string): string {
Utility.<API key>(str, this, '<API key>', 'str');
return str.replace(/\s+$/, '');
}
/**
* Returns the string with any leading and trailing whitespace from str removed.
*/
export function trimWhitespace(str: string): string {
Utility.<API key>(str, this, 'trimWhitespace', 'str');
return str.replace(/^\s+/, '').replace(/\s+$/, '');
}
/**
* Returns length difference between the two provided strings.
*/
export function getLengthDifference(left: string, right: string) {
Utility.<API key>(left, this, 'getLengthDifference', 'left');
Utility.<API key>(right, this, 'getLengthDifference', 'right');
return Math.abs(left.length - right.length);
}
/**
* Repeat char or string several times.
* @param char The string to repeat.
* @param count How many times to repeat the string.
*/
export function repeat(char: string, count: number): string {
let result = "";
for (let i = 0; i < count; i++) {
result += char;
}
return result;
}
/**
* Replace all the occurrences of the textToFind in the text with the textToReplace.
* @param text The original string.
* @param textToFind Text to find in the original string.
* @param textToReplace New text replacing the textToFind.
*/
export function replaceAll(text: string, textToFind: string, textToReplace: string): string {
if (!textToFind)
return text;
let pattern = <API key>(textToFind);
return text.replace(new RegExp(pattern, 'gi'), textToReplace);
}
/**
* Returns a name that is not specified in the values.
*/
export function findUniqueName(
usedNames: { [name: string]: boolean },
baseName: string): string {
debug.assertValue(usedNames, 'usedNames');
debug.assertValue(baseName, 'baseName');
// Find a unique name
let i = 0,
uniqueName: string = baseName;
while (usedNames[uniqueName]) {
uniqueName = baseName + (++i);
}
return uniqueName;
}
export function <API key>(list: string[], resourceProvider: <API key>, maxValue?: number): string {
if (!list || list.length === 0)
return '';
if (maxValue === null || maxValue === undefined)
maxValue = Number.MAX_VALUE;
let length = Math.min(maxValue, list.length);
let replacedList = [];
// Only need to replace user entries of {0} and {1} since we build the list in pairs.
for (let j = 0; j < 2; j++) {
let targetValue = '{' + j + '}';
let replaceValue = '_|_<' + j + '>_|_';
for (let i = 0; i < length; i++) {
if (list[i].indexOf(targetValue) > -1) {
list[i] = list[i].replace(targetValue, replaceValue);
replacedList.push({ targetValue: targetValue, replaceValue: replaceValue });
}
}
}
let commaSeparatedList: string = '';
for (let i = 0; i < length; i++) {
if (i === 0)
commaSeparatedList = list[i];
else
commaSeparatedList = StringExtensions.format(resourceProvider.get('<API key>'), commaSeparatedList, list[i]);
}
for (let i = 0; i < replacedList.length; i++) {
commaSeparatedList = commaSeparatedList.replace(replacedList[i].replaceValue, replacedList[i].targetValue);
}
return commaSeparatedList;
}
export function <API key>(s: string): string {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1');
}
}
/**
* Interface used for interacting with WCF typed objects.
*/
export interface TypedObject {
__type: string;
}
/**
* The general utility class.
*/
export class Utility {
private static TypeNamespace = 'http://schemas.microsoft.com/sqlbi/2013/01/NLRuntimeService';
public static JsonContentType = 'application/json';
public static JpegContentType = 'image/jpeg';
public static <API key> = 'application/x-javascript';
public static JsonDataType = 'json';
public static BlobDataType = 'blob';
public static HttpGetMethod = 'GET';
public static HttpPostMethod = 'POST';
public static HttpPutMethod = 'PUT';
public static HttpDeleteMethod = 'DELETE';
public static <API key> = 'Content-Type';
public static HttpAcceptHeader = 'Accept';
public static Undefined = 'undefined';
private static <API key>: string = window.location.protocol + '//' + window.location.host;
/**
* Ensures the specified value is not null or undefined. Throws a relevent exception if it is.
* @param value The value to check.
* @param context The context from which the check originated.
* @param methodName The name of the method that initiated the check.
* @param parameterName The parameter name of the value to check.
*/
public static <API key>(value, context, methodName, parameterName) {
if (value === null) {
Utility.throwException(Errors.argumentNull(Utility.getComponentName(context) + methodName + '.' + parameterName));
}
else if (typeof (value) === Utility.Undefined) {
Utility.throwException(Errors.argumentUndefined(Utility.getComponentName(context) + methodName + '.' + parameterName));
}
}
/**
* Ensures the specified value is not null, undefined or empty. Throws a relevent exception if it is.
* @param value The value to check.
* @param context The context from which the check originated.
* @param methodName The name of the method that initiated the check.
* @param parameterName The parameter name of the value to check.
*/
public static throwIfNullOrEmpty(value: any, context: any, methodName: string, parameterName: string) {
Utility.<API key>(value, context, methodName, parameterName);
if (!value.length) {
Utility.throwException(Errors.argumentOutOfRange(Utility.getComponentName(context) + methodName + '.' + parameterName));
}
}
/**
* Ensures the specified string is not null, undefined or empty. Throws a relevent exception if it is.
* @param value The value to check.
* @param context The context from which the check originated.
* @param methodName The name of the method that initiated the check.
* @param parameterName The parameter name of the value to check.
*/
public static <API key>(value: string, context: any, methodName: string, parameterName: string) {
Utility.<API key>(value, context, methodName, parameterName);
if (value.length < 1) {
Utility.throwException(Errors.argumentOutOfRange(Utility.getComponentName(context) + methodName + '.' + parameterName));
}
}
/**
* Ensures the specified value is not null, undefined, whitespace or empty. Throws a relevent exception if it is.
* @param value The value to check.
* @param context The context from which the check originated.
* @param methodName The name of the method that initiated the check.
* @param parameterName The parameter name of the value to check.
*/
public static <API key>(value: string, context: any, methodName: string, parameterName: string) {
Utility.<API key>(value, context, methodName, parameterName);
if (StringExtensions.<API key>(value)) {
Utility.throwException(Errors.argumentOutOfRange(Utility.getComponentName(context) + methodName + '.' + parameterName));
}
}
/**
* Ensures the specified condition is true. Throws relevant exception if it isn't.
* @param condition The condition to check.
* @param context The context from which the check originated.
* @param methodName The name of the method that initiated the check.
* @param parameterName The parameter name against which the condition is checked.
*/
public static throwIfNotTrue(condition: boolean, context: any, methodName: string, parameterName: string) {
if (!condition) {
Utility.throwException(Errors.argument(parameterName, Utility.getComponentName(context) + methodName + '.' + parameterName));
}
}
/**
* Checks whether the provided value is a 'string'.
* @param value The value to test.
*/
public static isString(value: any): boolean {
return ((typeof value) === 'string');
}
/**
* Checks whether the provided value is a 'boolean'.
* @param value The value to test.
*/
public static isBoolean(value: any): boolean {
return ((typeof value) === 'boolean');
}
/**
* Checks whether the provided value is a 'number'.
* @param value The value to test.
*/
public static isNumber(value: any): boolean {
return ((typeof value) === 'number');
}
/**
* Checks whether the provided value is a Date instance.
* @param value The value to test.
*/
public static isDate(value: any): boolean {
return Utility.isObject(value) && (value instanceof Date);
}
/**
* Checks whether the provided value is an 'object'.
* @param value The value to test.
*/
public static isObject(value: any): boolean {
return (value != null) && ((typeof value) === 'object');
}
/**
* Checks whether the provided value is null or undefined.
* @param value The value to test.
*/
public static isNullOrUndefined(value: any): boolean {
return (value === null) || (typeof (value) === Utility.Undefined);
}
/**
* Combine a base url and a path.
* @param baseUrl The base url.
* @param path The path to add on to the base url.
* @returns The combined url.
*/
public static urlCombine(baseUrl: string, path: string) {
Utility.<API key>(baseUrl, null, "urlCombine", "baseUrl");
Utility.<API key>(path, null, "urlCombine", "path");
// should any of the components be empty, fail gracefuly - this is important when using the test page
if (StringExtensions.<API key>(path)) {
return baseUrl;
}
if (StringExtensions.<API key>(baseUrl)) {
return path;
}
let finalUrl = baseUrl;
if (finalUrl.charAt(finalUrl.length - 1) === '/') {
if (path.charAt(0) === '/')
path = path.slice(1);
} else {
if (path.charAt(0) !== '/')
path = '/' + path;
}
return finalUrl + path;
}
public static getAbsoluteUri(path: string): string {
Utility.<API key>(path, null, "getAbsoluteUri", "path");
let url = path;
// Make absolute
if (url && url.indexOf('http') === - 1) {
url = Utility.urlCombine(clusterUri, url);
}
return url;
}
public static <API key>(path: string) {
Utility.<API key>(path, null, "<API key>", "path");
let url = path;
// Make absolute
if (url && url.indexOf('http') === - 1) {
url = jsCommon.Utility.urlCombine(Utility.<API key>, url);
}
return url;
}
public static getComponentName(context) {
return !context ? '' : (typeof context).toString() + '.';
}
public static throwException(e) {
Trace.error(
StringExtensions.format("Throwing exception: {0}", JSON.stringify(e)),
/*includeStackTrace*/ e.stack != null ? false : true);
throw e;
}
public static createClassSelector(className: string): string {
Utility.<API key>(className, null, 'CreateClassSelector', 'className');
return '.' + className;
}
public static createIdSelector(id: string): string {
Utility.<API key>(id, null, 'CreateIdSelector', 'id');
return '
}
/**
* Creates a client-side Guid string.
* @returns A string representation of a Guid.
*/
public static generateGuid(): string {
let guid = "",
idx = 0;
for (idx = 0; idx < 32; idx += 1) {
let guidDigitsItem = Math.random() * 16 | 0;
switch (idx) {
case 8:
case 12:
case 16:
case 20:
guid += "-";
break;
}
guid += guidDigitsItem.toString(16);
}
return guid;
}
/**
* Generates a random 7 character string that is used as a connection group name.
* @returns A random connection group name.
*/
public static <API key>(): string {
let name = "";
let possible = "<API key>";
for (let i = 0; i < 7; i++)
name += possible.charAt(Math.floor(Math.random() * possible.length));
return name;
}
/**
* Try extract a cookie from {@link document.cookie} identified by key.
*/
public static getCookieValue(key: string): string {
// the cookie is of the format <key1=value1>; <key2=value2>. Split by ';', then by '='
// to search for the key
let keyValuePairs = document.cookie.split(';');
for (let i = 0; i < keyValuePairs.length; i++) {
let keyValue = keyValuePairs[i];
let split = keyValue.split('=');
if (split.length > 0 && split[0].trim() === key) {
return keyValue.substr(keyValue.indexOf('=') + 1);
}
}
return null;
}
/**
* Extracts the protocol://hostname section of a url.
* @param url The URL from which to extract the section.
* @returns The protocol://hostname portion of the given URL.
*/
public static getDomainForUrl(url: string): string {
let hrefObject = Utility.<API key>(url);
return hrefObject.prop('protocol') + '//' + hrefObject.prop('hostname');
}
/**
* Extracts the hostname and absolute path sections of a url.
* @param url The URL from which to extract the section.
* @returns The hostname and absolute path portion of the given URL.
*/
public static getHostNameForUrl(url: string): string {
let hrefObject = Utility.<API key>(url);
return Utility.urlCombine(hrefObject.prop('hostname'), hrefObject.prop('pathname'));
}
/**
* Return the original url with query string stripped.
* @param url The URL from which to extract the section.
* @returns the original url with query string stripped.
*/
public static <API key>(url: string): string {
let hrefObject = Utility.<API key>(url);
return hrefObject.prop('protocol') + '//' + Utility.urlCombine(hrefObject.prop('host'), hrefObject.prop('pathname'));
}
/**
* Extracts the protocol section of a url.
* @param url The URL from which to extract the section.
* @returns The protocol for the current URL.
*/
public static getProtocolFromUrl(url: string): string {
return Utility.<API key>(url).prop('protocol').replace(':', '');
}
/**
* Returns a formatted href object from a URL.
* @param url The URL used to generate the object.
* @returns A jQuery object with the url.
*/
public static <API key>(url: string): JQuery {
let aObject = $('<a>');
aObject = aObject.prop('href', url);
return aObject;
}
/**
* Converts a WCF representation of a dictionary to a JavaScript dictionary.
* @param wcfDictionary The WCF dictionary to convert.
* @returns The native JavaScript representation of this dictionary.
*/
public static <API key>(wcfDictionary: any[]): { [index: string]: any; } {
// convert the WCF JSON representation of a dictionary
// to JS dictionary.
// WCF representation: [{"Key": Key, "Value": Value}..]
// JS representation: [Key: Value ..]
let result: { [index: string]: any; } = {};
for (let i = 0; i < wcfDictionary.length; i++) {
let keyValuePair = wcfDictionary[i];
result[keyValuePair['Key']] = keyValuePair['Value'];
}
return result;
}
public static <API key>(jsonDate: string, fromUtcMilliseconds: boolean): Date {
if (StringExtensions.isNullOrEmpty(jsonDate)) {
return null;
}
let begIndex = jsonDate.indexOf('(');
let endIndex = jsonDate.indexOf(')');
if (begIndex !== -1 && endIndex !== -1) {
let milliseconds = parseInt(jsonDate.substring(begIndex + 1, endIndex), 10);
if (fromUtcMilliseconds) {
return new Date(milliseconds);
}
else {
let retValue = new Date(0);
retValue.setUTCMilliseconds(milliseconds);
return retValue;
}
}
return null;
}
/**
* Get the outer html of the given jquery object.
* @param content The jquery object.
* @returns The entire html representation of the object.
*/
public static getOuterHtml(content: JQuery): string {
return $('<div>').append(content).html();
}
/**
* Comparison Method: Compares two integer numbers.
* @param a An integer value.
* @param b An integer value.
* @returns The comparison result.
*/
public static compareInt(a: number, b: number): number {
return a - b;
}
/**
* Return the index of the smallest value in a numerical array.
* @param a A numeric array.
* @returns The index of the smallest value in the array.
*/
public static getIndexOfMinValue(a: number[]) {
let retValue = 0;
let currentMinValue = a[0];
for (let i = 0; i < a.length; i++) {
if (a[i] < currentMinValue) {
currentMinValue = a[i];
retValue = i;
}
}
return retValue;
}
/**
* Tests whether a URL is valid.
* @param url The url to be tested.
* @returns Whether the provided url is valid.
*/
public static isValidUrl(url: string): boolean {
return !StringExtensions.isNullOrEmpty(url) &&
(StringExtensions.<API key>(url, 'http:
}
public static <API key>(input: string) {
return input.replace(/"/g, "").replace(/url\(|\)$/ig, "");
}
/**
* Verifies image data url of images.
*/
public static isValidImageDataUrl(url: string): boolean {
let regex: RegExp = new RegExp('data:(image\/(png|jpg|jpeg|gif|svg))');
return regex.test(url);
}
/**
* Downloads a content string as a file.
* @param content Content stream.
* @param fileName File name to use.
*/
public static saveAsFile(content: any, fileName: string): void {
let contentBlob = new Blob([content], { type: HttpConstants.<API key> });
let url = window['webkitURL'] || URL;
let urlLink = url.createObjectURL(contentBlob);
let fileNameLink = fileName || urlLink;
// IE support, use msSaveOrOpenBlob API
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(contentBlob, fileNameLink);
return;
}
// WebKit-based browser support requires generating an anchor tag with
// download attribute set to blob store and triggering a click event to invoke
// a download to file action
let hyperlink = document.createElement('a');
hyperlink.href = urlLink;
hyperlink.target = '_blank';
hyperlink['download'] = fileNameLink;
document.body.appendChild(hyperlink);
hyperlink.click();
document.body.removeChild(hyperlink);
}
/**
* Helper method to get the simple type name from a typed object.
* @param obj The typed object.
* @returns The simple type name for the object.
*/
public static getType(obj: TypedObject) {
Utility.<API key>(obj.__type, this, 'getType', 'obj');
let parts = obj.__type.split(":");
if (parts.length !== 2) {
Errors.argument("obj.__type", "Type String not in expected format [Type]#[Namespace]: " + obj.__type);
}
if (parts[1] !== Utility.TypeNamespace) {
Errors.argument("obj.__type", "Type Namespace not expected: " + parts[1]);
}
return parts[0];
}
/**
* Check if an element supports a specific event type.
* @param eventName The name of the event.
* @param element The element to test for event support.
* @returns Whether the even is supported on the provided element.
*/
public static isEventSupported(eventName: string, element: Element): boolean {
eventName = 'on' + eventName;
let isSupported = (eventName in element);
if (!isSupported) {
// if we can't use setAttribute try a generic element
if (!element.setAttribute) {
element = document.createElement('div');
}
if (element.setAttribute && element.removeAttribute) {
element.setAttribute(eventName, '');
isSupported = typeof element[eventName] === 'function';
// if the property was created - remove it
if (typeof element[eventName] !== 'undefined') {
element[eventName] = null;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
public static toPixel(pixelAmount: number): string {
Utility.<API key>(pixelAmount, this, "toPixel", "pixelAmount");
return pixelAmount.toString() + CssConstants.pixelUnits;
}
public static getPropertyCount(object: any) {
Utility.<API key>(object, this, "getPropertyCount", "object");
return Object.getOwnPropertyNames(object).length;
}
/**
* Check if an element supports a specific event type.
* @param filePath File path.
* @returns File extension.
*/
public static getFileExtension(filePath: string): string {
if (filePath) {
let index = filePath.lastIndexOf('.');
if (index >= 0)
return filePath.substr(index + 1);
}
return '';
}
/**
* Extract the filename out of a full path delimited by '\' or '/'.
* @param filePath File path.
* @returns filename File name.
*/
public static <API key>(filePath: string): string {
return filePath.replace(/^.*[\\\/]/, '');
}
/**
* This method indicates whether window.clipboardData is supported.
* For example, clipboard support for Windows Store apps is currently disabled
* since window.clipboardData is unsupported (it raises access denied error)
* since clipboard in Windows Store is being
* achieved through Windows.ApplicationModel.DataTransfer.Clipboard class.
*/
public static canUseClipboard(): boolean {
return (typeof MSApp === "undefined");
}
public static <API key>(): boolean {
return navigator.userAgent.indexOf("WOW64") !== -1 ||
navigator.userAgent.indexOf("Win64") !== -1;
}
public static parseNumber(value: any, defaultValue?: number): number {
if (value === null)
return null;
if (value === undefined)
return defaultValue;
let result = Number(value);
if (isFinite(result))
return result;
if (isNaN(result) && !(typeof value === "number" || value === "NaN"))
return defaultValue;
return result;
}
public static getURLParamValue(name:string) {
let results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
}
else {
return results[1] || 0;
}
}
public static <API key>(): string {
let timeSummer = new Date(Date.UTC(2005, 6, 30, 0, 0, 0, 0));
let summerOffset = -1 * timeSummer.getTimezoneOffset();
let timeWinter = new Date(Date.UTC(2005, 12, 30, 0, 0, 0, 0));
let winterOffset = -1 * timeWinter.getTimezoneOffset();
let localTimeZoneString;
if (-720 === summerOffset && -720 === winterOffset) { localTimeZoneString = 'Dateline Standard Time'; }
else if (-660 === summerOffset && -660 === winterOffset) { localTimeZoneString = 'UTC-11'; }
else if (-660 === summerOffset && -660 === winterOffset) { localTimeZoneString = 'Samoa Standard Time'; }
else if (-600 === summerOffset && -600 === winterOffset) { localTimeZoneString = 'Hawaiian Standard Time'; }
else if (-480 === summerOffset && -540 === winterOffset) { localTimeZoneString = 'Alaskan Standard Time'; }
else if (-420 === summerOffset && -480 === winterOffset) { localTimeZoneString = 'Pacific Standard Time'; }
else if (-420 === summerOffset && -420 === winterOffset) { localTimeZoneString = 'US Mountain Standard Time'; }
else if (-360 === summerOffset && -420 === winterOffset) { localTimeZoneString = 'Mountain Standard Time'; }
else if (-360 === summerOffset && -360 === winterOffset) { localTimeZoneString = 'Central America Standard Time'; }
else if (-300 === summerOffset && -360 === winterOffset) { localTimeZoneString = 'Central Standard Time'; }
else if (-300 === summerOffset && -300 === winterOffset) { localTimeZoneString = 'SA Pacific Standard Time'; }
else if (-240 === summerOffset && -300 === winterOffset) { localTimeZoneString = 'Eastern Standard Time'; }
else if (-270 === summerOffset && -270 === winterOffset) { localTimeZoneString = 'Venezuela Standard Time'; }
else if (-240 === summerOffset && -240 === winterOffset) { localTimeZoneString = 'SA Western Standard Time'; }
else if (-240 === summerOffset && -180 === winterOffset) { localTimeZoneString = 'Central Brazilian Standard Time'; }
else if (-180 === summerOffset && -240 === winterOffset) { localTimeZoneString = 'Atlantic Standard Time'; }
else if (-180 === summerOffset && -180 === winterOffset) { localTimeZoneString = 'Montevideo Standard Time'; }
else if (-180 === summerOffset && -120 === winterOffset) { localTimeZoneString = 'E. South America Standard Time'; }
else if (-150 === summerOffset && -210 === winterOffset) { localTimeZoneString = 'Mid-Atlantic Standard Time'; }
else if (-120 === summerOffset && -120 === winterOffset) { localTimeZoneString = 'SA Eastern Standard Time'; }
else if (0 === summerOffset && 0 === winterOffset) { localTimeZoneString = 'UTC'; }
else if (60 === summerOffset && 0 === winterOffset) { localTimeZoneString = 'GMT Standard Time'; }
else if (60 === summerOffset && 120 === winterOffset) { localTimeZoneString = 'Namibia Standard Time'; }
else if (120 === summerOffset && 60 === winterOffset) { localTimeZoneString = 'Romance Standard Time'; }
else if (120 === summerOffset && 120 === winterOffset) { localTimeZoneString = 'South Africa Standard Time'; }
else if (180 === summerOffset && 120 === winterOffset) { localTimeZoneString = 'GTB Standard Time'; }
else if (180 === summerOffset && 180 === winterOffset) { localTimeZoneString = 'E. Africa Standard Time'; }
else if (240 === summerOffset && 180 === winterOffset) { localTimeZoneString = 'Russian Standard Time'; }
else if (240 === summerOffset && 240 === winterOffset) { localTimeZoneString = 'Arabian Standard Time'; }
else if (270 === summerOffset && 210 === winterOffset) { localTimeZoneString = 'Iran Standard Time'; }
else if (270 === summerOffset && 270 === winterOffset) { localTimeZoneString = 'Afghanistan Standard Time'; }
else if (300 === summerOffset && 240 === winterOffset) { localTimeZoneString = 'Pakistan Standard Time'; }
else if (300 === summerOffset && 300 === winterOffset) { localTimeZoneString = 'West Asia Standard Time'; }
else if (330 === summerOffset && 330 === winterOffset) { localTimeZoneString = 'India Standard Time'; }
else if (345 === summerOffset && 345 === winterOffset) { localTimeZoneString = 'Nepal Standard Time'; }
else if (360 === summerOffset && 300 === winterOffset) { localTimeZoneString = 'N. Central Asia Standard Time'; }
else if (360 === summerOffset && 360 === winterOffset) { localTimeZoneString = 'Central Asia Standard Time'; }
else if (390 === summerOffset && 390 === winterOffset) { localTimeZoneString = 'Myanmar Standard Time'; }
else if (420 === summerOffset && 360 === winterOffset) { localTimeZoneString = 'North Asia Standard Time'; }
else if (420 === summerOffset && 420 === winterOffset) { localTimeZoneString = 'SE Asia Standard Time'; }
else if (480 === summerOffset && 420 === winterOffset) { localTimeZoneString = 'North Asia East Standard Time'; }
else if (480 === summerOffset && 480 === winterOffset) { localTimeZoneString = 'China Standard Time'; }
else if (540 === summerOffset && 480 === winterOffset) { localTimeZoneString = 'Yakutsk Standard Time'; }
else if (540 === summerOffset && 540 === winterOffset) { localTimeZoneString = 'Tokyo Standard Time'; }
else if (570 === summerOffset && 570 === winterOffset) { localTimeZoneString = 'Cen. Australia Standard Time'; }
else if (600 === summerOffset && 600 === winterOffset) { localTimeZoneString = 'E. Australia Standard Time'; }
else if (600 === summerOffset && 660 === winterOffset) { localTimeZoneString = 'AUS Eastern Standard Time'; }
else if (660 === summerOffset && 600 === winterOffset) { localTimeZoneString = 'Tasmania Standard Time'; }
else if (660 === summerOffset && 660 === winterOffset) { localTimeZoneString = 'West Pacific Standard Time'; }
else if (690 === summerOffset && 690 === winterOffset) { localTimeZoneString = 'Central Pacific Standard Time'; }
else if (720 === summerOffset && 660 === winterOffset) { localTimeZoneString = 'Magadan Standard Time'; }
else if (720 === summerOffset && 720 === winterOffset) { localTimeZoneString = 'Fiji Standard Time'; }
else if (720 === summerOffset && 780 === winterOffset) { localTimeZoneString = 'New Zealand Standard Time'; }
else if (780 === summerOffset && 780 === winterOffset) { localTimeZoneString = 'Tonga Standard Time'; }
else { localTimeZoneString = 'UTC'; }
return localTimeZoneString;
}
}
export class VersionUtility {
/**
* Compares 2 version strings.
* @param versionA The first version string.
* @param versionB The second version string.
* @returns A result for the comparison.
*/
static compareVersions(versionA: string, versionB: string): number {
let a = versionA.split('.').map(parseFloat);
let b = versionB.split('.').map(parseFloat);
let versionParts = Math.max(a.length, b.length);
for (let i = 0; i < versionParts; i++) {
let partA = a[i] || 0;
let partB = b[i] || 0;
if (partA > partB)
return 1;
if (partA < partB)
return -1;
}
return 0;
}
}
export module PerformanceUtil {
export class PerfMarker {
private _name: string;
private _start: string;
constructor(name: string) {
this._name = name;
this._start = PerfMarker.begin(name);
}
private static begin(name: string) {
if (window.performance === undefined || performance.mark === undefined) return;
if (console.time) {
console.time(name);
}
name = 'Begin ' + name;
performance.mark(name);
return name;
}
public end() {
if (window.performance === undefined || performance.mark === undefined || performance.measure === undefined) return;
let name = this._name;
let end = 'End ' + name;
performance.mark(end);
performance.measure(name, this._start, end);
if (console.timeEnd) {
console.timeEnd(name);
}
}
}
export function create(name: string): PerfMarker {
return new PerfMarker(name);
}
}
export module DeferUtility {
/**
* Wraps a callback and returns a new function.
* The function can be called many times but the callback
* will only be executed once on the next frame.
* Use this to throttle big UI updates and access to DOM.
*/
export function deferUntilNextFrame(callback: Function): Function {
let isWaiting, args, context;
if (!window.<API key>) {
window.<API key> = (func) => setTimeout(func, 1000 / 50);
}
return function() {
if (!isWaiting) {
isWaiting = true;
args = arguments;
context = this;
window.<API key>(() => {
isWaiting = false;
callback.apply(context, args);
});
}
};
}
}
} |
#import <Cocoa/Cocoa.h>
FOUNDATION_EXPORT double <API key>;
FOUNDATION_EXPORT const unsigned char <API key>[]; |
<div ng-controller='LoginCtrl' class='login'>
<div app-login forgot-pass='forgotPass' login='login'></div>
</div> |
#ifndef <API key>
#define <API key>
#include "shrpx.h"
#include <ev.h>
namespace shrpx {
class ConnectionHandler;
class AcceptHandler {
public:
AcceptHandler(int fd, ConnectionHandler *h);
~AcceptHandler();
void accept_connection();
void enable();
void disable();
int get_fd() const;
private:
ev_io wev_;
ConnectionHandler *conn_hnr_;
int fd_;
};
} // namespace shrpx
#endif // <API key> |
package org.openhab.binding.homematic.internal.communicator.server;
import java.io.IOException;
/**
* Simple RPC server interface.
*
* @author Gerhard Riegler - Initial contribution
*/
public interface RpcServer {
/**
* Starts the rpc server.
*/
public void start() throws IOException;
/**
* Stops the rpc server.
*/
public void shutdown();
} |
#include "DVDCodecUtils.h"
#include "Util.h"
#include "cores/FFmpeg.h"
#include "cores/VideoPlayer/Interface/TimingConstants.h"
extern "C" {
#include <libswscale/swscale.h>
}
bool CDVDCodecUtils::<API key>(int width)
{
// known hardware limitation of purevideo 3 (VP3). (the Nvidia 9400 is a purevideo 3 chip)
// from nvidia's linux vdpau README: All current third generation PureVideo hardware
// (G98, MCP77, MCP78, MCP79, MCP7A) cannot decode H.264 for the following horizontal resolutions:
// This relates to the following macroblock sizes.
int unsupported[] = {49, 54, 59, 64, 113, 118, 123, 128};
for (int u : unsupported)
{
if (u == (width + 15) / 16)
return false;
}
return true;
}
double CDVDCodecUtils::<API key>(double frameduration, bool *match)
{
//if the duration is within 20 microseconds of a common duration, use that
const double durations[] = {DVD_TIME_BASE * 1.001 / 24.0, DVD_TIME_BASE / 24.0, DVD_TIME_BASE / 25.0,
DVD_TIME_BASE * 1.001 / 30.0, DVD_TIME_BASE / 30.0, DVD_TIME_BASE / 50.0,
DVD_TIME_BASE * 1.001 / 60.0, DVD_TIME_BASE / 60.0};
double lowestdiff = DVD_TIME_BASE;
int selected = -1;
for (size_t i = 0; i < ARRAY_SIZE(durations); i++)
{
double diff = fabs(frameduration - durations[i]);
if (diff < DVD_MSEC_TO_TIME(0.02) && diff < lowestdiff)
{
selected = i;
lowestdiff = diff;
}
}
if (selected != -1)
{
if (match)
*match = true;
return durations[selected];
}
else
{
if (match)
*match = false;
return frameduration;
}
} |
#!/usr/bin/perl
# This file is part of Koha.
# Koha is free software; you can redistribute it and/or modify it under the
# version.
# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
# with Koha; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
use strict;
#use warnings; FIXME - Bug 2505
use C4::Auth;
use CGI;
use C4::Context;
use C4::Search;
use C4::Output;
=head1 FUNCTIONS
=head2 plugin_parameters
Other parameters added when the plugin is called by the dopop function
=cut
sub plugin_parameters {
my ($dbh,$record,$tagslib,$i,$tabloop) = @_;
return "";
}
sub plugin_javascript {
my ($dbh,$record,$tagslib,$field_number,$tabloop) = @_;
my $function_name= $field_number;
my $res="
<script>
function Focus$function_name(subfield_managed) {
return 1;
}
function Blur$function_name(subfield_managed) {
return 1;
}
function Clic$function_name(i) {
defaultvalue=document.getElementById(\"$field_number\").value;
newin=window.open(\"../cataloguing/plugin_launcher.pl?plugin_name=unimarc_field_123a.pl&index=$field_number&result=\"+defaultvalue,\"unimarc_field_123a\",'width=1000,height=375,toolbar=false,scrollbars=yes');
}
</script>
";
return ($function_name,$res);
}
sub plugin {
my ($input) = @_;
my $index= $input->param('index');
my $result= $input->param('result');
my $dbh = C4::Context->dbh;
my ($template, $loggedinuser, $cookie)
= <API key>({template_name => "cataloguing/value_builder/unimarc_field_123a.tmpl",
query => $input,
type => "intranet",
authnotrequired => 0,
flagsrequired => {editcatalogue => '*'},
debug => 1,
});
my $f1 = substr($result,0,1);
$template->param(index => $index,
"f1$f1" => $f1);
<API key> $input, $cookie, $template->output;
}
1; |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* functions for displaying server, database and table export
*
* @usedby display_export.inc.php
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Outputs appropriate checked statement for checkbox.
*
* @param string $str option name
*
* @return string
*/
function <API key>($str)
{
if (isset($GLOBALS['cfg']['Export'][$str]) && $GLOBALS['cfg']['Export'][$str]) {
return ' checked="checked"';
}
return null;
}
/**
* Prints Html For Export Selection Options
*
* @param String $tmp_select Tmp selected method of export
*
* @return string
*/
function <API key>($tmp_select = '')
{
$multi_values = '<div style="text-align: left">';
$multi_values .= '<a href="
$multi_values .= ' onclick="setSelectOptions'
. '(\'dump\', \'db_select[]\', true); return false;">';
$multi_values .= __('Select All');
$multi_values .= '</a>';
$multi_values .= ' / ';
$multi_values .= '<a href="
$multi_values .= ' onclick="setSelectOptions'
. '(\'dump\', \'db_select[]\', false); return false;">';
$multi_values .= __('Unselect All') . '</a><br />';
$multi_values .= '<select name="db_select[]" '
. 'id="db_select" size="10" multiple="multiple">';
$multi_values .= "\n";
// Check if the selected databases are defined in $_GET
// (from clicking Back button on export.php)
if (isset($_GET['db_select'])) {
$_GET['db_select'] = urldecode($_GET['db_select']);
$_GET['db_select'] = explode(",", $_GET['db_select']);
}
foreach ($GLOBALS['pma']->databases as $current_db) {
if ($current_db == 'information_schema'
|| $current_db == 'performance_schema'
|| $current_db == 'mysql'
) {
continue;
}
if (isset($_GET['db_select'])) {
if (in_array($current_db, $_GET['db_select'])) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
} elseif (!empty($tmp_select)) {
if (/*overload*/mb_strpos(
' ' . $tmp_select,
'|' . $current_db . '|'
)) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
} else {
$is_selected = ' selected="selected"';
}
$current_db = htmlspecialchars($current_db);
$multi_values .= ' <option value="' . $current_db . '"'
. $is_selected . '>' . $current_db . '</option>' . "\n";
} // end while
$multi_values .= "\n";
$multi_values .= '</select></div>';
return $multi_values;
}
/**
* Prints Html For Export Hidden Input
*
* @param String $export_type Selected Export Type
* @param String $db Selected DB
* @param String $table Selected Table
* @param String $single_table Single Table
* @param String $sql_query Sql Query
*
* @return string
*/
function <API key>(
$export_type, $db, $table, $single_table, $sql_query
) {
global $cfg;
$html = "";
if ($export_type == 'server') {
$html .= <API key>('', '', 1);
} elseif ($export_type == 'database') {
$html .= <API key>($db, '', 1);
} else {
$html .= <API key>($db, $table, 1);
}
// just to keep this value for possible next display of this form after saving
// on server
if (!empty($single_table)) {
$html .= '<input type="hidden" name="single_table" value="TRUE" />'
. "\n";
}
$html .= '<input type="hidden" name="export_type" value="'
. $export_type . '" />';
$html .= "\n";
// If the export method was not set, the default is quick
if (isset($_GET['export_method'])) {
$cfg['Export']['method'] = $_GET['export_method'];
} elseif (! isset($cfg['Export']['method'])) {
$cfg['Export']['method'] = 'quick';
}
// The export method (quick, custom or custom-no-form)
$html .= '<input type="hidden" name="export_method" value="'
. htmlspecialchars($cfg['Export']['method']) . '" />';
if (! empty($sql_query)) {
$html .= '<input type="hidden" name="sql_query" value="'
. htmlspecialchars($sql_query) . '" />' . "\n";
} elseif (isset($_GET['sql_query'])) {
$html .= '<input type="hidden" name="sql_query" value="'
. htmlspecialchars($_GET['sql_query']) . '" />' . "\n";
}
return $html;
}
/**
* Prints Html For Export Options Header
*
* @param String $export_type Selected Export Type
* @param String $db Selected DB
* @param String $table Selected Table
*
* @return string
*/
function <API key>($export_type, $db, $table)
{
$html = '<div class="exportoptions" id="header">';
$html .= '<h2>';
$html .= PMA_Util::getImage('b_export.png', __('Export'));
if ($export_type == 'server') {
$html .= __('Exporting databases from the current server');
} elseif ($export_type == 'database') {
$html .= sprintf(
__('Exporting tables from "%s" database'),
htmlspecialchars($db)
);
} else {
$html .= sprintf(
__('Exporting rows from "%s" table'),
htmlspecialchars($table)
);
}
$html .= '</h2>';
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Method
*
* @return string
*/
function <API key>()
{
global $cfg;
if (isset($_GET['quick_or_custom'])) {
$export_method = $_GET['quick_or_custom'];
} else {
$export_method = $cfg['Export']['method'];
}
if ($export_method == 'custom-no-form') {
return '';
}
$html = '<div class="exportoptions" id="quick_or_custom">';
$html .= '<h3>' . __('Export Method:') . '</h3>';
$html .= '<ul>';
$html .= '<li>';
$html .= '<input type="radio" name="quick_or_custom" value="quick" '
. ' id="radio_quick_export"';
if ($export_method == 'quick') {
$html .= ' checked="checked"';
}
$html .= ' />';
$html .= '<label for ="radio_quick_export">';
$html .= __('Quick - display only the minimal options');
$html .= '</label>';
$html .= '</li>';
$html .= '<li>';
$html .= '<input type="radio" name="quick_or_custom" value="custom" '
. ' id="radio_custom_export"';
if ($export_method == 'custom') {
$html .= ' checked="checked"';
}
$html .= ' />';
$html .= '<label for="radio_custom_export">';
$html .= __('Custom - display all possible options');
$html .= '</label>';
$html .= '</li>';
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Selection
*
* @param String $export_type Selected Export Type
* @param String $multi_values Export Options
*
* @return string
*/
function <API key>($export_type, $multi_values)
{
$html = '<div class="exportoptions" id="<API key>">';
if ($export_type == 'server') {
$html .= '<h3>' . __('Database(s):') . '</h3>';
} else if ($export_type == 'database') {
$html .= '<h3>' . __('Table(s):') . '</h3>';
}
if (! empty($multi_values)) {
$html .= $multi_values;
}
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Format
*
* @param array $export_list Export List
*
* @return string
*/
function <API key>($export_list)
{
$html = '<div class="exportoptions" id="format">';
$html .= '<h3>' . __('Format:') . '</h3>';
$html .= PMA_pluginGetChoice('Export', 'what', $export_list, 'format');
$html .= '</div>';
$html .= '<div class="exportoptions" id="<API key>">';
$html .= '<h3>' . __('Format-specific options:') . '</h3>';
$html .= '<p class="no_js_msg" id="<API key>">';
$html .= __(
'Scroll down to fill in the options for the selected format '
. 'and ignore the options for other formats.'
);
$html .= '</p>';
$html .= <API key>('Export', $export_list);
$html .= '</div>';
if (function_exists('<API key>')) {
// Encoding setting form appended by Y.Kawada
// Japanese encoding setting
$html .= '<div class="exportoptions" id="kanji_encoding">';
$html .= '<h3>' . __('Encoding Conversion:') . '</h3>';
$html .= <API key>();
$html .= '</div>';
}
$html .= '<div class="exportoptions" id="submit">';
$html .= PMA_Util::getExternalBug(
__('SQL compatibility mode'), 'mysql', '50027', '14515'
);
global $cfg;
if ($cfg['ExecTimeLimit'] > 0) {
$html .= '<input type="submit" value="' . __('Go')
. '" id="buttonGo" onclick="check_time_out('
. $cfg['ExecTimeLimit'] . ')"/>';
} else {
// if the time limit set is zero, then time out won't occur
// So no need to check for time out.
$html .= '<input type="submit" value="' . __('Go') . '" id="buttonGo" />';
}
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Rows
*
* @param String $db Selected DB
* @param String $table Selected Table
* @param String $unlim_num_rows Num of Rows
*
* @return string
*/
function <API key>($db, $table, $unlim_num_rows)
{
$html = '<div class="exportoptions" id="rows">';
$html .= '<h3>' . __('Rows:') . '</h3>';
$html .= '<ul>';
$html .= '<li>';
$html .= '<input type="radio" name="allrows" value="0" id="radio_allrows_0"';
if (isset($_GET['allrows']) && $_GET['allrows'] == 0) {
$html .= ' checked="checked"';
}
$html .= '/>';
$html .= '<label for ="radio_allrows_0">' . __('Dump some row(s)') . '</label>';
$html .= '<ul>';
$html .= '<li>';
$html .= '<label for="limit_to">' . __('Number of rows:') . '</label>';
$html .= '<input type="text" id="limit_to" name="limit_to" size="5" value="';
if (isset($_GET['limit_to'])) {
$html .= htmlspecialchars($_GET['limit_to']);
} elseif (!empty($unlim_num_rows)) {
$html .= $unlim_num_rows;
} else {
$html .= PMA_Table::countRecords($db, $table);
}
$html .= '" onfocus="this.select()" />';
$html .= '</li>';
$html .= '<li>';
$html .= '<label for="limit_from">' . __('Row to begin at:') . '</label>';
$html .= '<input type="text" id="limit_from" name="limit_from" value="';
if (isset($_GET['limit_from'])) {
$html .= htmlspecialchars($_GET['limit_from']);
} else {
$html .= '0';
}
$html .= '" size="5" onfocus="this.select()" />';
$html .= '</li>';
$html .= '</ul>';
$html .= '</li>';
$html .= '<li>';
$html .= '<input type="radio" name="allrows" value="1" id="radio_allrows_1"';
if (! isset($_GET['allrows']) || $_GET['allrows'] == 1) {
$html .= ' checked="checked"';
}
$html .= '/>';
$html .= ' <label for="radio_allrows_1">' . __('Dump all rows') . '</label>';
$html .= '</li>';
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Quick Export
*
* @return string
*/
function <API key>()
{
global $cfg;
$html = '<div class="exportoptions" id="output_quick_export">';
$html .= '<h3>' . __('Output:') . '</h3>';
$html .= '<ul>';
$html .= '<li>';
$html .= '<input type="checkbox" name="<API key>" value="saveit" ';
$html .= 'id="<API key>" ';
$html .= <API key>('<API key>');
$html .= '/>';
$html .= '<label for="<API key>">';
$html .= sprintf(
__('Save on server in the directory <b>%s</b>'),
htmlspecialchars(PMA_Util::userDir($cfg['SaveDir']))
);
$html .= '</label>';
$html .= '</li>';
$html .= '<li>';
$html .= '<input type="checkbox" name="<API key>" ';
$html .= 'value="saveitover" id="<API key>" ';
$html .= <API key>('<API key>');
$html .= '/>';
$html .= '<label for="<API key>">';
$html .= __('Overwrite existing file(s)');
$html .= '</label>';
$html .= '</li>';
$html .= '</ul>';
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options Save Dir
*
* @return string
*/
function <API key>()
{
global $cfg;
$html = '<li>';
$html .= '<input type="checkbox" name="onserver" value="saveit" ';
$html .= 'id="<API key>" ';
$html .= <API key>('onserver');
$html .= '/>';
$html .= '<label for="<API key>">';
$html .= sprintf(
__('Save on server in the directory <b>%s</b>'),
htmlspecialchars(PMA_Util::userDir($cfg['SaveDir']))
);
$html .= '</label>';
$html .= '</li>';
$html .= '<li>';
$html .= '<input type="checkbox" name="onserverover" value="saveitover"';
$html .= ' id="<API key>" ';
$html .= <API key>('onserver_overwrite');
$html .= '/>';
$html .= '<label for="<API key>">';
$html .= __('Overwrite existing file(s)');
$html .= '</label>';
$html .= '</li>';
return $html;
}
/**
* Prints Html For Export Options
*
* @param String $export_type Selected Export Type
*
* @return string
*/
function <API key>($export_type)
{
$html = '<li>';
$html .= '<label for="filename_template" class="desc">';
$html .= __('File name template:');
$trans = new PMA_Message;
$trans->addMessage(__('@SERVER@ will become the server name'));
if ($export_type == 'database' || $export_type == 'table') {
$trans->addMessage(__(', @DATABASE@ will become the database name'));
if ($export_type == 'table') {
$trans->addMessage(__(', @TABLE@ will become the table name'));
}
}
$msg = new PMA_Message(
__(
'This value is interpreted using %1$sstrftime%2$s, '
. 'so you can use time formatting strings. '
. 'Additionally the following transformations will happen: %3$s. '
. 'Other text will be kept as is. See the %4$sFAQ%5$s for details.'
)
);
$msg->addParam(
'<a href="' . PMA_linkURL(PMA_getPHPDocLink('function.strftime.php'))
. '" target="documentation" title="' . __('Documentation') . '">',
false
);
$msg->addParam('</a>', false);
$msg->addParam($trans);
$doc_url = PMA_Util::getDocuLink('faq', 'faq6-27');
$msg->addParam(
'<a href="' . $doc_url . '" target="documentation">',
false
);
$msg->addParam('</a>', false);
$html .= PMA_Util::showHint($msg);
$html .= '</label>';
$html .= '<input type="text" name="filename_template" id="filename_template" ';
$html .= ' value="';
if (isset($_GET['filename_template'])) {
$html .= htmlspecialchars($_GET['filename_template']);
} else {
if ($export_type == 'database') {
$html .= htmlspecialchars(
$GLOBALS['PMA_Config']->getUserValue(
'<API key>',
$GLOBALS['cfg']['Export']['<API key>']
)
);
} elseif ($export_type == 'table') {
$html .= htmlspecialchars(
$GLOBALS['PMA_Config']->getUserValue(
'<API key>',
$GLOBALS['cfg']['Export']['file_template_table']
)
);
} else {
$html .= htmlspecialchars(
$GLOBALS['PMA_Config']->getUserValue(
'<API key>',
$GLOBALS['cfg']['Export']['<API key>']
)
);
}
}
$html .= '"';
$html .= '/>';
$html .= '<input type="checkbox" name="remember_template" ';
$html .= 'id="<API key>" ';
$html .= <API key>('<API key>');
$html .= '/>';
$html .= '<label for="<API key>">';
$html .= __('use this for future exports');
$html .= '</label>';
$html .= '</li>';
return $html;
}
/**
* Prints Html For Export Options Charset
*
* @return string
*/
function <API key>()
{
global $cfg;
$html = ' <li><label for="<API key>" class="desc">'
. __('Character set of the file:') . '</label>' . "\n";
reset($cfg['AvailableCharsets']);
$html .= '<select id="<API key>" name="charset_of_file" size="1">';
foreach ($cfg['AvailableCharsets'] as $temp_charset) {
$html .= '<option value="' . $temp_charset . '"';
if (isset($_GET['charset_of_file'])
&& ($_GET['charset_of_file'] != $temp_charset)
) {
$html .= '';
} elseif ((empty($cfg['Export']['charset']) && $temp_charset == 'utf-8')
|| $temp_charset == $cfg['Export']['charset']
) {
$html .= ' selected="selected"';
}
$html .= '>' . $temp_charset . '</option>';
} // end foreach
$html .= '</select></li>';
return $html;
}
/**
* Prints Html For Export Options Compression
*
* @return string
*/
function <API key>()
{
global $cfg;
if (isset($_GET['compression'])) {
$<API key> = $_GET['compression'];
} elseif (isset($cfg['Export']['compression'])) {
$<API key> = $cfg['Export']['compression'];
} else {
$<API key> = "none";
}
$html = "";
// zip and gzip encode features
$is_zip = ($cfg['ZipDump'] && @function_exists('gzcompress'));
$is_gzip = ($cfg['GZipDump'] && @function_exists('gzencode'));
if ($is_zip || $is_gzip) {
$html .= '<li>';
$html .= '<label for="compression" class="desc">'
. __('Compression:') . '</label>';
$html .= '<select id="compression" name="compression">';
$html .= '<option value="none">' . __('None') . '</option>';
if ($is_zip) {
$html .= '<option value="zip" ';
if ($<API key> == "zip") {
$html .= 'selected="selected"';
}
$html .= '>' . __('zipped') . '</option>';
}
if ($is_gzip) {
$html .= '<option value="gzip" ';
if ($<API key> == "gzip") {
$html .= 'selected="selected"';
}
$html .= '>' . __('gzipped') . '</option>';
}
$html .= '</select>';
$html .= '</li>';
} else {
$html .= '<input type="hidden" name="compression" value="'
. htmlspecialchars($<API key>) . '" />';
}
return $html;
}
/**
* Prints Html For Export Options Radio
*
* @return string
*/
function <API key>()
{
$html = '<li>';
$html .= '<input type="radio" id="radio_view_as_text" '
. ' name="output_format" value="astext" ';
if (isset($_GET['repopulate']) || $GLOBALS['cfg']['Export']['asfile'] == false) {
$html .= 'checked="checked"';
}
$html .= '/>';
$html .= '<label for="radio_view_as_text">'
. __('View output as text') . '</label></li>';
return $html;
}
/**
* Prints Html For Export Options
*
* @param String $export_type Selected Export Type
*
* @return string
*/
function <API key>($export_type)
{
global $cfg;
$html = '<div class="exportoptions" id="output">';
$html .= '<h3>' . __('Output:') . '</h3>';
$html .= '<ul id="ul_output">';
$html .= '<li><input type="checkbox" id="btn_alias_config" ';
if (isset($_SESSION['tmpval']['aliases'])
&& !PMA_emptyRecursive($_SESSION['tmpval']['aliases'])
) {
$html .= 'checked="checked"';
}
unset($_SESSION['tmpval']['aliases']);
$html .= '/>';
$html .= '<label for="btn_alias_config">';
$html .= __('Rename exported databases/tables/columns');
$html .= '</label></li>';
$html .= '<li>';
$html .= '<input type="radio" name="output_format" value="sendit" ';
$html .= 'id="radio_dump_asfile" ';
if (!isset($_GET['repopulate'])) {
$html .= <API key>('asfile');
}
$html .= '/>';
$html .= '<label for="radio_dump_asfile">'
. __('Save output to a file') . '</label>';
$html .= '<ul id="ul_save_asfile">';
if (isset($cfg['SaveDir']) && !empty($cfg['SaveDir'])) {
$html .= <API key>();
}
$html .= <API key>($export_type);
// charset of file
if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE) {
$html .= <API key>();
} // end if
$html .= <API key>();
$html .= '</ul>';
$html .= '</li>';
$html .= <API key>();
$html .= '</ul>';
/*
* @todo use sprintf() for better translatability, while keeping the
* <label></label> principle (for screen readers)
*/
$html .= '<label for="maxsize">'
. __('Skip tables larger than') . '</label>';
$html .= '<input type="text" id="maxsize" name="maxsize" size="4">' . __('MiB');
$html .= '</div>';
return $html;
}
/**
* Prints Html For Export Options
*
* @param String $export_type Selected Export Type
* @param String $db Selected DB
* @param String $table Selected Table
* @param String $multi_values Export selection
* @param String $num_tables number of tables
* @param array $export_list Export List
* @param String $unlim_num_rows Number of Rows
*
* @return string
*/
function <API key>(
$export_type, $db, $table, $multi_values,
$num_tables, $export_list, $unlim_num_rows
) {
global $cfg;
$html = <API key>($export_type, $db, $table);
$html .= <API key>();
$html .= <API key>($export_type, $multi_values);
$tableLength = /*overload*/mb_strlen($table);
if ($tableLength && empty($num_tables) && ! PMA_Table::isMerge($db, $table)) {
$html .= <API key>($db, $table, $unlim_num_rows);
}
if (isset($cfg['SaveDir']) && !empty($cfg['SaveDir'])) {
$html .= <API key>();
}
$html .= <API key>($db, $table);
$html .= <API key>($export_type);
$html .= <API key>($export_list);
return $html;
}
/**
* Prints Html For Alias Modal Dialog
*
* @param String $db Selected DB
* @param String $table Selected Table
*
* @return string
*/
function <API key>($db = '', $table = '')
{
if (isset($_SESSION['tmpval']['aliases'])) {
$aliases = $_SESSION['tmpval']['aliases'];
}
// In case of server export, the following list of
// databases are not shown in the list.
$dbs_not_allowed = array(
'information_schema',
'performance_schema',
'mysql'
);
// Fetch Columns info
// Server export does not have db set.
$title = __('Rename exported databases/tables/columns');
if (empty($db)) {
$databases = $GLOBALS['dbi']->getColumnsFull(
null, null, null, $GLOBALS['userlink']
);
foreach ($dbs_not_allowed as $db) {
unset($databases[$db]);
}
// Database export does not have table set.
} elseif (empty($table)) {
$tables = $GLOBALS['dbi']->getColumnsFull(
$db, null, null, $GLOBALS['userlink']
);
$databases = array($db => $tables);
// Table export
} else {
$columns = $GLOBALS['dbi']->getColumnsFull(
$db, $table, null, $GLOBALS['userlink']
);
$databases = array(
$db => array(
$table => $columns
)
);
}
$html = '<div id="alias_modal" class="hide" title="' . $title . '">';
$db_html = '<label class="col-2">' . __('Select database') . ': '
. '</label><select id="db_alias_select">';
$table_html = '<label class="col-2">' . __('Select table') . ': </label>';
$first_db = true;
$table_input_html = $db_input_html = '';
foreach ($databases as $db => $tables) {
$val = '';
if (!empty($aliases[$db]['alias'])) {
$val = htmlspecialchars($aliases[$db]['alias']);
}
$db = htmlspecialchars($db);
$name_attr = 'aliases[' . $db . '][alias]';
$id_attr = substr(md5($name_attr), 0, 12);
$class = 'hide';
if ($first_db) {
$first_db = false;
$class = '';
$db_input_html = '<label class="col-2" for="' . $id_attr . '">'
. __('New database name') . ': </label>';
}
$db_input_html .= '<input type="text" name="' . $name_attr . '" '
. 'placeholder="' . $db . ' alias" class="' . $class . '" '
. 'id="' . $id_attr . '" value="' . $val . '"/>';
$db_html .= '<option value="' . $id_attr . '">' . $db . '</option>';
$table_html .= '<span id="' . $id_attr . '_tables" class="' . $class . '">';
$table_html .= '<select id="' . $id_attr . '_tables_select" '
. 'class="table_alias_select">';
$first_tbl = true;
$col_html = '';
foreach ($tables as $table => $columns) {
$val = '';
if (!empty($aliases[$db]['tables'][$table]['alias'])) {
$val = htmlspecialchars($aliases[$db]['tables'][$table]['alias']);
}
$table = htmlspecialchars($table);
$name_attr = 'aliases[' . $db . '][tables][' . $table . '][alias]';
$id_attr = substr(md5($name_attr), 0, 12);
$class = 'hide';
if ($first_tbl) {
$first_tbl = false;
$class = '';
$table_input_html = '<label class="col-2" for="' . $id_attr . '">'
. __('New table name') . ': </label>';
}
$table_input_html .= '<input type="text" value="' . $val . '" '
. 'name="' . $name_attr . '" id="' . $id_attr . '" '
. 'placeholder="' . $table . ' alias" class="' . $class . '"/>';
$table_html .= '<option value="' . $id_attr . '">'
. $table . '</option>';
$col_html .= '<table id="' . $id_attr . '_cols" class="'
. $class . '" width="100%">';
$col_html .= '<thead><tr><th>' . __('Old column name') . '</th>'
. '<th>' . __('New column name') . '</th></tr></thead><tbody>';
$class = 'odd';
foreach ($columns as $column => $col_def) {
$val = '';
if (!empty($aliases[$db]['tables'][$table]['columns'][$column])) {
$val = htmlspecialchars(
$aliases[$db]['tables'][$table]['columns'][$column]
);
}
$column = htmlspecialchars($column);
$name_attr = 'aliases[' . $db . '][tables][' . $table
. '][columns][' . $column . ']';
$id_attr = substr(md5($name_attr), 0, 12);
$col_html .= '<tr class="' . $class . '">';
$col_html .= '<th><label for="' . $id_attr . '">' . $column
. '</label></th>';
$col_html .= '<td><dummy_inp type="text" name="' . $name_attr . '" '
. 'id="' . $id_attr . '" placeholder="'
. $column . ' alias" value="' . $val . '"></dummy_inp></td>';
$col_html .= '</tr>';
$class = $class === 'odd' ? 'even' : 'odd';
}
$col_html .= '</tbody></table>';
}
$table_html .= '</select>';
$table_html .= $table_input_html . '<hr/>' . $col_html . '</span>';
}
$db_html .= '</select>';
$html .= $db_html;
$html .= $db_input_html . '<hr/>';
$html .= $table_html;
$html .= '</div>';
return $html;
}
?> |
#include "sysemu/char.h"
#include "hw/hw.h"
#include "hw/arm/omap.h"
#include "hw/char/serial.h"
#include "exec/address-spaces.h"
/* UARTs */
struct omap_uart_s {
MemoryRegion iomem;
hwaddr base;
SerialState *serial; /* TODO */
struct omap_target_agent_s *ta;
omap_clk fclk;
qemu_irq irq;
uint8_t eblr;
uint8_t syscontrol;
uint8_t wkup;
uint8_t cfps;
uint8_t mdr[2];
uint8_t scr;
uint8_t clksel;
};
void omap_uart_reset(struct omap_uart_s *s)
{
s->eblr = 0x00;
s->syscontrol = 0;
s->wkup = 0x3f;
s->cfps = 0x69;
s->clksel = 0;
}
struct omap_uart_s *omap_uart_init(hwaddr base,
qemu_irq irq, omap_clk fclk, omap_clk iclk,
qemu_irq txdma, qemu_irq rxdma,
const char *label, CharDriverState *chr)
{
struct omap_uart_s *s = (struct omap_uart_s *)
g_malloc0(sizeof(struct omap_uart_s));
s->base = base;
s->fclk = fclk;
s->irq = irq;
s->serial = serial_mm_init(get_system_memory(), base, 2, irq,
omap_clk_getrate(fclk)/16,
chr ?: qemu_chr_new(label, "null", NULL),
<API key>);
return s;
}
static uint64_t omap_uart_read(void *opaque, hwaddr addr,
unsigned size)
{
struct omap_uart_s *s = (struct omap_uart_s *) opaque;
if (size == 4) {
return omap_badwidth_read8(opaque, addr);
}
switch (addr) {
case 0x20: /* MDR1 */
return s->mdr[0];
case 0x24: /* MDR2 */
return s->mdr[1];
case 0x40: /* SCR */
return s->scr;
case 0x44: /* SSR */
return 0x0;
case 0x48: /* EBLR (OMAP2) */
return s->eblr;
case 0x4C: /* OSC_12M_SEL (OMAP1) */
return s->clksel;
case 0x50: /* MVR */
return 0x30;
case 0x54: /* SYSC (OMAP2) */
return s->syscontrol;
case 0x58: /* SYSS (OMAP2) */
return 1;
case 0x5c: /* WER (OMAP2) */
return s->wkup;
case 0x60: /* CFPS (OMAP2) */
return s->cfps;
}
OMAP_BAD_REG(addr);
return 0;
}
static void omap_uart_write(void *opaque, hwaddr addr,
uint64_t value, unsigned size)
{
struct omap_uart_s *s = (struct omap_uart_s *) opaque;
if (size == 4) {
<API key>(opaque, addr, value);
return;
}
switch (addr) {
case 0x20: /* MDR1 */
s->mdr[0] = value & 0x7f;
break;
case 0x24: /* MDR2 */
s->mdr[1] = value & 0xff;
break;
case 0x40: /* SCR */
s->scr = value & 0xff;
break;
case 0x48: /* EBLR (OMAP2) */
s->eblr = value & 0xff;
break;
case 0x4C: /* OSC_12M_SEL (OMAP1) */
s->clksel = value & 1;
break;
case 0x44: /* SSR */
case 0x50: /* MVR */
case 0x58: /* SYSS (OMAP2) */
OMAP_RO_REG(addr);
break;
case 0x54: /* SYSC (OMAP2) */
s->syscontrol = value & 0x1d;
if (value & 2)
omap_uart_reset(s);
break;
case 0x5c: /* WER (OMAP2) */
s->wkup = value & 0x7f;
break;
case 0x60: /* CFPS (OMAP2) */
s->cfps = value & 0xff;
break;
default:
OMAP_BAD_REG(addr);
}
}
static const MemoryRegionOps omap_uart_ops = {
.read = omap_uart_read,
.write = omap_uart_write,
.endianness = <API key>,
};
struct omap_uart_s *omap2_uart_init(MemoryRegion *sysmem,
struct omap_target_agent_s *ta,
qemu_irq irq, omap_clk fclk, omap_clk iclk,
qemu_irq txdma, qemu_irq rxdma,
const char *label, CharDriverState *chr)
{
hwaddr base = omap_l4_attach(ta, 0, NULL);
struct omap_uart_s *s = omap_uart_init(base, irq,
fclk, iclk, txdma, rxdma, label, chr);
<API key>(&s->iomem, NULL, &omap_uart_ops, s, "omap.uart", 0x100);
s->ta = ta;
<API key>(sysmem, base + 0x20, &s->iomem);
return s;
}
void omap_uart_attach(struct omap_uart_s *s, CharDriverState *chr)
{
/* TODO: Should reuse or destroy current s->serial */
s->serial = serial_mm_init(get_system_memory(), s->base, 2, s->irq,
omap_clk_getrate(s->fclk) / 16,
chr ?: qemu_chr_new("null", "null", NULL),
<API key>);
} |
<?php
/**
* @see <API key>
*/
require_once 'Zend/Service/DeveloperGarden/Response/ConferenceCall/<API key>.php';
class <API key>
extends <API key>
{
/**
* response data
*
* @var Zend_Service_DeveloperGarden_Response_ConferenceCall_CreateConferenceResponseType
*/
public $<API key> = null;
} |
using System;
using System.Collections;
using Server.Items;
using Server.ContextMenus;
using Server.Misc;
using Server.Network;
namespace Server.Mobiles
{
public class Executioner : BaseCreature
{
[Constructable]
public Executioner() : base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
SpeechHue = Utility.RandomDyedHue();
Title = "the executioner";
Hue = Utility.RandomSkinHue();
if ( this.Female = Utility.RandomBool() )
{
this.Body = 0x191;
this.Name = NameList.RandomName( "female" );
AddItem( new Skirt( Utility.RandomRedHue() ) );
}
else
{
this.Body = 0x190;
this.Name = NameList.RandomName( "male" );
AddItem( new ShortPants( Utility.RandomRedHue() ) );
}
SetStr( 386, 400 );
SetDex( 151, 165 );
SetInt( 161, 175 );
SetDamage( 8, 10 );
SetDamageType( ResistanceType.Physical, 100 );
SetResistance( ResistanceType.Physical, 35, 45 );
SetResistance( ResistanceType.Fire, 25, 30 );
SetResistance( ResistanceType.Cold, 25, 30 );
SetResistance( ResistanceType.Poison, 10, 20 );
SetResistance( ResistanceType.Energy, 10, 20 );
SetSkill( SkillName.Anatomy, 125.0 );
SetSkill( SkillName.Fencing, 46.0, 77.5 );
SetSkill( SkillName.Macing, 35.0, 57.5 );
SetSkill( SkillName.Poisoning, 60.0, 82.5 );
SetSkill( SkillName.MagicResist, 83.5, 92.5 );
SetSkill( SkillName.Swords, 125.0 );
SetSkill( SkillName.Tactics, 125.0 );
SetSkill( SkillName.Lumberjacking, 125.0 );
Fame = 5000;
Karma = -5000;
VirtualArmor = 40;
AddItem( new ThighBoots( Utility.RandomRedHue() ) );
AddItem( new Surcoat( Utility.RandomRedHue() ) );
AddItem( new ExecutionersAxe());
Utility.AssignRandomHair( this );
}
public override void GenerateLoot()
{
AddLoot( LootPack.FilthyRich );
AddLoot( LootPack.Meager );
}
public override bool AlwaysMurderer{ get{ return true; } }
public Executioner( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} |
docs = presence_profile.xml
docbook_dir = ../../../docbook
include $(docbook_dir)/Makefile.module |
/* -*- buffer-read-only: t -*- vi: set ro: */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Written by Bruno Haible <bruno@clisp.org>, 2008. */
#include <config.h>
#include <errno.h>
/* Verify that the POSIX mandated errno values exist and can be used as
initializers outside of a function.
The variable names happen to match the Linux/x86 error numbers. */
int e1 = EPERM;
int e2 = ENOENT;
int e3 = ESRCH;
int e4 = EINTR;
int e5 = EIO;
int e6 = ENXIO;
int e7 = E2BIG;
int e8 = ENOEXEC;
int e9 = EBADF;
int e10 = ECHILD;
int e11 = EAGAIN;
int e11a = EWOULDBLOCK;
int e12 = ENOMEM;
int e13 = EACCES;
int e14 = EFAULT;
int e16 = EBUSY;
int e17 = EEXIST;
int e18 = EXDEV;
int e19 = ENODEV;
int e20 = ENOTDIR;
int e21 = EISDIR;
int e22 = EINVAL;
int e23 = ENFILE;
int e24 = EMFILE;
int e25 = ENOTTY;
int e26 = ETXTBSY;
int e27 = EFBIG;
int e28 = ENOSPC;
int e29 = ESPIPE;
int e30 = EROFS;
int e31 = EMLINK;
int e32 = EPIPE;
int e33 = EDOM;
int e34 = ERANGE;
int e35 = EDEADLK;
int e36 = ENAMETOOLONG;
int e37 = ENOLCK;
int e38 = ENOSYS;
int e39 = ENOTEMPTY;
int e40 = ELOOP;
int e42 = ENOMSG;
int e43 = EIDRM;
int e67 = ENOLINK;
int e71 = EPROTO;
int e72 = EMULTIHOP;
int e74 = EBADMSG;
int e75 = EOVERFLOW;
int e84 = EILSEQ;
int e88 = ENOTSOCK;
int e89 = EDESTADDRREQ;
int e90 = EMSGSIZE;
int e91 = EPROTOTYPE;
int e92 = ENOPROTOOPT;
int e93 = EPROTONOSUPPORT;
int e95 = EOPNOTSUPP;
int e95a = ENOTSUP;
int e97 = EAFNOSUPPORT;
int e98 = EADDRINUSE;
int e99 = EADDRNOTAVAIL;
int e100 = ENETDOWN;
int e101 = ENETUNREACH;
int e102 = ENETRESET;
int e103 = ECONNABORTED;
int e104 = ECONNRESET;
int e105 = ENOBUFS;
int e106 = EISCONN;
int e107 = ENOTCONN;
int e110 = ETIMEDOUT;
int e111 = ECONNREFUSED;
int e113 = EHOSTUNREACH;
int e114 = EALREADY;
int e115 = EINPROGRESS;
int e116 = ESTALE;
int e122 = EDQUOT;
int e125 = ECANCELED;
/* Don't verify that these errno values are all different, except for possibly
EWOULDBLOCK == EAGAIN. Even Linux/x86 does not pass this check: it has
ENOTSUP == EOPNOTSUPP. */
int
main ()
{
/* Verify that errno can be assigned. */
errno = EOVERFLOW;
/* snprintf() callers want to distinguish EINVAL and EOVERFLOW. */
if (errno == EINVAL)
return 1;
return 0;
} |
<?php
/**
* @see <API key>
*/
require_once 'Zend/Validate/Barcode/AdapterAbstract.php';
class <API key> extends <API key>
{
/**
* Allowed barcode lengths
* @var integer
*/
protected $_length = 13;
/**
* Allowed barcode characters
* @var string
*/
protected $_characters = '0123456789';
/**
* Checksum function
* @var string
*/
protected $_checksum = '_gtin';
} |
<?php // $Id: openhive.php,v 1.6 2007/01/08 19:34:19 skodak Exp $
require_once("../../../../../config.php");
if (empty($CFG->hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) {
print_header();
notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.');
print_footer();
die;
}
if (empty($SESSION->HIVE_SESSION)) {
print_header();
notify('You do not have access to the Hive repository. Moodle signs you into Hive when you log in. This process may have failed.');
close_window_button();
print_footer();
die;
}
$query .= 'HISTORY=';
$query .= '&hiveLanguage=en_AU';
$query .= '&PUBCATEGORY_LIST=';
$query .= '&CATEGORY_LIST=';
$query .= '&HIDE_LOGOUT=Y';
$query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php';
$query .= '&<API key>=Y';
$query .= '&HIVE_RET=ORG';
$query .= '&HIVE_PAGE=Lite%20Browse';
$query .= '&HIVE_REQ=2113';
$query .= '&HIVE_ERRCODE=0';
$query .= '&mklms=Doodle';
$query .= '&HIVE_PROD=0';
$query .= '&<API key>='.$CFG->decsbureauid;
$query .= '&HIVE_REF=hin:hive@Hive%20Login%20HTML%20Template';
$query .= '&HIVE_LITEMODE=liteBrowse';
$query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php';
$query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION;
redirect($CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath .'?'.$query);
?> |
import unittest
import os
SAMPLE_FILE = os.path.join(os.path.dirname(__file__), 'sample1.ogg')
SAMPLE_LENGTH = 1.402
SAMPLE_LENGTH_MIN = SAMPLE_LENGTH * 0.99
SAMPLE_LENGTH_MAX = SAMPLE_LENGTH * 1.01
class AudioTestCase(unittest.TestCase):
def get_sound(self):
import os
assert os.path.exists(SAMPLE_FILE)
from kivy.core import audio
return audio.SoundLoader.load(SAMPLE_FILE)
def test_length_simple(self):
sound = self.get_sound()
volume = sound.volume = 0.75
length = sound.length
assert SAMPLE_LENGTH_MIN <= length <= SAMPLE_LENGTH_MAX
# ensure that the gstreamer play/stop doesn't mess up the volume
assert volume == sound.volume
def test_length_playing(self):
import time
sound = self.get_sound()
sound.play()
try:
time.sleep(0.1)
length = sound.length
assert SAMPLE_LENGTH_MIN <= length <= SAMPLE_LENGTH_MAX
finally:
sound.stop()
def test_length_stopped(self):
import time
sound = self.get_sound()
sound.play()
try:
time.sleep(0.1)
finally:
sound.stop()
length = sound.length
assert SAMPLE_LENGTH_MIN <= length <= SAMPLE_LENGTH_MAX
class <API key>(AudioTestCase):
def make_sound(self, source):
from kivy.core.audio import audio_gstreamer
return audio_gstreamer.SoundGstreamer(source)
class AudioPygameTestCase(AudioTestCase):
def make_sound(self, source):
from kivy.core.audio import audio_pygame
return audio_pygame.SoundPygame(source) |
! { dg-do run }
!
! PR fortran/19107
! -fwhole-file flag added for PR fortran/44945
!
! This test the fix of PR19107, where character array actual
! arguments in derived type constructors caused an ICE.
! It also checks that the scalar counterparts are OK.
! Contributed by Paul Thomas pault@gcc.gnu.org
!
MODULE global
TYPE :: dt
CHARACTER(4) a
CHARACTER(4) b(2)
END TYPE
TYPE (dt), DIMENSION(:), ALLOCATABLE, SAVE :: c
END MODULE global
program <API key>
USE global
call alloc (2)
if ((any (c%a /= "wxyz")) .OR. &
(any (c%b(1) /= "abcd")) .OR. &
(any (c%b(2) /= "efgh"))) STOP 1
contains
SUBROUTINE alloc (n)
USE global
ALLOCATE (c(n), STAT=IALLOC_FLAG)
DO i = 1,n
c (i) = dt ("wxyz",(/"abcd","efgh"/))
ENDDO
end subroutine alloc
END program <API key> |
// Use of this source code is governed by a BSD-style
package zlib
import (
"bytes"
"fmt"
"internal/testenv"
"io"
"os"
"testing"
)
var filenames = []string{
"../testdata/gettysburg.txt",
"../testdata/e.txt",
"../testdata/pi.txt",
}
var data = []string{
"test a reasonable sized string that can be compressed",
}
// Tests that compressing and then decompressing the given file at the given compression level and dictionary
// yields equivalent bytes to the original file.
func testFileLevelDict(t *testing.T, fn string, level int, d string) {
// Read the file, as golden output.
golden, err := os.Open(fn)
if err != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err)
return
}
defer golden.Close()
b0, err0 := io.ReadAll(golden)
if err0 != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err0)
return
}
testLevelDict(t, fn, b0, level, d)
}
func testLevelDict(t *testing.T, fn string, b0 []byte, level int, d string) {
// Make dictionary, if given.
var dict []byte
if d != "" {
dict = []byte(d)
}
// Push data through a pipe that compresses at the write end, and decompresses at the read end.
piper, pipew := io.Pipe()
defer piper.Close()
go func() {
defer pipew.Close()
zlibw, err := NewWriterLevelDict(pipew, level, dict)
if err != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err)
return
}
defer zlibw.Close()
_, err = zlibw.Write(b0)
if err != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err)
return
}
}()
zlibr, err := NewReaderDict(piper, dict)
if err != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err)
return
}
defer zlibr.Close()
// Compare the decompressed data.
b1, err1 := io.ReadAll(zlibr)
if err1 != nil {
t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err1)
return
}
if len(b0) != len(b1) {
t.Errorf("%s (level=%d, dict=%q): length mismatch %d versus %d", fn, level, d, len(b0), len(b1))
return
}
for i := 0; i < len(b0); i++ {
if b0[i] != b1[i] {
t.Errorf("%s (level=%d, dict=%q): mismatch at %d, 0x%02x versus 0x%02x\n", fn, level, d, i, b0[i], b1[i])
return
}
}
}
func <API key>(t *testing.T, fn string, level int, dict []byte) {
var b0 []byte
var err error
if fn != "" {
b0, err = os.ReadFile(fn)
if err != nil {
t.Errorf("%s (level=%d): %v", fn, level, err)
return
}
}
// Compress once.
buf := new(bytes.Buffer)
var zlibw *Writer
if dict == nil {
zlibw, err = NewWriterLevel(buf, level)
} else {
zlibw, err = NewWriterLevelDict(buf, level, dict)
}
if err == nil {
_, err = zlibw.Write(b0)
}
if err == nil {
err = zlibw.Close()
}
if err != nil {
t.Errorf("%s (level=%d): %v", fn, level, err)
return
}
out := buf.String()
// Reset and compress again.
buf2 := new(bytes.Buffer)
zlibw.Reset(buf2)
_, err = zlibw.Write(b0)
if err == nil {
err = zlibw.Close()
}
if err != nil {
t.Errorf("%s (level=%d): %v", fn, level, err)
return
}
out2 := buf2.String()
if out2 != out {
t.Errorf("%s (level=%d): different output after reset (got %d bytes, expected %d",
fn, level, len(out2), len(out))
}
}
func TestWriter(t *testing.T) {
for i, s := range data {
b := []byte(s)
tag := fmt.Sprintf("#%d", i)
testLevelDict(t, tag, b, DefaultCompression, "")
testLevelDict(t, tag, b, NoCompression, "")
testLevelDict(t, tag, b, HuffmanOnly, "")
for level := BestSpeed; level <= BestCompression; level++ {
testLevelDict(t, tag, b, level, "")
}
}
}
func TestWriterBig(t *testing.T) {
for i, fn := range filenames {
testFileLevelDict(t, fn, DefaultCompression, "")
testFileLevelDict(t, fn, NoCompression, "")
testFileLevelDict(t, fn, HuffmanOnly, "")
for level := BestSpeed; level <= BestCompression; level++ {
testFileLevelDict(t, fn, level, "")
if level >= 1 && testing.Short() && testenv.Builder() == "" {
break
}
}
if i == 0 && testing.Short() && testenv.Builder() == "" {
break
}
}
}
func TestWriterDict(t *testing.T) {
const dictionary = "0123456789."
for i, fn := range filenames {
testFileLevelDict(t, fn, DefaultCompression, dictionary)
testFileLevelDict(t, fn, NoCompression, dictionary)
testFileLevelDict(t, fn, HuffmanOnly, dictionary)
for level := BestSpeed; level <= BestCompression; level++ {
testFileLevelDict(t, fn, level, dictionary)
if level >= 1 && testing.Short() && testenv.Builder() == "" {
break
}
}
if i == 0 && testing.Short() && testenv.Builder() == "" {
break
}
}
}
func TestWriterReset(t *testing.T) {
const dictionary = "0123456789."
for _, fn := range filenames {
<API key>(t, fn, NoCompression, nil)
<API key>(t, fn, DefaultCompression, nil)
<API key>(t, fn, HuffmanOnly, nil)
<API key>(t, fn, NoCompression, []byte(dictionary))
<API key>(t, fn, DefaultCompression, []byte(dictionary))
<API key>(t, fn, HuffmanOnly, []byte(dictionary))
if testing.Short() {
break
}
for level := BestSpeed; level <= BestCompression; level++ {
<API key>(t, fn, level, nil)
}
}
}
func <API key>(t *testing.T) {
var input = []byte("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
var buf bytes.Buffer
compressor, err := NewWriterLevelDict(&buf, BestCompression, input)
if err != nil {
t.Errorf("error in NewWriterLevelDict: %s", err)
return
}
compressor.Write(input)
compressor.Close()
const expectedMaxSize = 25
output := buf.Bytes()
if len(output) > expectedMaxSize {
t.Errorf("result too large (got %d, want <= %d bytes). Is the dictionary being used?", len(output), expectedMaxSize)
}
} |
#include <linux/module.h>
#include <linux/serial.h>
#include <linux/serial_core.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/dma-mapping.h>
#include <linux/dmapool.h>
#include <linux/wait.h>
#include <linux/sysfs.h>
#include <linux/stat.h>
#include <linux/device.h>
#include <linux/wakelock.h>
#include <linux/debugfs.h>
#include <asm/atomic.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <mach/hardware.h>
#include <mach/dma.h>
#include <mach/msm_serial_hs.h>
#include "msm_serial_hs_hwreg.h"
#ifdef CONFIG_BT_CSR_7820
#define ALRAN
#endif
#ifdef ALRAN
#include <linux/sched.h>
#define MAX_KERNEL_IRQ_LOGS (2000)
struct ScheduleLogData {
ktime_t time;
unsigned int unPid;
unsigned long isr_status;
unsigned long sr_status;
};
static struct ScheduleLogData pHSLogData[MAX_KERNEL_IRQ_LOGS];
static int nNextLogIdx;
#endif
static int <API key> = 1;
module_param_named(debug_mask, <API key>,
int, S_IRUGO | S_IWUSR | S_IWGRP);
enum flush_reason {
FLUSH_NONE,
FLUSH_DATA_READY,
FLUSH_DATA_INVALID, /* values after this indicate invalid data */
FLUSH_IGNORE = FLUSH_DATA_INVALID,
FLUSH_STOP,
FLUSH_SHUTDOWN,
};
enum msm_hs_clk_states_e {
MSM_HS_CLK_PORT_OFF, /* port not in use */
MSM_HS_CLK_OFF, /* clock disabled */
<API key>, /* disable after TX and RX flushed */
MSM_HS_CLK_ON, /* clock enabled */
};
/* Track the forced RXSTALE flush during clock off sequence.
* These states are only valid during <API key> */
enum <API key> {
CLK_REQ_OFF_START,
<API key>,
<API key>,
<API key>,
};
struct msm_hs_tx {
unsigned int tx_ready_int_en; /* ok to dma more tx */
unsigned int dma_in_flight; /* tx dma in progress */
struct msm_dmov_cmd xfer;
dmov_box *command_ptr;
u32 *command_ptr_ptr;
dma_addr_t mapped_cmd_ptr;
dma_addr_t mapped_cmd_ptr_ptr;
int tx_count;
dma_addr_t dma_base;
struct tasklet_struct tlet;
};
struct msm_hs_rx {
enum flush_reason flush;
struct msm_dmov_cmd xfer;
dma_addr_t cmdptr_dmaaddr;
dmov_box *command_ptr;
u32 *command_ptr_ptr;
dma_addr_t mapped_cmd_ptr;
wait_queue_head_t wait;
dma_addr_t rbuffer;
unsigned char *buffer;
unsigned int buffer_pending;
struct dma_pool *pool;
struct wake_lock wake_lock;
struct delayed_work flip_insert_work;
struct tasklet_struct tlet;
};
enum buffer_states {
NONE_PENDING = 0x0,
FIFO_OVERRUN = 0x1,
PARITY_ERROR = 0x2,
CHARS_NORMAL = 0x4,
};
/* optional low power wakeup, typically on a GPIO RX irq */
struct msm_hs_wakeup {
int irq; /* < 0 indicates low power wakeup disabled */
unsigned char ignore; /* bool */
/* bool: inject char into rx tty on wakeup */
unsigned char inject_rx;
char rx_to_inject;
};
struct msm_hs_port {
struct uart_port uport;
unsigned long imr_reg; /* shadow value of UARTDM_IMR */
struct clk *clk;
struct clk *pclk;
struct msm_hs_tx tx;
struct msm_hs_rx rx;
/* gsbi uarts have to do additional writes to gsbi memory */
/* block and top control status block. The following pointers */
/* keep a handle to these blocks. */
unsigned char __iomem *mapped_gsbi;
int dma_tx_channel;
int dma_rx_channel;
int dma_tx_crci;
int dma_rx_crci;
struct hrtimer clk_off_timer; /* to poll TXEMT before clock off */
ktime_t clk_off_delay;
#ifdef ALRAN
struct hrtimer qtest_timer; /* test force clock on & off */
ktime_t qtest_delay;
#endif
enum msm_hs_clk_states_e clk_state;
enum <API key> clk_req_off_state;
struct msm_hs_wakeup wakeup;
struct wake_lock dma_wake_lock; /* held while any DMA active */
};
#define <API key> 16 /* DM burst size (in bytes) */
#define UARTDM_TX_BUF_SIZE UART_XMIT_SIZE
#define UARTDM_RX_BUF_SIZE 512
#define RETRY_TIMEOUT 5
#define UARTDM_NR 2
static struct dentry *debug_base;
static struct msm_hs_port q_uart_port[UARTDM_NR];
static struct platform_driver <API key>;
static struct uart_driver msm_hs_driver;
static struct uart_ops msm_hs_ops;
#define UARTDM_TO_MSM(uart_port) \
container_of((uart_port), struct msm_hs_port, uport)
static ssize_t show_clock(struct device *dev, struct device_attribute *attr,
char *buf)
{
int state = 1;
enum msm_hs_clk_states_e clk_state;
unsigned long flags;
struct platform_device *pdev = container_of(dev, struct
platform_device, dev);
struct msm_hs_port *msm_uport = &q_uart_port[pdev->id];
spin_lock_irqsave(&msm_uport->uport.lock, flags);
clk_state = msm_uport->clk_state;
<API key>(&msm_uport->uport.lock, flags);
if (clk_state <= MSM_HS_CLK_OFF)
state = 0;
return snprintf(buf, PAGE_SIZE, "%d\n", state);
}
static ssize_t set_clock(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int state;
struct platform_device *pdev = container_of(dev, struct
platform_device, dev);
struct msm_hs_port *msm_uport = &q_uart_port[pdev->id];
state = buf[0] - '0';
switch (state) {
case 0: {
<API key>(&msm_uport->uport);
break;
}
case 1: {
<API key>(&msm_uport->uport);
break;
}
default: {
return -EINVAL;
}
}
return count;
}
static DEVICE_ATTR(clock, S_IWUSR | S_IRUGO, show_clock, set_clock);
static inline unsigned int <API key>(struct msm_hs_port *msm_uport)
{
return (msm_uport->wakeup.irq > 0);
}
static inline int is_gsbi_uart(struct msm_hs_port *msm_uport)
{
/* assume gsbi uart if gsbi resource found in pdata */
return ((msm_uport->mapped_gsbi != NULL));
}
static inline unsigned int msm_hs_read(struct uart_port *uport,
unsigned int offset)
{
return readl_relaxed(uport->membase + offset);
}
static inline void msm_hs_write(struct uart_port *uport, unsigned int offset,
unsigned int value)
{
writel_relaxed(value, uport->membase + offset);
}
static void msm_hs_release_port(struct uart_port *port)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(port);
struct platform_device *pdev = to_platform_device(port->dev);
struct resource *gsbi_resource;
resource_size_t size;
if (is_gsbi_uart(msm_uport)) {
iowrite32(GSBI_PROTOCOL_IDLE, msm_uport->mapped_gsbi +
GSBI_CONTROL_ADDR);
gsbi_resource = <API key>(pdev,
IORESOURCE_MEM,
"gsbi_resource");
if (unlikely(!gsbi_resource))
return;
size = resource_size(gsbi_resource);
release_mem_region(gsbi_resource->start, size);
iounmap(msm_uport->mapped_gsbi);
msm_uport->mapped_gsbi = NULL;
}
}
static int msm_hs_request_port(struct uart_port *port)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(port);
struct platform_device *pdev = to_platform_device(port->dev);
struct resource *gsbi_resource;
resource_size_t size;
gsbi_resource = <API key>(pdev,
IORESOURCE_MEM,
"gsbi_resource");
if (gsbi_resource) {
size = resource_size(gsbi_resource);
if (unlikely(!request_mem_region(gsbi_resource->start, size,
"msm_serial_hs")))
return -EBUSY;
msm_uport->mapped_gsbi = ioremap(gsbi_resource->start,
size);
if (!msm_uport->mapped_gsbi) {
release_mem_region(gsbi_resource->start, size);
return -EBUSY;
}
}
/* no gsbi uart */
return 0;
}
static int <API key>(void *data, u64 val)
{
struct msm_hs_port *msm_uport = data;
struct uart_port *uport = &(msm_uport->uport);
unsigned long flags;
int ret = 0;
clk_enable(msm_uport->clk);
if (msm_uport->pclk)
clk_enable(msm_uport->pclk);
if (val) {
spin_lock_irqsave(&uport->lock, flags);
ret = msm_hs_read(uport, UARTDM_MR2_ADDR);
ret |= <API key>;
msm_hs_write(uport, UARTDM_MR2_ADDR, ret);
<API key>(&uport->lock, flags);
} else {
spin_lock_irqsave(&uport->lock, flags);
ret = msm_hs_read(uport, UARTDM_MR2_ADDR);
ret &= ~<API key>;
msm_hs_write(uport, UARTDM_MR2_ADDR, ret);
<API key>(&uport->lock, flags);
}
/* Calling CLOCK API. Hence mb() requires here. */
mb();
clk_disable(msm_uport->clk);
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
return 0;
}
static int <API key>(void *data, u64 *val)
{
struct msm_hs_port *msm_uport = data;
struct uart_port *uport = &(msm_uport->uport);
unsigned long flags;
int ret = 0;
clk_enable(msm_uport->clk);
if (msm_uport->pclk)
clk_enable(msm_uport->pclk);
spin_lock_irqsave(&uport->lock, flags);
ret = msm_hs_read(&msm_uport->uport, UARTDM_MR2_ADDR);
<API key>(&uport->lock, flags);
clk_disable(msm_uport->clk);
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
*val = (ret & <API key>) ? 1 : 0;
return 0;
}
<API key>(<API key>, <API key>,
<API key>, "%llu\n");
/*
* msm_serial_hs debugfs node: <debugfs_root>/msm_serial_hs/loopback.<id>
* writing 1 turns on internal loopback mode in HW. Useful for automation
* test scripts.
* writing 0 disables the internal loopback mode. Default is disabled.
*/
static void __init <API key>(struct msm_hs_port *msm_uport,
int id)
{
char node_name[15];
snprintf(node_name, sizeof(node_name), "loopback.%d", id);
if (IS_ERR_OR_NULL(debugfs_create_file(node_name,
S_IRUGO | S_IWUSR,
debug_base,
msm_uport,
&<API key>))) {
<API key>(debug_base);
}
}
static int __devexit msm_hs_remove(struct platform_device *pdev)
{
struct msm_hs_port *msm_uport;
struct device *dev;
struct <API key> *pdata = pdev->dev.platform_data;
if (pdev->id < 0 || pdev->id >= UARTDM_NR) {
printk(KERN_ERR "Invalid plaform device ID = %d\n", pdev->id);
return -EINVAL;
}
msm_uport = &q_uart_port[pdev->id];
dev = msm_uport->uport.dev;
if (pdata && pdata->gpio_config)
if (pdata->gpio_config(0))
dev_err(dev, "GPIO config error\n");
sysfs_remove_file(&pdev->dev.kobj, &dev_attr_clock.attr);
<API key>(debug_base);
dma_unmap_single(dev, msm_uport->rx.mapped_cmd_ptr, sizeof(dmov_box),
DMA_TO_DEVICE);
dma_pool_free(msm_uport->rx.pool, msm_uport->rx.buffer,
msm_uport->rx.rbuffer);
dma_pool_destroy(msm_uport->rx.pool);
dma_unmap_single(dev, msm_uport->rx.cmdptr_dmaaddr, sizeof(u32),
DMA_TO_DEVICE);
dma_unmap_single(dev, msm_uport->tx.mapped_cmd_ptr_ptr, sizeof(u32),
DMA_TO_DEVICE);
dma_unmap_single(dev, msm_uport->tx.mapped_cmd_ptr, sizeof(dmov_box),
DMA_TO_DEVICE);
wake_lock_destroy(&msm_uport->rx.wake_lock);
wake_lock_destroy(&msm_uport->dma_wake_lock);
<API key>(&msm_hs_driver, &msm_uport->uport);
clk_put(msm_uport->clk);
/* Free the tx resources */
kfree(msm_uport->tx.command_ptr);
kfree(msm_uport->tx.command_ptr_ptr);
/* Free the rx resources */
kfree(msm_uport->rx.command_ptr);
kfree(msm_uport->rx.command_ptr_ptr);
iounmap(msm_uport->uport.membase);
return 0;
}
static int msm_hs_init_clk(struct uart_port *uport)
{
int ret;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
wake_lock(&msm_uport->dma_wake_lock);
/* Set up the MREG/NREG/DREG/MNDREG */
ret = clk_set_rate(msm_uport->clk, uport->uartclk);
if (ret) {
printk(KERN_WARNING "Error setting clock rate on UART\n");
return ret;
}
ret = clk_enable(msm_uport->clk);
if (ret) {
printk(KERN_ERR "Error could not turn on UART clk\n");
return ret;
}
if (msm_uport->pclk) {
ret = clk_enable(msm_uport->pclk);
if (ret) {
dev_err(uport->dev,
"Error could not turn on UART pclk\n");
return ret;
}
}
msm_uport->clk_state = MSM_HS_CLK_ON;
return 0;
}
/*
* programs the UARTDM_CSR register with correct bit rates
*
* Interrupts should be disabled before we are called, as
* we modify Set Baud rate
* Set receive stale interrupt level, dependant on Bit Rate
* Goal is to have around 8 ms before indicate stale.
* roundup (((Bit Rate * .008) / 10) + 1
*/
static void <API key>(struct uart_port *uport,
unsigned int bps)
{
unsigned long rxstale;
unsigned long data;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
switch (bps) {
case 300:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x00);
rxstale = 1;
break;
case 600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x11);
rxstale = 1;
break;
case 1200:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x22);
rxstale = 1;
break;
case 2400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x33);
rxstale = 1;
break;
case 4800:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x44);
rxstale = 1;
break;
case 9600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x55);
rxstale = 2;
break;
case 14400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x66);
rxstale = 3;
break;
case 19200:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x77);
rxstale = 4;
break;
case 28800:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x88);
rxstale = 6;
break;
case 38400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x99);
rxstale = 8;
break;
case 57600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xaa);
rxstale = 16;
break;
case 76800:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xbb);
rxstale = 16;
break;
case 115200:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xcc);
rxstale = 31;
break;
case 230400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xee);
rxstale = 31;
break;
case 460800:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xff);
rxstale = 31;
break;
case 4000000:
case 3686400:
case 3200000:
case 3500000:
case 3000000:
case 2500000:
case 1500000:
case 1152000:
case 1000000:
case 921600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xff);
rxstale = 31;
break;
default:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xff);
/* default to 9600 */
bps = 9600;
rxstale = 2;
break;
}
/*
* uart baud rate depends on CSR and MND Values
* we are updating CSR before and then calling
* clk_set_rate which updates MND Values. Hence
* dsb requires here.
*/
mb();
if (bps > 460800) {
uport->uartclk = bps * 16;
} else {
uport->uartclk = 7372800;
}
if (clk_set_rate(msm_uport->clk, uport->uartclk)) {
printk(KERN_WARNING "Error setting clock rate on UART\n");
return;
}
data = rxstale & <API key>;
data |= <API key> & (rxstale << 2);
msm_hs_write(uport, UARTDM_IPR_ADDR, data);
/*
* It is suggested to do reset of transmitter and receiver after
* changing any protocol configuration. Here Baud rate and stale
* timeout are getting updated. Hence reset transmitter and receiver.
*/
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_TX);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_RX);
}
static void <API key>(struct uart_port *uport,
unsigned int bps)
{
unsigned long rxstale;
unsigned long data;
switch (bps) {
case 9600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x99);
rxstale = 2;
break;
case 14400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xaa);
rxstale = 3;
break;
case 19200:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xbb);
rxstale = 4;
break;
case 28800:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xcc);
rxstale = 6;
break;
case 38400:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xdd);
rxstale = 8;
break;
case 57600:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xee);
rxstale = 16;
break;
case 115200:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0xff);
rxstale = 31;
break;
default:
msm_hs_write(uport, UARTDM_CSR_ADDR, 0x99);
/* default to 9600 */
bps = 9600;
rxstale = 2;
break;
}
data = rxstale & <API key>;
data |= <API key> & (rxstale << 2);
msm_hs_write(uport, UARTDM_IPR_ADDR, data);
}
/*
* termios : new ktermios
* oldtermios: old ktermios previous setting
*
* Configure the serial port
*/
static void msm_hs_set_termios(struct uart_port *uport,
struct ktermios *termios,
struct ktermios *oldtermios)
{
unsigned int bps;
unsigned long data;
unsigned long flags;
unsigned int c_cflag = termios->c_cflag;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
spin_lock_irqsave(&uport->lock, flags);
clk_enable(msm_uport->clk);
/*
* Disable Rx channel of UARTDM
* DMA Rx Stall happens if enqueue and flush of Rx command happens
* concurrently. Hence before changing the baud rate/protocol
* configuration and sending flush command to ADM, disable the Rx
* channel of UARTDM.
* Note: should not reset the receiver here immediately as it is not
* suggested to do disable/reset or reset/disable at the same time.
*/
data = msm_hs_read(uport, UARTDM_DMEN_ADDR);
data &= ~<API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
/* 300 is the minimum baud support by the driver */
bps = uart_get_baud_rate(uport, termios, oldtermios, 200, 4000000);
/* Temporary remapping 200 BAUD to 3.2 mbps */
if (bps == 200)
bps = 3200000;
uport->uartclk = clk_get_rate(msm_uport->clk);
if (!uport->uartclk)
<API key>(uport, bps);
else
<API key>(uport, bps);
data = msm_hs_read(uport, UARTDM_MR2_ADDR);
data &= ~<API key>;
/* set parity */
if (PARENB == (c_cflag & PARENB)) {
if (PARODD == (c_cflag & PARODD)) {
data |= ODD_PARITY;
} else if (CMSPAR == (c_cflag & CMSPAR)) {
data |= SPACE_PARITY;
} else {
data |= EVEN_PARITY;
}
}
/* Set bits per char */
data &= ~<API key>;
switch (c_cflag & CSIZE) {
case CS5:
data |= FIVE_BPC;
break;
case CS6:
data |= SIX_BPC;
break;
case CS7:
data |= SEVEN_BPC;
break;
default:
data |= EIGHT_BPC;
break;
}
/* stop bits */
if (c_cflag & CSTOPB) {
data |= STOP_BIT_TWO;
} else {
/* otherwise 1 stop bit */
data |= STOP_BIT_ONE;
}
data |= <API key>;
/* write parity/bits per char/stop bit configuration */
msm_hs_write(uport, UARTDM_MR2_ADDR, data);
/* Configure HW flow control */
data = msm_hs_read(uport, UARTDM_MR1_ADDR);
data &= ~(<API key> | <API key>);
if (c_cflag & CRTSCTS) {
data |= <API key>;
data |= <API key>;
}
msm_hs_write(uport, UARTDM_MR1_ADDR, data);
uport->ignore_status_mask = termios->c_iflag & INPCK;
uport->ignore_status_mask |= termios->c_iflag & IGNPAR;
uport->read_status_mask = (termios->c_cflag & CREAD);
msm_hs_write(uport, UARTDM_IMR_ADDR, 0);
/* Set Transmit software time out */
uart_update_timeout(uport, c_cflag, bps);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_RX);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_TX);
if (msm_uport->rx.flush == FLUSH_NONE) {
wake_lock(&msm_uport->rx.wake_lock);
msm_uport->rx.flush = FLUSH_IGNORE;
/*
* Before using dmov APIs make sure that
* previous writel are completed. Hence
* dsb requires here.
*/
mb();
/* do discard flush */
msm_dmov_stop_cmd(msm_uport->dma_rx_channel,
&msm_uport->rx.xfer, 0);
}
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* calling other hardware component here clk_disable API. */
mb();
clk_disable(msm_uport->clk);
<API key>(&uport->lock, flags);
}
/*
* Standard API, Transmitter
* Any character in the transmit shift register is sent
*/
unsigned int msm_hs_tx_empty(struct uart_port *uport)
{
unsigned int data;
unsigned int ret = 0;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
clk_enable(msm_uport->clk);
data = msm_hs_read(uport, UARTDM_SR_ADDR);
if (data & <API key>)
ret = TIOCSER_TEMT;
#ifdef CONFIG_BT_CSR_7820
if (ret == TIOCSER_TEMT && (data & <API key>) == 0)
ret = TIOCSER_TEMT;
else
ret = 0;
#endif
clk_disable(msm_uport->clk);
return ret;
}
EXPORT_SYMBOL(msm_hs_tx_empty);
/*
* Standard API, Stop transmitter.
* Any character in the transmit shift register is sent as
* well as the current data mover transfer .
*/
static void <API key>(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
msm_uport->tx.tx_ready_int_en = 0;
}
/*
* Standard API, Stop receiver as soon as possible.
*
* Function immediately terminates the operation of the
* channel receiver and any incoming characters are lost. None
* of the receiver status bits are affected by this command and
* characters that are already in the receive FIFO there.
*/
static void <API key>(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
unsigned int data;
clk_enable(msm_uport->clk);
/* disable dlink */
data = msm_hs_read(uport, UARTDM_DMEN_ADDR);
data &= ~<API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
/* calling DMOV or CLOCK API. Hence mb() */
mb();
/* Disable the receiver */
if (msm_uport->rx.flush == FLUSH_NONE) {
wake_lock(&msm_uport->rx.wake_lock);
/* do discard flush */
msm_dmov_stop_cmd(msm_uport->dma_rx_channel,
&msm_uport->rx.xfer, 0);
}
if (msm_uport->rx.flush != FLUSH_SHUTDOWN)
msm_uport->rx.flush = FLUSH_STOP;
clk_disable(msm_uport->clk);
}
/* Transmit the next chunk of data */
static void <API key>(struct uart_port *uport)
{
int left;
int tx_count;
int aligned_tx_count;
dma_addr_t src_addr;
dma_addr_t aligned_src_addr;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
struct msm_hs_tx *tx = &msm_uport->tx;
struct circ_buf *tx_buf = &msm_uport->uport.state->xmit;
if (uart_circ_empty(tx_buf) || uport->state->port.tty->stopped) {
<API key>(uport);
return;
}
tx->dma_in_flight = 1;
tx_count = <API key>(tx_buf);
if (UARTDM_TX_BUF_SIZE < tx_count)
tx_count = UARTDM_TX_BUF_SIZE;
left = UART_XMIT_SIZE - tx_buf->tail;
if (tx_count > left)
tx_count = left;
src_addr = tx->dma_base + tx_buf->tail;
/* Mask the src_addr to align on a cache
* and add those bytes to tx_count */
aligned_src_addr = src_addr & ~(<API key>() - 1);
aligned_tx_count = tx_count + src_addr - aligned_src_addr;
<API key>(uport->dev, aligned_src_addr,
aligned_tx_count, DMA_TO_DEVICE);
tx->command_ptr->num_rows = (((tx_count + 15) >> 4) << 16) |
((tx_count + 15) >> 4);
tx->command_ptr->src_row_addr = src_addr;
<API key>(uport->dev, tx->mapped_cmd_ptr,
sizeof(dmov_box), DMA_TO_DEVICE);
*tx->command_ptr_ptr = CMD_PTR_LP | DMOV_CMD_ADDR(tx->mapped_cmd_ptr);
/* Save tx_count to use in Callback */
tx->tx_count = tx_count;
msm_hs_write(uport, UARTDM_NCF_TX_ADDR, tx_count);
/* Disable the tx_ready interrupt */
msm_uport->imr_reg &= ~<API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* Calling next DMOV API. Hence mb() here. */
mb();
<API key>(uport->dev, tx->mapped_cmd_ptr_ptr,
sizeof(u32), DMA_TO_DEVICE);
<API key>(msm_uport->dma_tx_channel, &tx->xfer);
}
/* Start to receive the next chunk of data */
static void <API key>(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
unsigned int buffer_pending = msm_uport->rx.buffer_pending;
unsigned int data;
msm_uport->rx.buffer_pending = 0;
if (buffer_pending && <API key>)
printk(KERN_ERR "Error: rx started in buffer state = %x",
buffer_pending);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_STALE_INT);
msm_hs_write(uport, UARTDM_DMRX_ADDR, UARTDM_RX_BUF_SIZE);
msm_hs_write(uport, UARTDM_CR_ADDR, STALE_EVENT_ENABLE);
msm_uport->imr_reg |= <API key>;
/*
* Enable UARTDM Rx Interface as previously it has been
* disable in set_termios before configuring baud rate.
*/
data = msm_hs_read(uport, UARTDM_DMEN_ADDR);
data |= <API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* Calling next DMOV API. Hence mb() here. */
mb();
msm_uport->rx.flush = FLUSH_NONE;
<API key>(msm_uport->dma_rx_channel, &msm_uport->rx.xfer);
}
static void flip_insert_work(struct work_struct *work)
{
unsigned long flags;
int retval;
struct msm_hs_port *msm_uport =
container_of(work, struct msm_hs_port,
rx.flip_insert_work.work);
struct tty_struct *tty = msm_uport->uport.state->port.tty;
spin_lock_irqsave(&msm_uport->uport.lock, flags);
if (msm_uport->rx.buffer_pending == NONE_PENDING) {
if (<API key>)
printk(KERN_ERR "Error: No buffer pending in %s",
__func__);
return;
}
if (msm_uport->rx.buffer_pending & FIFO_OVERRUN) {
retval = <API key>(tty, 0, TTY_OVERRUN);
if (retval)
msm_uport->rx.buffer_pending &= ~FIFO_OVERRUN;
}
if (msm_uport->rx.buffer_pending & PARITY_ERROR) {
retval = <API key>(tty, 0, TTY_PARITY);
if (retval)
msm_uport->rx.buffer_pending &= ~PARITY_ERROR;
}
if (msm_uport->rx.buffer_pending & CHARS_NORMAL) {
int rx_count, rx_offset;
rx_count = (msm_uport->rx.buffer_pending & 0xFFFF0000) >> 16;
rx_offset = (msm_uport->rx.buffer_pending & 0xFFD0) >> 5;
retval = <API key>(tty, msm_uport->rx.buffer +
rx_offset, rx_count);
msm_uport->rx.buffer_pending &= (FIFO_OVERRUN |
PARITY_ERROR);
if (retval != rx_count)
msm_uport->rx.buffer_pending |= CHARS_NORMAL |
retval << 8 | (rx_count - retval) << 16;
}
if (msm_uport->rx.buffer_pending)
<API key>(&msm_uport->rx.flip_insert_work,
msecs_to_jiffies(RETRY_TIMEOUT));
else
if ((msm_uport->clk_state == MSM_HS_CLK_ON) &&
(msm_uport->rx.flush <= FLUSH_IGNORE)) {
if (<API key>)
printk(KERN_WARNING
"msm_serial_hs: "
"Pending buffers cleared. "
"Restarting\n");
<API key>(&msm_uport->uport);
}
<API key>(&msm_uport->uport.lock, flags);
<API key>(tty);
}
static void <API key>(unsigned long tlet_ptr)
{
int retval;
int rx_count;
unsigned long status;
unsigned long flags;
unsigned int error_f = 0;
struct uart_port *uport;
struct msm_hs_port *msm_uport;
unsigned int flush;
struct tty_struct *tty;
msm_uport = container_of((struct tasklet_struct *)tlet_ptr,
struct msm_hs_port, rx.tlet);
uport = &msm_uport->uport;
tty = uport->state->port.tty;
status = msm_hs_read(uport, UARTDM_SR_ADDR);
spin_lock_irqsave(&uport->lock, flags);
clk_enable(msm_uport->clk);
msm_hs_write(uport, UARTDM_CR_ADDR, STALE_EVENT_DISABLE);
/* overflow is not connect to data in a FIFO */
if (unlikely((status & <API key>) &&
(uport->read_status_mask & CREAD))) {
retval = <API key>(tty, 0, TTY_OVERRUN);
if (!retval)
msm_uport->rx.buffer_pending |= TTY_OVERRUN;
uport->icount.buf_overrun++;
error_f = 1;
}
if (!(uport->ignore_status_mask & INPCK))
status = status & ~(<API key>);
if (unlikely(status & <API key>)) {
/* Can not tell difference between parity & frame error */
uport->icount.parity++;
error_f = 1;
if (uport->ignore_status_mask & IGNPAR) {
retval = <API key>(tty, 0, TTY_PARITY);
if (!retval)
msm_uport->rx.buffer_pending |= TTY_PARITY;
}
}
if (error_f)
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_ERROR_STATUS);
if (msm_uport->clk_req_off_state == <API key>)
msm_uport->clk_req_off_state = <API key>;
flush = msm_uport->rx.flush;
if (flush == FLUSH_IGNORE)
if (!msm_uport->rx.buffer_pending)
<API key>(uport);
if (flush == FLUSH_STOP) {
msm_uport->rx.flush = FLUSH_SHUTDOWN;
wake_up(&msm_uport->rx.wait);
}
if (flush >= FLUSH_DATA_INVALID)
goto out;
rx_count = msm_hs_read(uport, <API key>);
/* order the read of rx.buffer */
rmb();
if (0 != (uport->read_status_mask & CREAD)) {
retval = <API key>(tty, msm_uport->rx.buffer,
rx_count);
if (retval != rx_count) {
msm_uport->rx.buffer_pending |= CHARS_NORMAL |
retval << 5 | (rx_count - retval) << 16;
}
}
/* order the read of rx.buffer and the start of next rx xfer */
wmb();
if (!msm_uport->rx.buffer_pending)
<API key>(uport);
out:
if (msm_uport->rx.buffer_pending) {
if (<API key>)
printk(KERN_WARNING
"msm_serial_hs: "
"tty buffer exhausted. "
"Stalling\n");
<API key>(&msm_uport->rx.flip_insert_work
, msecs_to_jiffies(RETRY_TIMEOUT));
}
clk_disable(msm_uport->clk);
/* release wakelock in 500ms, not immediately, because higher layers
* don't always take wakelocks when they should */
wake_lock_timeout(&msm_uport->rx.wake_lock, HZ / 2);
/* <API key>() might call msm_hs_start(), so unlock */
<API key>(&uport->lock, flags);
if (flush < FLUSH_DATA_INVALID)
<API key>(tty);
}
/* Enable the transmitter Interrupt */
static void <API key>(struct uart_port *uport )
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
clk_enable(msm_uport->clk);
if (msm_uport->tx.tx_ready_int_en == 0) {
msm_uport->tx.tx_ready_int_en = 1;
if (msm_uport->tx.dma_in_flight == 0)
<API key>(uport);
}
clk_disable(msm_uport->clk);
}
/*
* This routine is called when we are done with a DMA transfer
*
* This routine is registered with Data mover when we set
* up a Data Mover transfer. It is called from Data mover ISR
* when the DMA transfer is done.
*/
static void <API key>(struct msm_dmov_cmd *cmd_ptr,
unsigned int result,
struct msm_dmov_errdata *err)
{
struct msm_hs_port *msm_uport;
WARN_ON(result != 0x80000002); /* DMA did not finish properly */
msm_uport = container_of(cmd_ptr, struct msm_hs_port, tx.xfer);
tasklet_schedule(&msm_uport->tx.tlet);
}
static void <API key>(unsigned long tlet_ptr)
{
unsigned long flags;
struct msm_hs_port *msm_uport = container_of((struct tasklet_struct *)
tlet_ptr, struct msm_hs_port, tx.tlet);
spin_lock_irqsave(&(msm_uport->uport.lock), flags);
clk_enable(msm_uport->clk);
msm_uport->imr_reg |= <API key>;
msm_hs_write(&(msm_uport->uport), UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* Calling clk API. Hence mb() requires. */
mb();
clk_disable(msm_uport->clk);
<API key>(&(msm_uport->uport.lock), flags);
}
/*
* This routine is called when we are done with a DMA transfer or the
* a flush has been sent to the data mover driver.
*
* This routine is registered with Data mover when we set up a Data Mover
* transfer. It is called from Data mover ISR when the DMA transfer is done.
*/
static void <API key>(struct msm_dmov_cmd *cmd_ptr,
unsigned int result,
struct msm_dmov_errdata *err)
{
struct msm_hs_port *msm_uport;
msm_uport = container_of(cmd_ptr, struct msm_hs_port, rx.xfer);
tasklet_schedule(&msm_uport->rx.tlet);
}
/*
* Standard API, Current states of modem control inputs
*
* Since CTS can be handled entirely by HARDWARE we always
* indicate clear to send and count on the TX FIFO to block when
* it fills up.
*
* - TIOCM_DCD
* - TIOCM_CTS
* - TIOCM_DSR
* - TIOCM_RI
* (Unsupported) DCD and DSR will return them high. RI will return low.
*/
static unsigned int <API key>(struct uart_port *uport)
{
return TIOCM_DSR | TIOCM_CAR | TIOCM_CTS;
}
/*
* Standard API, Set or clear RFR_signal
*
* Set RFR high, (Indicate we are not ready for data), we disable auto
* ready for receiving and then set RFR_N high. To set RFR to low we just turn
* back auto ready for receiving and it should lower RFR signal
* when hardware is ready
*/
void <API key>(struct uart_port *uport,
unsigned int mctrl)
{
unsigned int set_rts;
unsigned int data;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
clk_enable(msm_uport->clk);
/* RTS is active low */
set_rts = TIOCM_RTS & mctrl ? 0 : 1;
data = msm_hs_read(uport, UARTDM_MR1_ADDR);
if (set_rts) {
/*disable auto ready-for-receiving */
data &= ~<API key>;
msm_hs_write(uport, UARTDM_MR1_ADDR, data);
/* set RFR_N to high */
msm_hs_write(uport, UARTDM_CR_ADDR, RFR_HIGH);
} else {
/* Enable auto ready-for-receiving */
data |= <API key>;
msm_hs_write(uport, UARTDM_MR1_ADDR, data);
}
/* Calling CLOCK API. Hence mb() requires. */
mb();
clk_disable(msm_uport->clk);
}
void msm_hs_set_mctrl(struct uart_port *uport,
unsigned int mctrl)
{
unsigned long flags;
spin_lock_irqsave(&uport->lock, flags);
<API key>(uport, mctrl);
<API key>(&uport->lock, flags);
}
EXPORT_SYMBOL(msm_hs_set_mctrl);
/* Standard API, Enable modem status (CTS) interrupt */
static void <API key>(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
clk_enable(msm_uport->clk);
/* Enable DELTA_CTS Interrupt */
msm_uport->imr_reg |= <API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* Calling CLOCK API. Hence mb() requires here. */
mb();
clk_disable(msm_uport->clk);
}
/*
* Standard API, Break Signal
*
* Control the transmission of a break signal. ctl eq 0 => break
* signal terminate ctl ne 0 => start break signal
*/
static void msm_hs_break_ctl(struct uart_port *uport, int ctl)
{
unsigned long flags;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
spin_lock_irqsave(&uport->lock, flags);
clk_enable(msm_uport->clk);
msm_hs_write(uport, UARTDM_CR_ADDR, ctl ? START_BREAK : STOP_BREAK);
/* Calling CLOCK API. Hence mb() requires here. */
mb();
clk_disable(msm_uport->clk);
<API key>(&uport->lock, flags);
}
static void msm_hs_config_port(struct uart_port *uport, int cfg_flags)
{
unsigned long flags;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
if (cfg_flags & UART_CONFIG_TYPE) {
uport->type = PORT_MSM;
msm_hs_request_port(uport);
}
spin_lock_irqsave(&uport->lock, flags);
if (is_gsbi_uart(msm_uport)) {
if (msm_uport->pclk)
clk_enable(msm_uport->pclk);
iowrite32(GSBI_PROTOCOL_UART, msm_uport->mapped_gsbi +
GSBI_CONTROL_ADDR);
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
}
<API key>(&uport->lock, flags);
}
/* Handle CTS changes (Called from interrupt handler) */
static void <API key>(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
clk_enable(msm_uport->clk);
/* clear interrupt */
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_CTS);
/* Calling CLOCK API. Hence mb() requires here. */
mb();
uport->icount.cts++;
clk_disable(msm_uport->clk);
/* clear the IOCTL TIOCMIWAIT if called */
<API key>(&uport->state->port.delta_msr_wait);
}
/* check if the TX path is flushed, and if so clock off
* returns 0 did not clock off, need to retry (still sending final byte)
* -1 did not clock off, do not retry
* 1 if we clocked off
*/
static int <API key>(struct uart_port *uport)
{
unsigned long sr_status;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
struct circ_buf *tx_buf = &uport->state->xmit;
/* Cancel if tx tty buffer is not empty, dma is in flight,
* or tx fifo is not empty */
if (msm_uport->clk_state != <API key> ||
!uart_circ_empty(tx_buf) || msm_uport->tx.dma_in_flight ||
msm_uport->imr_reg & <API key>) {
return -1;
}
/* Make sure the uart is finished with the last byte */
sr_status = msm_hs_read(uport, UARTDM_SR_ADDR);
if (!(sr_status & <API key>))
return 0; /* retry */
/* Make sure forced RXSTALE flush complete */
switch (msm_uport->clk_req_off_state) {
case CLK_REQ_OFF_START:
msm_uport->clk_req_off_state = <API key>;
msm_hs_write(uport, UARTDM_CR_ADDR, FORCE_STALE_EVENT);
/*
* Before returning make sure that device writel completed.
* Hence mb() requires here.
*/
mb();
return 0; /* RXSTALE flush not complete - retry */
case <API key>:
case <API key>:
return 0; /* RXSTALE flush not complete - retry */
case <API key>:
break; /* continue */
}
if (msm_uport->rx.flush != FLUSH_SHUTDOWN) {
if (msm_uport->rx.flush == FLUSH_NONE)
<API key>(uport);
return 0; /* come back later to really clock off */
}
/* we really want to clock off */
clk_disable(msm_uport->clk);
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
msm_uport->clk_state = MSM_HS_CLK_OFF;
if (<API key>(msm_uport)) {
msm_uport->wakeup.ignore = 1;
enable_irq(msm_uport->wakeup.irq);
}
wake_unlock(&msm_uport->dma_wake_lock);
return 1;
}
static enum hrtimer_restart <API key>(struct hrtimer *timer) {
unsigned long flags;
int ret = HRTIMER_NORESTART;
struct msm_hs_port *msm_uport = container_of(timer, struct msm_hs_port,
clk_off_timer);
struct uart_port *uport = &msm_uport->uport;
spin_lock_irqsave(&uport->lock, flags);
if (!<API key>(uport)) {
hrtimer_forward_now(timer, msm_uport->clk_off_delay);
ret = HRTIMER_RESTART;
}
<API key>(&uport->lock, flags);
return ret;
}
#ifdef ALRAN
#define OVERRUN_CNT 50
#define OVERRUN_DELAY 100000000 /* 100ms */
static int u_overrun_cnt;
static int buf_overrun;
void u_overrun_clock_off(struct uart_port *uport)
{
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
unsigned long flags;
spin_lock_irqsave(&uport->lock, flags);
/* Stop RX & TX */
<API key>(uport);
<API key>(uport);
/* we really want to clock off */
clk_disable(msm_uport->clk);
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
msm_uport->clk_state = MSM_HS_CLK_OFF;
/*calling u_overrun_clock_on() after 100ms*/
hrtimer_start(&msm_uport->qtest_timer,
msm_uport->qtest_delay,
HRTIMER_MODE_REL);
u_overrun_cnt++;
pr_err("NEOBT u_overrun_cnt: %d\n", u_overrun_cnt);
<API key>(&uport->lock, flags);
}
static enum hrtimer_restart u_overrun_clock_on(struct hrtimer *timer)
{
struct msm_hs_port *msm_uport = container_of(timer, struct msm_hs_port,
qtest_timer);
struct uart_port *uport = &msm_uport->uport;
unsigned long flags;
unsigned int data;
int ret = HRTIMER_NORESTART;
spin_lock_irqsave(&uport->lock, flags);
/* Start TX */
<API key>(uport);
clk_enable(msm_uport->clk);
if (msm_uport->pclk)
ret = clk_enable(msm_uport->pclk);
if (unlikely(ret)) {
dev_err(uport->dev, "Clock ON Failure"
"Stalling HSUART\n");
hrtimer_forward_now(timer, msm_uport->qtest_delay);
return HRTIMER_RESTART;
}
/* Start RX */
if (msm_uport->rx.flush == FLUSH_STOP ||
msm_uport->rx.flush == FLUSH_SHUTDOWN) {
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_RX);
data = msm_hs_read(uport, UARTDM_DMEN_ADDR);
data |= <API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
/* Complete above device write. Hence mb() here. */
mb();
}
<API key>(uport);
if (msm_uport->rx.flush == FLUSH_STOP)
msm_uport->rx.flush = FLUSH_IGNORE;
msm_uport->clk_state = MSM_HS_CLK_ON;
<API key>(&uport->lock, flags);
return ret;
}
#endif
static irqreturn_t msm_hs_isr(int irq, void *dev)
{
unsigned long flags;
unsigned long isr_status;
#ifdef ALRAN
unsigned long sr_status;
#endif
struct msm_hs_port *msm_uport = (struct msm_hs_port *)dev;
struct uart_port *uport = &msm_uport->uport;
struct circ_buf *tx_buf = &uport->state->xmit;
struct msm_hs_tx *tx = &msm_uport->tx;
struct msm_hs_rx *rx = &msm_uport->rx;
spin_lock_irqsave(&uport->lock, flags);
isr_status = msm_hs_read(uport, UARTDM_MISR_ADDR);
#ifdef ALRAN
pHSLogData[nNextLogIdx].time = ktime_get();
pHSLogData[nNextLogIdx].unPid = current->pid;
pHSLogData[nNextLogIdx].isr_status = isr_status;
sr_status = msm_hs_read(uport, UARTDM_SR_ADDR);
pHSLogData[nNextLogIdx].sr_status = sr_status;
/* extra check for spurious msm_hs_isr */
if(!isr_status) {
pr_err("%s(): try to unlock msm_hs_isr", __func__);
<API key>(&uport->lock, flags);
return IRQ_HANDLED;
}
/*Adding this line for using overrun workaround*/
if (sr_status & <API key>) {
buf_overrun++;
if (buf_overrun == OVERRUN_CNT) {
buf_overrun = 0;
u_overrun_clock_off(uport);
<API key>(&uport->lock, flags);
return IRQ_HANDLED;
}
}
nNextLogIdx++;
if (nNextLogIdx == MAX_KERNEL_IRQ_LOGS)
nNextLogIdx = 0;
pHSLogData[nNextLogIdx].unPid = 0xAAAAAAAA;
#endif
/* Uart RX starting */
if (isr_status & <API key>) {
wake_lock(&rx->wake_lock); /* hold wakelock while rx dma */
msm_uport->imr_reg &= ~<API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/* Complete device write for IMR. Hence mb() requires. */
mb();
}
/* Stale rx interrupt */
if (isr_status & <API key>) {
msm_hs_write(uport, UARTDM_CR_ADDR, STALE_EVENT_DISABLE);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_STALE_INT);
/*
* Complete device write before calling DMOV API. Hence
* mb() requires here.
*/
mb();
if (msm_uport->clk_req_off_state == <API key>)
msm_uport->clk_req_off_state =
<API key>;
if (rx->flush == FLUSH_NONE) {
rx->flush = FLUSH_DATA_READY;
msm_dmov_flush(msm_uport->dma_rx_channel);
}
}
/* tx ready interrupt */
if (isr_status & <API key>) {
/* Clear TX Ready */
msm_hs_write(uport, UARTDM_CR_ADDR, CLEAR_TX_READY);
if (msm_uport->clk_state == <API key>) {
msm_uport->imr_reg |= <API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR,
msm_uport->imr_reg);
}
/*
* Complete both writes before starting new TX.
* Hence mb() requires here.
*/
mb();
/* Complete DMA TX transactions and submit new transactions */
tx_buf->tail = (tx_buf->tail + tx->tx_count) & ~UART_XMIT_SIZE;
tx->dma_in_flight = 0;
uport->icount.tx += tx->tx_count;
if (tx->tx_ready_int_en)
<API key>(uport);
if (<API key>(tx_buf) < WAKEUP_CHARS)
uart_write_wakeup(uport);
}
if (isr_status & <API key>) {
/* TX FIFO is empty */
msm_uport->imr_reg &= ~<API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/*
* Complete device write before starting clock_off request.
* Hence mb() requires here.
*/
mb();
if (!<API key>(uport))
hrtimer_start(&msm_uport->clk_off_timer,
msm_uport->clk_off_delay,
HRTIMER_MODE_REL);
}
/* Change in CTS interrupt */
if (isr_status & <API key>)
<API key>(uport);
<API key>(&uport->lock, flags);
return IRQ_HANDLED;
}
/* request to turn off uart clock once pending TX is flushed */
void <API key>(struct uart_port *uport) {
unsigned long flags;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
spin_lock_irqsave(&uport->lock, flags);
if (msm_uport->clk_state == MSM_HS_CLK_ON) {
msm_uport->clk_state = <API key>;
msm_uport->clk_req_off_state = CLK_REQ_OFF_START;
msm_uport->imr_reg |= <API key>;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/*
* Complete device write before retuning back.
* Hence mb() requires here.
*/
mb();
}
<API key>(&uport->lock, flags);
}
EXPORT_SYMBOL(<API key>);
static void <API key>(struct uart_port *uport) {
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
unsigned int data;
int ret = 0;
switch (msm_uport->clk_state) {
case MSM_HS_CLK_OFF:
wake_lock(&msm_uport->dma_wake_lock);
clk_enable(msm_uport->clk);
if (msm_uport->pclk)
ret = clk_enable(msm_uport->pclk);
disable_irq_nosync(msm_uport->wakeup.irq);
if (unlikely(ret)) {
dev_err(uport->dev, "Clock ON Failure"
"Stalling HSUART\n");
break;
}
/* else fall-through */
case <API key>:
if (msm_uport->rx.flush == FLUSH_STOP ||
msm_uport->rx.flush == FLUSH_SHUTDOWN) {
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_RX);
data = msm_hs_read(uport, UARTDM_DMEN_ADDR);
data |= <API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
/* Complete above device write. Hence mb() here. */
mb();
}
<API key>(&msm_uport->clk_off_timer);
if (msm_uport->rx.flush == FLUSH_SHUTDOWN)
<API key>(uport);
if (msm_uport->rx.flush == FLUSH_STOP)
msm_uport->rx.flush = FLUSH_IGNORE;
msm_uport->clk_state = MSM_HS_CLK_ON;
break;
case MSM_HS_CLK_ON:
break;
case MSM_HS_CLK_PORT_OFF:
break;
}
}
void <API key>(struct uart_port *uport) {
unsigned long flags;
spin_lock_irqsave(&uport->lock, flags);
<API key>(uport);
<API key>(&uport->lock, flags);
}
EXPORT_SYMBOL(<API key>);
static irqreturn_t msm_hs_wakeup_isr(int irq, void *dev)
{
unsigned int wakeup = 0;
unsigned long flags;
struct msm_hs_port *msm_uport = (struct msm_hs_port *)dev;
struct uart_port *uport = &msm_uport->uport;
struct tty_struct *tty = NULL;
spin_lock_irqsave(&uport->lock, flags);
if (msm_uport->clk_state == MSM_HS_CLK_OFF) {
/* ignore the first irq - it is a pending irq that occured
* before enable_irq() */
if (msm_uport->wakeup.ignore)
msm_uport->wakeup.ignore = 0;
else
wakeup = 1;
}
if (wakeup) {
/* the uart was clocked off during an rx, wake up and
* optionally inject char into tty rx */
<API key>(uport);
if (msm_uport->wakeup.inject_rx) {
tty = uport->state->port.tty;
<API key>(tty,
msm_uport->wakeup.rx_to_inject,
TTY_NORMAL);
}
}
<API key>(&uport->lock, flags);
if (wakeup && msm_uport->wakeup.inject_rx)
<API key>(tty);
return IRQ_HANDLED;
}
static const char *msm_hs_type(struct uart_port *port)
{
return ("MSM HS UART");
}
/* Called when port is opened */
static int msm_hs_startup(struct uart_port *uport)
{
int ret;
int rfr_level;
unsigned long flags;
unsigned int data;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
struct circ_buf *tx_buf = &uport->state->xmit;
struct msm_hs_tx *tx = &msm_uport->tx;
rfr_level = uport->fifosize;
if (rfr_level > 16)
rfr_level -= 16;
tx->dma_base = dma_map_single(uport->dev, tx_buf->buf, UART_XMIT_SIZE,
DMA_TO_DEVICE);
/* turn on uart clk */
ret = msm_hs_init_clk(uport);
if (unlikely(ret))
return ret;
/* Set auto RFR Level */
data = msm_hs_read(uport, UARTDM_MR1_ADDR);
data &= ~<API key>;
data &= ~<API key>;
data |= (<API key> & (rfr_level << 2));
data |= (<API key> & rfr_level);
msm_hs_write(uport, UARTDM_MR1_ADDR, data);
/* Make sure RXSTALE count is non-zero */
data = msm_hs_read(uport, UARTDM_IPR_ADDR);
if (!data) {
data |= 0x1f & <API key>;
msm_hs_write(uport, UARTDM_IPR_ADDR, data);
}
/* Enable Data Mover Mode */
data = <API key> | <API key>;
msm_hs_write(uport, UARTDM_DMEN_ADDR, data);
/* Reset TX */
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_TX);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_RX);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_ERROR_STATUS);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_BREAK_INT);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_STALE_INT);
msm_hs_write(uport, UARTDM_CR_ADDR, RESET_CTS);
msm_hs_write(uport, UARTDM_CR_ADDR, RFR_LOW);
/* Turn on Uart Receiver */
msm_hs_write(uport, UARTDM_CR_ADDR, <API key>);
/* Turn on Uart Transmitter */
msm_hs_write(uport, UARTDM_CR_ADDR, <API key>);
/* Initialize the tx */
tx->tx_ready_int_en = 0;
tx->dma_in_flight = 0;
tx->xfer.complete_func = <API key>;
tx->command_ptr->cmd = CMD_LC |
CMD_DST_CRCI(msm_uport->dma_tx_crci) | CMD_MODE_BOX;
tx->command_ptr->src_dst_len = (<API key> << 16)
| (<API key>);
tx->command_ptr->row_offset = (<API key> << 16);
tx->command_ptr->dst_row_addr =
msm_uport->uport.mapbase + UARTDM_TF_ADDR;
msm_uport->imr_reg |= <API key>;
/* Enable reading the current CTS, no harm even if CTS is ignored */
msm_uport->imr_reg |= <API key>;
msm_hs_write(uport, UARTDM_TFWR_ADDR, 0); /* TXLEV on empty TX fifo */
/*
* Complete all device write related configuration before
* queuing RX request. Hence mb() requires here.
*/
mb();
if (<API key>(msm_uport)) {
ret = irq_set_irq_wake(msm_uport->wakeup.irq, 1);
if (unlikely(ret))
return ret;
}
ret = request_irq(uport->irq, msm_hs_isr, IRQF_TRIGGER_HIGH,
"msm_hs_uart", msm_uport);
if (unlikely(ret))
return ret;
if (<API key>(msm_uport)) {
ret = request_irq(msm_uport->wakeup.irq, msm_hs_wakeup_isr,
<API key>,
"msm_hs_wakeup", msm_uport);
if (unlikely(ret))
return ret;
disable_irq(msm_uport->wakeup.irq);
}
spin_lock_irqsave(&uport->lock, flags);
<API key>(uport);
<API key>(&uport->lock, flags);
ret = <API key>(uport->dev);
if (ret)
dev_err(uport->dev, "set active error:%d\n", ret);
pm_runtime_enable(uport->dev);
#ifdef CONFIG_BT_CSR_7820
/* Temp. patch for Bluetooth hci timeout */
pm_runtime_get_sync(uport->dev);
#endif
return 0;
}
/* Initialize tx and rx data structures */
static int uartdm_init_port(struct uart_port *uport)
{
int ret = 0;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
struct msm_hs_tx *tx = &msm_uport->tx;
struct msm_hs_rx *rx = &msm_uport->rx;
/* Allocate the command pointer. Needs to be 64 bit aligned */
tx->command_ptr = kmalloc(sizeof(dmov_box), GFP_KERNEL | __GFP_DMA);
if (!tx->command_ptr)
return -ENOMEM;
tx->command_ptr_ptr = kmalloc(sizeof(u32), GFP_KERNEL | __GFP_DMA);
if (!tx->command_ptr_ptr) {
ret = -ENOMEM;
goto free_tx_command_ptr;
}
tx->mapped_cmd_ptr = dma_map_single(uport->dev, tx->command_ptr,
sizeof(dmov_box), DMA_TO_DEVICE);
tx->mapped_cmd_ptr_ptr = dma_map_single(uport->dev,
tx->command_ptr_ptr,
sizeof(u32), DMA_TO_DEVICE);
tx->xfer.cmdptr = DMOV_CMD_ADDR(tx->mapped_cmd_ptr_ptr);
init_waitqueue_head(&rx->wait);
wake_lock_init(&rx->wake_lock, WAKE_LOCK_SUSPEND, "msm_serial_hs_rx");
wake_lock_init(&msm_uport->dma_wake_lock, WAKE_LOCK_SUSPEND,
"msm_serial_hs_dma");
tasklet_init(&rx->tlet, <API key>,
(unsigned long) &rx->tlet);
tasklet_init(&tx->tlet, <API key>,
(unsigned long) &tx->tlet);
rx->pool = dma_pool_create("rx_buffer_pool", uport->dev,
UARTDM_RX_BUF_SIZE, 16, 0);
if (!rx->pool) {
pr_err("%s(): cannot allocate rx_buffer_pool", __func__);
ret = -ENOMEM;
goto exit_tasket_init;
}
rx->buffer = dma_pool_alloc(rx->pool, GFP_KERNEL, &rx->rbuffer);
if (!rx->buffer) {
pr_err("%s(): cannot allocate rx->buffer", __func__);
ret = -ENOMEM;
goto free_pool;
}
/* Allocate the command pointer. Needs to be 64 bit aligned */
rx->command_ptr = kmalloc(sizeof(dmov_box), GFP_KERNEL | __GFP_DMA);
if (!rx->command_ptr) {
pr_err("%s(): cannot allocate rx->command_ptr", __func__);
ret = -ENOMEM;
goto free_rx_buffer;
}
rx->command_ptr_ptr = kmalloc(sizeof(u32), GFP_KERNEL | __GFP_DMA);
if (!rx->command_ptr_ptr) {
pr_err("%s(): cannot allocate rx->command_ptr_ptr", __func__);
ret = -ENOMEM;
goto free_rx_command_ptr;
}
rx->command_ptr->num_rows = ((UARTDM_RX_BUF_SIZE >> 4) << 16) |
(UARTDM_RX_BUF_SIZE >> 4);
rx->command_ptr->dst_row_addr = rx->rbuffer;
/* Set up Uart Receive */
msm_hs_write(uport, UARTDM_RFWR_ADDR, 0);
rx->xfer.complete_func = <API key>;
rx->command_ptr->cmd = CMD_LC |
CMD_SRC_CRCI(msm_uport->dma_rx_crci) | CMD_MODE_BOX;
rx->command_ptr->src_dst_len = (<API key> << 16)
| (<API key>);
rx->command_ptr->row_offset = <API key>;
rx->command_ptr->src_row_addr = uport->mapbase + UARTDM_RF_ADDR;
rx->mapped_cmd_ptr = dma_map_single(uport->dev, rx->command_ptr,
sizeof(dmov_box), DMA_TO_DEVICE);
*rx->command_ptr_ptr = CMD_PTR_LP | DMOV_CMD_ADDR(rx->mapped_cmd_ptr);
rx->cmdptr_dmaaddr = dma_map_single(uport->dev, rx->command_ptr_ptr,
sizeof(u32), DMA_TO_DEVICE);
rx->xfer.cmdptr = DMOV_CMD_ADDR(rx->cmdptr_dmaaddr);
INIT_DELAYED_WORK(&rx->flip_insert_work, flip_insert_work);
return ret;
free_rx_command_ptr:
kfree(rx->command_ptr);
free_rx_buffer:
dma_pool_free(msm_uport->rx.pool, msm_uport->rx.buffer,
msm_uport->rx.rbuffer);
free_pool:
dma_pool_destroy(msm_uport->rx.pool);
exit_tasket_init:
wake_lock_destroy(&msm_uport->rx.wake_lock);
wake_lock_destroy(&msm_uport->dma_wake_lock);
tasklet_kill(&msm_uport->tx.tlet);
tasklet_kill(&msm_uport->rx.tlet);
dma_unmap_single(uport->dev, msm_uport->tx.mapped_cmd_ptr_ptr,
sizeof(u32), DMA_TO_DEVICE);
dma_unmap_single(uport->dev, msm_uport->tx.mapped_cmd_ptr,
sizeof(dmov_box), DMA_TO_DEVICE);
kfree(msm_uport->tx.command_ptr_ptr);
free_tx_command_ptr:
kfree(msm_uport->tx.command_ptr);
return ret;
}
static int __init msm_hs_probe(struct platform_device *pdev)
{
int ret;
struct uart_port *uport;
struct msm_hs_port *msm_uport;
struct resource *resource;
struct <API key> *pdata = pdev->dev.platform_data;
if (pdev->id < 0 || pdev->id >= UARTDM_NR) {
printk(KERN_ERR "Invalid plaform device ID = %d\n", pdev->id);
return -EINVAL;
}
msm_uport = &q_uart_port[pdev->id];
uport = &msm_uport->uport;
uport->dev = &pdev->dev;
resource = <API key>(pdev, IORESOURCE_MEM, 0);
if (unlikely(!resource))
return -ENXIO;
uport->mapbase = resource->start; /* virtual address */
uport->membase = ioremap(uport->mapbase, PAGE_SIZE);
if (unlikely(!uport->membase))
return -ENOMEM;
uport->irq = platform_get_irq(pdev, 0);
if (unlikely((int)uport->irq < 0))
return -ENXIO;
if (pdata == NULL)
msm_uport->wakeup.irq = -1;
else {
msm_uport->wakeup.irq = pdata->wakeup_irq;
msm_uport->wakeup.ignore = 1;
msm_uport->wakeup.inject_rx = pdata->inject_rx_on_wakeup;
msm_uport->wakeup.rx_to_inject = pdata->rx_to_inject;
if (unlikely(msm_uport->wakeup.irq < 0))
return -ENXIO;
if (pdata->gpio_config)
if (unlikely(pdata->gpio_config(1)))
dev_err(uport->dev, "Cannot configure"
"gpios\n");
}
resource = <API key>(pdev, IORESOURCE_DMA,
"uartdm_channels");
if (unlikely(!resource))
return -ENXIO;
msm_uport->dma_tx_channel = resource->start;
msm_uport->dma_rx_channel = resource->end;
resource = <API key>(pdev, IORESOURCE_DMA,
"uartdm_crci");
if (unlikely(!resource))
return -ENXIO;
msm_uport->dma_tx_crci = resource->start;
msm_uport->dma_rx_crci = resource->end;
uport->iotype = UPIO_MEM;
uport->fifosize = 64;
uport->ops = &msm_hs_ops;
uport->flags = UPF_BOOT_AUTOCONF;
uport->uartclk = 7372800;
msm_uport->imr_reg = 0x0;
msm_uport->clk = clk_get(&pdev->dev, "core_clk");
if (IS_ERR(msm_uport->clk))
return PTR_ERR(msm_uport->clk);
msm_uport->pclk = clk_get(&pdev->dev, "iface_clk");
/*
* Some configurations do not require explicit pclk control so
* do not flag error on pclk get failure.
*/
if (IS_ERR(msm_uport->pclk))
msm_uport->pclk = NULL;
ret = clk_set_rate(msm_uport->clk, uport->uartclk);
if (ret) {
printk(KERN_WARNING "Error setting clock rate on UART\n");
return ret;
}
ret = uartdm_init_port(uport);
if (unlikely(ret))
return ret;
/* configure the CR Protection to Enable */
msm_hs_write(uport, UARTDM_CR_ADDR, CR_PROTECTION_EN);
/*
* Enable Command register protection before going ahead as this hw
* configuration makes sure that issued cmd to CR register gets complete
* before next issued cmd start. Hence mb() requires here.
*/
mb();
msm_uport->clk_state = MSM_HS_CLK_PORT_OFF;
hrtimer_init(&msm_uport->clk_off_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL);
msm_uport->clk_off_timer.function = <API key>;
msm_uport->clk_off_delay = ktime_set(0, 1000000); /* 1ms */
#ifdef ALRAN
hrtimer_init(&msm_uport->qtest_timer, CLOCK_MONOTONIC,
HRTIMER_MODE_REL);
msm_uport->qtest_timer.function = u_overrun_clock_on;
msm_uport->qtest_delay = ktime_set(0, OVERRUN_DELAY); /* 100ms */
#endif
ret = sysfs_create_file(&pdev->dev.kobj, &dev_attr_clock.attr);
if (unlikely(ret))
return ret;
<API key>(msm_uport, pdev->id);
uport->line = pdev->id;
return uart_add_one_port(&msm_hs_driver, uport);
}
static int __init msm_serial_hs_init(void)
{
int ret;
int i;
/* Init all UARTS as non-configured */
for (i = 0; i < UARTDM_NR; i++)
q_uart_port[i].uport.type = PORT_UNKNOWN;
ret = <API key>(&msm_hs_driver);
if (unlikely(ret)) {
printk(KERN_ERR "%s failed to load\n", __FUNCTION__);
return ret;
}
debug_base = debugfs_create_dir("msm_serial_hs", NULL);
if (IS_ERR_OR_NULL(debug_base))
pr_info("msm_serial_hs: Cannot create debugfs dir\n");
ret = <API key>(&<API key>,
msm_hs_probe);
if (ret) {
printk(KERN_ERR "%s failed to load\n", __FUNCTION__);
<API key>(debug_base);
<API key>(&msm_hs_driver);
return ret;
}
printk(KERN_INFO "msm_serial_hs module loaded\n");
return ret;
}
/*
* Called by the upper layer when port is closed.
* - Disables the port
* - Unhook the ISR
*/
static void msm_hs_shutdown(struct uart_port *uport)
{
unsigned long flags;
struct msm_hs_port *msm_uport = UARTDM_TO_MSM(uport);
BUG_ON(msm_uport->rx.flush < FLUSH_STOP);
tasklet_kill(&msm_uport->tx.tlet);
wait_event(msm_uport->rx.wait, msm_uport->rx.flush == FLUSH_SHUTDOWN);
tasklet_kill(&msm_uport->rx.tlet);
<API key>(&msm_uport->rx.flip_insert_work);
#ifdef CONFIG_BT_CSR_7820
/* Moved free irq on top of shutdown because of deadlock issue */
/* Free the interrupt */
free_irq(uport->irq, msm_uport);
#endif
clk_enable(msm_uport->clk);
pm_runtime_disable(uport->dev);
<API key>(uport->dev);
#ifdef CONFIG_BT_CSR_7820
/* Temp. patch for Bluetooth hci timeout */
pm_runtime_put_sync(uport->dev);
#endif
spin_lock_irqsave(&uport->lock, flags);
/* Disable the transmitter */
msm_hs_write(uport, UARTDM_CR_ADDR, <API key>);
/* Disable the receiver */
msm_hs_write(uport, UARTDM_CR_ADDR, <API key>);
msm_uport->imr_reg = 0;
msm_hs_write(uport, UARTDM_IMR_ADDR, msm_uport->imr_reg);
/*
* Complete all device write before actually disabling uartclk.
* Hence mb() requires here.
*/
mb();
clk_disable(msm_uport->clk); /* to balance local clk_enable() */
if (msm_uport->clk_state != MSM_HS_CLK_OFF) {
clk_disable(msm_uport->clk); /* to balance clk_state */
if (msm_uport->pclk)
clk_disable(msm_uport->pclk);
wake_unlock(&msm_uport->dma_wake_lock);
}
msm_uport->clk_state = MSM_HS_CLK_PORT_OFF;
dma_unmap_single(uport->dev, msm_uport->tx.dma_base,
UART_XMIT_SIZE, DMA_TO_DEVICE);
<API key>(&uport->lock, flags);
if (<API key>(msm_uport))
irq_set_irq_wake(msm_uport->wakeup.irq, 0);
#ifndef CONFIG_BT_CSR_7820
/* Free the interrupt */
free_irq(uport->irq, msm_uport);
#endif
if (<API key>(msm_uport))
free_irq(msm_uport->wakeup.irq, msm_uport);
}
static void __exit msm_serial_hs_exit(void)
{
printk(KERN_INFO "msm_serial_hs module removed\n");
<API key>(&<API key>);
<API key>(&msm_hs_driver);
}
static int msm_hs_runtime_idle(struct device *dev)
{
/*
* returning success from idle results in runtime suspend to be
* called
*/
return 0;
}
static int <API key>(struct device *dev)
{
struct platform_device *pdev = container_of(dev, struct
platform_device, dev);
struct msm_hs_port *msm_uport = &q_uart_port[pdev->id];
<API key>(&msm_uport->uport);
return 0;
}
static int <API key>(struct device *dev)
{
struct platform_device *pdev = container_of(dev, struct
platform_device, dev);
struct msm_hs_port *msm_uport = &q_uart_port[pdev->id];
<API key>(&msm_uport->uport);
return 0;
}
static const struct dev_pm_ops msm_hs_dev_pm_ops = {
.runtime_suspend = <API key>,
.runtime_resume = <API key>,
.runtime_idle = msm_hs_runtime_idle,
};
static struct platform_driver <API key> = {
.remove = msm_hs_remove,
.driver = {
.name = "msm_serial_hs",
.pm = &msm_hs_dev_pm_ops,
},
};
static struct uart_driver msm_hs_driver = {
.owner = THIS_MODULE,
.driver_name = "msm_serial_hs",
.dev_name = "ttyHS",
.nr = UARTDM_NR,
.cons = 0,
};
static struct uart_ops msm_hs_ops = {
.tx_empty = msm_hs_tx_empty,
.set_mctrl = <API key>,
.get_mctrl = <API key>,
.stop_tx = <API key>,
.start_tx = <API key>,
.stop_rx = <API key>,
.enable_ms = <API key>,
.break_ctl = msm_hs_break_ctl,
.startup = msm_hs_startup,
.shutdown = msm_hs_shutdown,
.set_termios = msm_hs_set_termios,
.type = msm_hs_type,
.config_port = msm_hs_config_port,
.release_port = msm_hs_release_port,
.request_port = msm_hs_request_port,
};
module_init(msm_serial_hs_init);
module_exit(msm_serial_hs_exit);
MODULE_DESCRIPTION("High Speed UART Driver for the MSM chipset");
MODULE_VERSION("1.2");
MODULE_LICENSE("GPL v2"); |
<?php
defined('_JEXEC') or die('RESTRICTED');
abstract class WFToken
{
private static function _createToken( $length = 32 )
{
static $chars = '0123456789abcdef';
$max = strlen( $chars ) - 1;
$token = '';
$name = session_name();
for( $i = 0; $i < $length; ++$i ) {
$token .= $chars[ (rand( 0, $max )) ];
}
return md5($token.$name);
}
public static function getToken()
{
$session =JFactory::getSession();
$user =JFactory::getUser();
$token = $session->get('session.token', null, 'wf');
//create a token
if ( $token === null) {
$token = self::_createToken(12);
$session->set('session.token', $token, 'wf');
}
$hash = 'wf' . JUtility::getHash($user->get( 'id', 0 ) . $token);
return $hash;
}
/**
* Check the received token
*/
public static function checkToken($method = 'POST')
{
$token = self::getToken();
// check POST and GET for token
return JRequest::getVar($token, JRequest::getVar($token, '', 'GET', 'alnum'), 'POST', 'alnum');
}
} |
<?php
namespace Symfony\Component\DependencyInjection\Loader\Configurator\Traits;
use Symfony\Component\DependencyInjection\Exception\<API key>;
trait TagTrait
{
/**
* Adds a tag for this definition.
*
* @param string $name The tag name
* @param array $attributes An array of attributes
*
* @return $this
*/
final public function tag($name, array $attributes = array())
{
if (!\is_string($name) || '' === $name) {
throw new <API key>(sprintf('The tag name for service "%s" must be a non-empty string.', $this->id));
}
foreach ($attributes as $attribute => $value) {
if (!is_scalar($value) && null !== $value) {
throw new <API key>(sprintf('A tag attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s".', $this->id, $name, $attribute));
}
}
$this->definition->addTag($name, $attributes);
return $this;
}
} |
#endregion
using System.Collections.Generic;
namespace OpenRA.Traits
{
[Desc("Attach this to the `World` actor.")]
public class FactionInfo : TraitInfo<Faction>
{
[Desc("This is the name exposed to the players.")]
public readonly string Name = null;
[Desc("This is the internal name for owner checks.")]
public readonly string InternalName = null;
[Desc("Pick a random faction as the player's facton out of this list.")]
public readonly HashSet<string> <API key> = new HashSet<string>();
[Desc("The side that the faction belongs to. For example, England belongs to the 'Allies' side.")]
public readonly string Side = null;
[Translate]
public readonly string Description = null;
public readonly bool Selectable = true;
}
public class Faction { /* we're only interested in the Info */ }
} |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
class ModuleDocFragment(object):
# Windows shell documentation fragment
# FIXME: set_module_language don't belong here but must be set so they don't fail when someone
# get_option('set_module_language') on this plugin
DOCUMENTATION = """
options:
async_dir:
description:
- Directory in which ansible will keep async job information.
- Before Ansible 2.8, this was set to C(remote_tmp + "\\.ansible_async").
default: '%USERPROFILE%\\.ansible_async'
ini:
- section: powershell
key: async_dir
vars:
- name: ansible_async_dir
version_added: '2.8'
remote_tmp:
description:
- Temporary directory to use on targets when copying files to the host.
default: '%TEMP%'
ini:
- section: powershell
key: remote_tmp
vars:
- name: ansible_remote_tmp
set_module_language:
description:
- Controls if we set the locale for modules when executing on the
target.
- Windows only supports C(no) as an option.
type: bool
default: 'no'
choices: ['no', False]
environment:
description:
- List of dictionaries of environment variables and their values to use when
executing commands.
type: list
default: [{}]
""" |
// ssl/detail/write_op.hpp
#ifndef <API key>
#define <API key>
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/detail/<API key>.hpp"
#include "asio/ssl/detail/engine.hpp"
#include "asio/detail/push_options.hpp"
namespace asio {
namespace ssl {
namespace detail {
template <typename ConstBufferSequence>
class write_op
{
public:
static ASIO_CONSTEXPR const char* tracking_name()
{
return "ssl::stream<>::async_write_some";
}
write_op(const ConstBufferSequence& buffers)
: buffers_(buffers)
{
}
engine::want operator()(engine& eng,
asio::error_code& ec,
std::size_t& bytes_transferred) const
{
unsigned char storage[
asio::detail::<API key><asio::const_buffer,
ConstBufferSequence>::<API key>];
asio::const_buffer buffer =
asio::detail::<API key><asio::const_buffer,
ConstBufferSequence>::linearise(buffers_, asio::buffer(storage));
return eng.write(buffer, ec, bytes_transferred);
}
template <typename Handler>
void call_handler(Handler& handler,
const asio::error_code& ec,
const std::size_t& bytes_transferred) const
{
ASIO_MOVE_OR_LVALUE(Handler)(handler)(ec, bytes_transferred);
}
private:
ConstBufferSequence buffers_;
};
} // namespace detail
} // namespace ssl
} // namespace asio
#include "asio/detail/pop_options.hpp"
#endif // <API key> |
#ifndef _SPI_H_
#define _SPI_H_
#include "../lib_low_level.h"
#define SPI_DELAY_CYCLES 1
void spi_init();
u8 spib(u8 b);
void spi_block_read(u8 *buffer, u32 buffer_size);
void SPI_CS_INIT();
void SPI_CS_LOW();
void SPI_CS_HIGH();
#endif |
#include "fitz.h"
#include "mupdf.h"
/* Load or synthesize ToUnicode map for fonts */
fz_error
pdf_load_to_unicode(pdf_font_desc *font, pdf_xref *xref,
char **strings, char *collection, fz_obj *cmapstm)
{
fz_error error = fz_okay;
pdf_cmap *cmap;
int cid;
int ucsbuf[8];
int ucslen;
int i;
if (pdf_is_stream(xref, fz_to_num(cmapstm), fz_to_gen(cmapstm)))
{
error = <API key>(&cmap, xref, cmapstm);
if (error)
return fz_rethrow(error, "cannot load embedded cmap (%d %d R)", fz_to_num(cmapstm), fz_to_gen(cmapstm));
font->to_unicode = pdf_new_cmap();
for (i = 0; i < (strings ? 256 : 65536); i++)
{
cid = pdf_lookup_cmap(font->encoding, i);
if (cid >= 0)
{
ucslen = <API key>(cmap, i, ucsbuf);
if (ucslen == 1)
<API key>(font->to_unicode, cid, cid, ucsbuf[0]);
if (ucslen > 1)
pdf_map_one_to_many(font->to_unicode, cid, ucsbuf, ucslen);
}
}
pdf_sort_cmap(font->to_unicode);
pdf_drop_cmap(cmap);
}
else if (collection)
{
error = fz_okay;
if (!strcmp(collection, "Adobe-CNS1"))
error = <API key>(&font->to_unicode, "Adobe-CNS1-UCS2");
else if (!strcmp(collection, "Adobe-GB1"))
error = <API key>(&font->to_unicode, "Adobe-GB1-UCS2");
else if (!strcmp(collection, "Adobe-Japan1"))
error = <API key>(&font->to_unicode, "Adobe-Japan1-UCS2");
else if (!strcmp(collection, "Adobe-Korea1"))
error = <API key>(&font->to_unicode, "Adobe-Korea1-UCS2");
if (error)
return fz_rethrow(error, "cannot load ToUnicode system cmap %s-UCS2", collection);
}
if (strings)
{
/* TODO one-to-many mappings */
font->cid_to_ucs_len = 256;
font->cid_to_ucs = fz_calloc(256, sizeof(unsigned short));
for (i = 0; i < 256; i++)
{
if (strings[i])
font->cid_to_ucs[i] = pdf_lookup_agl(strings[i]);
else
font->cid_to_ucs[i] = '?';
}
}
if (!font->to_unicode && !font->cid_to_ucs)
{
/* TODO: synthesize a ToUnicode if it's a freetype font with
* cmap and/or post tables or if it has glyph names. */
}
return fz_okay;
} |
# <API key>: true
require 'rails_helper'
describe <API key> do
subject { described_class.new }
let!(:remote_account) { Fabricate(:account, domain: 'domain.com', username: 'foo', uri: 'https://domain.com/users/foo') }
let!(:remote_status) { Fabricate(:status, uri: 'https://domain.com/users/foo/12345', account: remote_account) }
let!(:local_status) { Fabricate(:status) }
let(:<API key>) { Fabricate(:announcement, text: "rebooting very soon, see #{ActivityPub::TagManager.instance.uri_for(remote_status)} and #{ActivityPub::TagManager.instance.uri_for(local_status)}") }
describe 'perform' do
before do
service = double
allow(<API key>).to receive(:new).and_return(service)
allow(service).to receive(:call).with('https://domain.com/users/foo/12345') { remote_status.reload }
subject.perform(<API key>.id)
end
it 'updates the linked statuses' do
expect(<API key>.reload.status_ids).to eq [remote_status.id, local_status.id]
end
end
end |
#ifndef <API key>
#define <API key>
#include "QGIViewSymbol.h"
namespace TechDraw {
class DrawViewSpreadsheet;
}
namespace TechDrawGui
{
class TechDrawGuiExport QGIViewSpreadsheet : public QGIViewSymbol
{
public:
QGIViewSpreadsheet();
~QGIViewSpreadsheet() = default;
enum {Type = QGraphicsItem::UserType + 124};
int type() const override { return Type;}
void setViewFeature(TechDraw::DrawViewSpreadsheet *obj);
};
} // end namespace TechDrawGui
#endif // <API key> |
package org.fenixedu.academic.domain.messaging;
import org.fenixedu.academic.domain.Person;
import org.fenixedu.bennu.core.domain.Bennu;
public class ForumSubscription extends <API key> {
public ForumSubscription() {
super();
setRootDomainObject(Bennu.getInstance());
<API key>(false);
setFavorite(false);
}
public ForumSubscription(Person person, Forum forum) {
this();
setPerson(person);
setForum(forum);
}
public void delete() {
setPerson(null);
setForum(null);
setRootDomainObject(null);
deleteDomainObject();
}
public void removePerson() {
super.setPerson(null);
}
public void removeForum() {
super.setForum(null);
}
} |
/ [<API key>.ts]
type T1 = {
x: T1["x"]; // Error
};
type T2<K extends "x" | "y"> = {
x: T2<K>[K]; // Error
y: number;
}
declare let x2: T2<"x">;
let x2x = x2.x;
interface T3<T extends T3<T>> {
x: T["x"];
}
interface T4<T extends T4<T>> {
x: T4<T>["x"]; // Error
}
class C1 {
x: C1["x"]; // Error
}
class C2 {
x: this["y"];
y: this["z"];
z: this["x"];
}
// Repro from #12627
interface Foo {
hello: boolean;
}
function foo<T extends Foo | T["hello"]>() {
}
/ [<API key>.js]
var x2x = x2.x;
var C1 = /** @class */ (function () {
function C1() {
}
return C1;
}());
var C2 = /** @class */ (function () {
function C2() {
}
return C2;
}());
function foo() {
}
/ [<API key>.d.ts]
declare type T1 = {
x: T1["x"];
};
declare type T2<K extends "x" | "y"> = {
x: T2<K>[K];
y: number;
};
declare let x2: T2<"x">;
declare let x2x: any;
interface T3<T extends T3<T>> {
x: T["x"];
}
interface T4<T extends T4<T>> {
x: T4<T>["x"];
}
declare class C1 {
x: C1["x"];
}
declare class C2 {
x: this["y"];
y: this["z"];
z: this["x"];
}
interface Foo {
hello: boolean;
}
declare function foo<T extends Foo | T["hello"]>(): void; |
package proguard.shrink;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.AttributeVisitor;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import java.io.PrintStream;
/**
* This ClassVisitor and MemberVisitor prints out the reasons why
* classes and class members have been marked as being used.
*
* @see UsageMarker
*
* @author Eric Lafortune
*/
public class <API key>
extends SimplifiedVisitor
implements ClassVisitor,
MemberVisitor,
AttributeVisitor
{
private final ShortestUsageMarker shortestUsageMarker;
private final boolean verbose;
private final PrintStream ps;
/**
* Creates a new UsagePrinter that prints verbosely to <code>System.out</code>.
* @param shortestUsageMarker the usage marker that was used to mark the
* classes and class members.
*/
public <API key>(ShortestUsageMarker shortestUsageMarker)
{
this(shortestUsageMarker, true);
}
/**
* Creates a new UsagePrinter that prints to the given stream.
* @param shortestUsageMarker the usage marker that was used to mark the
* classes and class members.
* @param verbose specifies whether the output should be verbose.
*/
public <API key>(ShortestUsageMarker shortestUsageMarker,
boolean verbose)
{
this(shortestUsageMarker, verbose, System.out);
}
/**
* Creates a new UsagePrinter that prints to the given stream.
* @param shortestUsageMarker the usage marker that was used to mark the
* classes and class members.
* @param verbose specifies whether the output should be verbose.
* @param printStream the stream to which to print.
*/
public <API key>(ShortestUsageMarker shortestUsageMarker,
boolean verbose,
PrintStream printStream)
{
this.shortestUsageMarker = shortestUsageMarker;
this.verbose = verbose;
this.ps = printStream;
}
// Implementations for ClassVisitor.
public void visitProgramClass(ProgramClass programClass)
{
// Print the name of this class.
ps.println(ClassUtil.externalClassName(programClass.getName()));
// Print the reason for keeping this class.
printReason(programClass);
}
public void visitLibraryClass(LibraryClass libraryClass)
{
// Print the name of this class.
ps.println(ClassUtil.externalClassName(libraryClass.getName()));
// Print the reason for keeping this class.
ps.println(" is a library class.\n");
}
// Implementations for MemberVisitor.
public void visitProgramField(ProgramClass programClass, ProgramField programField)
{
// Print the name of this field.
String name = programField.getName(programClass);
String type = programField.getDescriptor(programClass);
ps.println(ClassUtil.externalClassName(programClass.getName()) +
(verbose ?
": " + ClassUtil.<API key>(0, name, type):
"." + name));
// Print the reason for keeping this method.
printReason(programField);
}
public void visitProgramMethod(ProgramClass programClass, ProgramMethod programMethod)
{
// Print the name of this method.
String name = programMethod.getName(programClass);
String type = programMethod.getDescriptor(programClass);
ps.print(ClassUtil.externalClassName(programClass.getName()) +
(verbose ?
": " + ClassUtil.<API key>(programClass.getName(), 0, name, type):
"." + name));
programMethod.attributesAccept(programClass, this);
ps.println();
// Print the reason for keeping this method.
printReason(programMethod);
}
public void visitLibraryField(LibraryClass libraryClass, LibraryField libraryField)
{
// Print the name of this field.
String name = libraryField.getName(libraryClass);
String type = libraryField.getDescriptor(libraryClass);
ps.println(ClassUtil.externalClassName(libraryClass.getName()) +
(verbose ?
": " + ClassUtil.<API key>(0, name, type):
"." + name));
// Print the reason for keeping this field.
ps.println(" is a library field.\n");
}
public void visitLibraryMethod(LibraryClass libraryClass, LibraryMethod libraryMethod)
{
// Print the name of this method.
String name = libraryMethod.getName(libraryClass);
String type = libraryMethod.getDescriptor(libraryClass);
ps.println(ClassUtil.externalClassName(libraryClass.getName()) +
(verbose ?
": " + ClassUtil.<API key>(libraryClass.getName(), 0, name, type):
"." + name));
// Print the reason for keeping this method.
ps.println(" is a library method.\n");
}
// Implementations for AttributeVisitor.
public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute)
{
codeAttribute.attributesAccept(clazz, method, this);
}
public void <API key>(Clazz clazz, Method method, CodeAttribute codeAttribute, <API key> <API key>)
{
ps.print(" (" +
<API key>.getLowestLineNumber() + ":" +
<API key>.<API key>() + ")");
}
// Small utility methods.
private void printReason(VisitorAccepter visitorAccepter)
{
if (shortestUsageMarker.isUsed(visitorAccepter))
{
ShortestUsageMark shortestUsageMark = shortestUsageMarker.<API key>(visitorAccepter);
// Print the reason for keeping this class.
ps.print(" " + shortestUsageMark.getReason());
// Print the class or method that is responsible, with its reasons.
shortestUsageMark.acceptClassVisitor(this);
shortestUsageMark.acceptMemberVisitor(this);
}
else
{
ps.println(" is not being kept.\n");
}
}
} |
Ext.define('Ext.overrides.dom.Element', (function() {
var Element, // we cannot do this yet "= Ext.dom.Element"
WIN = window,
DOC = document,
HIDDEN = 'hidden',
ISCLIPPED = 'isClipped',
OVERFLOW = 'overflow',
OVERFLOWX = 'overflow-x',
OVERFLOWY = 'overflow-y',
ORIGINALCLIP = 'originalClip',
HEIGHT = 'height',
WIDTH = 'width',
VISIBILITY = 'visibility',
DISPLAY = 'display',
NONE = 'none',
HIDDEN = 'hidden',
OFFSETS = 'offsets',
ORIGINALDISPLAY = 'originalDisplay',
VISMODE = 'visibilityMode',
ISVISIBLE = 'isVisible',
OFFSETCLASS = Ext.baseCSSPrefix + 'hidden-offsets',
boxMarkup = [
'<div class="{0}-tl" role="presentation">',
'<div class="{0}-tr" role="presentation">',
'<div class="{0}-tc" role="presentation"></div>',
'</div>',
'</div>',
'<div class="{0}-ml" role="presentation">',
'<div class="{0}-mr" role="presentation">',
'<div class="{0}-mc" role="presentation"></div>',
'</div>',
'</div>',
'<div class="{0}-bl" role="presentation">',
'<div class="{0}-br" role="presentation">',
'<div class="{0}-bc" role="presentation"></div>',
'</div>',
'</div>'
].join(''),
scriptTagRe = /(?:<script([^>]*)?>)((\n|\r|.)*?)(?:<\/script>)/ig,
replaceScriptTagRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
srcRe = /\ssrc=([\'\"])(.*?)\1/i,
nonSpaceRe = /\S/,
typeRe = /\stype=([\'\"])(.*?)\1/i,
msRe = /^-ms-/,
camelRe = /(-[a-z])/gi,
camelReplaceFn = function(m, a) {
return a.charAt(1).toUpperCase();
},
XMASKED = Ext.baseCSSPrefix + "masked",
XMASKEDRELATIVE = Ext.baseCSSPrefix + "masked-relative",
EXTELMASKMSG = Ext.baseCSSPrefix + "mask-msg",
mouseEnterLeaveRe = /^(?:mouseenter|mouseleave)$/,
bodyRe = /^body/i,
propertyCache = {},
getDisplay = function(el) {
var data = el.getData(),
display = data[ORIGINALDISPLAY];
if (display === undefined) {
data[ORIGINALDISPLAY] = display = '';
}
return display;
},
getVisMode = function(el){
var data = el.getData(),
visMode = data[VISMODE];
if (visMode === undefined) {
data[VISMODE] = visMode = Element.VISIBILITY;
}
return visMode;
},
garbageBin,
emptyRange = DOC.createRange ? DOC.createRange() : null,
inputTags = {
INPUT: true,
TEXTAREA: true
};
return {
override: 'Ext.dom.Element',
mixins: [
'Ext.util.Animate'
],
uses: [
'Ext.dom.GarbageCollector',
'Ext.dom.Fly',
'Ext.event.publisher.MouseEnterLeave',
'Ext.fx.Manager',
'Ext.fx.Anim'
],
<API key>: false,
_init: function (E) {
Element = E; // now we can poke this into closure scope
},
statics: {
selectableCls: Ext.baseCSSPrefix + 'selectable',
unselectableCls: Ext.baseCSSPrefix + 'unselectable',
/**
* tabIndex attribute name for DOM lookups; needed in IE8 because
* it has a bug: dom.getAttribute('tabindex') will return null
* while dom.getAttribute('tabIndex') will return the actual value.
* IE9+ and all other browsers normalize attribute names to lowercase.
*
* @private
*/
<API key>: Ext.isIE8 ? 'tabIndex' : 'tabindex',
tabbableSelector: 'a[href],button,iframe,input,select,textarea,[tabindex],[contenteditable="true"]',
// Anchor and link tags are special; they are only naturally focusable (and tabbable)
// if they have href attribute, and tabbabledness is further platform/browser specific.
// Thus we check it separately in the code.
<API key>: {
BUTTON: true,
IFRAME: true,
EMBED: true,
INPUT: true,
OBJECT: true,
SELECT: true,
TEXTAREA: true,
HTML: Ext.isIE ? true : false
},
// <object> element is naturally tabbable only in IE8 and below
<API key>: {
BUTTON: true,
IFRAME: true,
INPUT: true,
SELECT: true,
TEXTAREA: true,
OBJECT: Ext.isIE8m ? true : false
},
<API key>: 'data-tabindexsaved',
<API key>: 'data-savedtabindex',
normalize: function(prop) {
if (prop === 'float') {
prop = Ext.supports.Float ? 'cssFloat' : 'styleFloat';
}
// For '-ms-foo' we need msFoo
return propertyCache[prop] || (propertyCache[prop] = prop.replace(msRe, 'ms-').replace(camelRe, camelReplaceFn));
},
getViewportHeight: function(){
return Ext.isIE9m ? DOC.documentElement.clientHeight : WIN.innerHeight;
},
getViewportWidth: function() {
return (!Ext.isStrict && !Ext.isOpera) ? document.body.clientWidth :
Ext.isIE9m ? DOC.documentElement.clientWidth : WIN.innerWidth;
}
},
/**
* Sets up event handlers to add and remove a css class when the mouse is down and then up on this element (a click effect)
* @param {String} className The class to add
* @param {Function} [testFn] A test function to execute before adding the class. The passed parameter
* will be the Element instance. If this functions returns false, the class will not be added.
* @param {Object} [scope] The scope to execute the testFn in.
* @return {Ext.dom.Element} this
*/
addClsOnClick: function(className, testFn, scope) {
var me = this,
dom = me.dom,
hasTest = Ext.isFunction(testFn);
me.on("mousedown", function() {
if (hasTest && testFn.call(scope || me, me) === false) {
return false;
}
Ext.fly(dom).addCls(className);
var d = Ext.getDoc(),
fn = function() {
Ext.fly(dom).removeCls(className);
d.removeListener("mouseup", fn);
};
d.on("mouseup", fn);
});
return me;
},
/**
* Sets up event handlers to add and remove a css class when this element has the focus
* @param {String} className The class to add
* @param {Function} [testFn] A test function to execute before adding the class. The passed parameter
* will be the Element instance. If this functions returns false, the class will not be added.
* @param {Object} [scope] The scope to execute the testFn in.
* @return {Ext.dom.Element} this
*/
addClsOnFocus: function(className, testFn, scope) {
var me = this,
dom = me.dom,
hasTest = Ext.isFunction(testFn);
me.on("focus", function() {
if (hasTest && testFn.call(scope || me, me) === false) {
return false;
}
Ext.fly(dom).addCls(className);
});
me.on("blur", function() {
Ext.fly(dom).removeCls(className);
});
return me;
},
/**
* Sets up event handlers to add and remove a css class when the mouse is over this element
* @param {String} className The class to add
* @param {Function} [testFn] A test function to execute before adding the class. The passed parameter
* will be the Element instance. If this functions returns false, the class will not be added.
* @param {Object} [scope] The scope to execute the testFn in.
* @return {Ext.dom.Element} this
*/
addClsOnOver: function(className, testFn, scope) {
var me = this,
dom = me.dom,
hasTest = Ext.isFunction(testFn);
me.hover(
function() {
if (hasTest && testFn.call(scope || me, me) === false) {
return;
}
Ext.fly(dom).addCls(className);
},
function() {
Ext.fly(dom).removeCls(className);
}
);
return me;
},
/**
* Convenience method for constructing a KeyMap
* @param {String/Number/Number[]/Object} key Either a string with the keys to listen for, the numeric key code,
* array of key codes or an object with the following options:
* @param {Number/Array} key.key
* @param {Boolean} key.shift
* @param {Boolean} key.ctrl
* @param {Boolean} key.alt
* @param {Function} fn The function to call
* @param {Object} [scope] The scope (`this` reference) in which the specified function is executed. Defaults to this Element.
* @return {Ext.util.KeyMap} The KeyMap created
*/
addKeyListener: function(key, fn, scope){
var config;
if(typeof key !== 'object' || Ext.isArray(key)){
config = {
target: this,
key: key,
fn: fn,
scope: scope
};
} else {
config = {
target: this,
key : key.key,
shift : key.shift,
ctrl : key.ctrl,
alt : key.alt,
fn: fn,
scope: scope
};
}
return new Ext.util.KeyMap(config);
},
/**
* Creates a KeyMap for this element
* @param {Object} config The KeyMap config. See {@link Ext.util.KeyMap} for more details
* @return {Ext.util.KeyMap} The KeyMap created
*/
addKeyMap: function(config) {
return new Ext.util.KeyMap(Ext.apply({
target: this
}, config));
},
/**
* @private
*/
afterAnimate: function() {
var shadow = this.shadow;
if (shadow && !shadow.disabled && !shadow.animate) {
shadow.show();
}
},
/**
* @private
*/
anchorAnimX: function(anchor) {
var xName = (anchor === 'l') ? 'right' : 'left';
this.dom.style[xName] = '0px';
},
// @private - process the passed fx configuration.
anim: function(config) {
if (!Ext.isObject(config)) {
return (config) ? {} : false;
}
var me = this,
duration = config.duration || Ext.fx.Anim.prototype.duration,
easing = config.easing || 'ease',
animConfig;
if (config.stopAnimation) {
me.stopAnimation();
}
Ext.applyIf(config, Ext.fx.Manager.getFxDefaults(me.id));
// Clear any 'paused' defaults.
Ext.fx.Manager.setFxDefaults(me.id, {
delay: 0
});
animConfig = {
// Pass the DOM reference. That's tested first so will be converted to an Ext.fx.Target fastest.
target: me.dom,
remove: config.remove,
alternate: config.alternate || false,
duration: duration,
easing: easing,
callback: config.callback,
listeners: config.listeners,
iterations: config.iterations || 1,
scope: config.scope,
block: config.block,
concurrent: config.concurrent,
delay: config.delay || 0,
paused: true,
keyframes: config.keyframes,
from: config.from || {},
to: Ext.apply({}, config)
};
Ext.apply(animConfig.to, config.to);
// Anim API properties - backward compat
delete animConfig.to.to;
delete animConfig.to.from;
delete animConfig.to.remove;
delete animConfig.to.alternate;
delete animConfig.to.keyframes;
delete animConfig.to.iterations;
delete animConfig.to.listeners;
delete animConfig.to.target;
delete animConfig.to.paused;
delete animConfig.to.callback;
delete animConfig.to.scope;
delete animConfig.to.duration;
delete animConfig.to.easing;
delete animConfig.to.concurrent;
delete animConfig.to.block;
delete animConfig.to.stopAnimation;
delete animConfig.to.delay;
return animConfig;
},
/**
* Performs custom animation on this Element.
*
* The following properties may be specified in `from`, `to`, and `keyframe` objects:
*
* - `x` - The page X position in pixels.
*
* - `y` - The page Y position in pixels
*
* - `left` - The element's CSS `left` value. Units must be supplied.
*
* - `top` - The element's CSS `top` value. Units must be supplied.
*
* - `width` - The element's CSS `width` value. Units must be supplied.
*
* - `height` - The element's CSS `height` value. Units must be supplied.
*
* - `scrollLeft` - The element's `scrollLeft` value.
*
* - `scrollTop` - The element's `scrollTop` value.
*
* - `opacity` - The element's `opacity` value. This must be a value between `0` and `1`.
*
* **Be aware** that animating an Element which is being used by an Ext Component without in some way informing the
* Component about the changed element state will result in incorrect Component behaviour. This is because the
* Component will be using the old state of the element. To avoid this problem, it is now possible to directly
* animate certain properties of Components.
*
* @param {Object} config Configuration for {@link Ext.fx.Anim}.
* Note that the {@link Ext.fx.Anim#to to} config is required.
* @return {Ext.dom.Element} this
*/
animate: function(config) {
var me = this,
animId = me.dom.id || Ext.id(me.dom),
listeners,
anim,
end;
if (!Ext.fx.Manager.hasFxBlock(animId)) {
// Bit of gymnastics here to ensure our internal listeners get bound first
if (config.listeners) {
listeners = config.listeners;
delete config.listeners;
}
if (config.internalListeners) {
config.listeners = config.internalListeners;
delete config.internalListeners;
}
end = config.autoEnd;
delete config.autoEnd;
anim = new Ext.fx.Anim(me.anim(config));
anim.on({
afteranimate: 'afterAnimate',
beforeanimate: 'beforeAnimate',
scope: me,
single: true
});
if (listeners) {
anim.on(listeners);
}
Ext.fx.Manager.queueFx(anim);
if (end) {
anim.jumpToEnd();
}
}
return me;
},
/**
* @private
*/
beforeAnimate: function() {
var shadow = this.shadow;
if (shadow && !shadow.disabled && !shadow.animate) {
shadow.hide();
}
},
/**
* Wraps the specified element with a special 9 element markup/CSS block that renders by default as
* a gray container with a gradient background, rounded corners and a 4-way shadow.
*
* This special markup is used throughout Ext when box wrapping elements ({@link Ext.button.Button},
* {@link Ext.panel.Panel} when {@link Ext.panel.Panel#frame frame=true}, {@link Ext.window.Window}).
* The markup is of this form:
*
* <div class="{0}-tl"><div class="{0}-tr"><div class="{0}-tc"></div></div></div>
* <div class="{0}-ml"><div class="{0}-mr"><div class="{0}-mc"></div></div></div>
* <div class="{0}-bl"><div class="{0}-br"><div class="{0}-bc"></div></div></div>
*
* Example usage:
*
* // Basic box wrap
* Ext.get("foo").boxWrap();
*
* // You can also add a custom class and use CSS inheritance rules to customize the box look.
* // 'x-box-blue' is a built-in alternative -- look at the related CSS definitions as an example
* // for how to create a custom box wrap style.
* Ext.get("foo").boxWrap().addCls("x-box-blue");
*
* @param {String} [class='x-box'] A base CSS class to apply to the containing wrapper element.
* Note that there are a number of CSS rules that are dependent on this name to make the overall effect work,
* so if you supply an alternate base class, make sure you also supply all of the necessary rules.
* @return {Ext.dom.Element} The outermost wrapping element of the created box structure.
*/
boxWrap: function(cls) {
cls = cls || Ext.baseCSSPrefix + 'box';
var el = Ext.get(this.insertHtml("beforeBegin", "<div class='" + cls + "' role='presentation'>" + Ext.String.format(boxMarkup, cls) + "</div>"));
el.selectNode('.' + cls + '-mc').appendChild(this.dom);
return el;
},
/**
* Removes Empty, or whitespace filled text nodes. Combines adjacent text nodes.
* @param {Boolean} [forceReclean=false] By default the element keeps track if it has been cleaned already
* so you can call this over and over. However, if you update the element and need to force a reclean, you
* can pass true.
*/
clean: function(forceReclean) {
var me = this,
dom = me.dom,
data = me.getData(),
n = dom.firstChild,
ni = -1,
nx;
if (data.isCleaned && forceReclean !== true) {
return me;
}
while (n) {
nx = n.nextSibling;
if (n.nodeType === 3) {
// Remove empty/whitespace text nodes
if (!(nonSpaceRe.test(n.nodeValue))) {
dom.removeChild(n);
// Combine adjacent text nodes
} else if (nx && nx.nodeType === 3) {
n.appendData(Ext.String.trim(nx.data));
dom.removeChild(nx);
nx = n.nextSibling;
n.nodeIndex = ++ni;
}
} else {
// Recursively clean
Ext.fly(n, '_clean').clean();
n.nodeIndex = ++ni;
}
n = nx;
}
data.isCleaned = true;
return me;
},
/**
* Emptys this element. Removes all child nodes.
*/
empty: emptyRange ? function() {
var dom = this.dom;
if (dom.firstChild) {
emptyRange.setStartBefore(dom.firstChild);
emptyRange.setEndAfter(dom.lastChild);
emptyRange.deleteContents();
}
} : function() {
var dom = this.dom;
while (dom.lastChild) {
dom.removeChild(dom.lastChild);
}
},
clearListeners: function() {
this.removeAnchor();
this.callParent();
},
/**
* Clears positioning back to the default when the document was loaded.
* @param {String} [value=''] The value to use for the left, right, top, bottom.
* You could use 'auto'.
* @return {Ext.dom.Element} this
*/
clearPositioning: function(value) {
value = value || '';
return this.setStyle({
left : value,
right : value,
top : value,
bottom : value,
'z-index' : '',
position : 'static'
});
},
/**
* Creates a proxy element of this element
* @param {String/Object} config The class name of the proxy element or a DomHelper config object
* @param {String/HTMLElement} [renderTo] The element or element id to render the proxy to. Defaults to: document.body.
* @param {Boolean} [matchBox=false] True to align and size the proxy to this element now.
* @return {Ext.dom.Element} The new proxy element
*/
createProxy: function(config, renderTo, matchBox) {
config = (typeof config === 'object') ? config :
{ tag: "div", role: 'presentation', cls: config };
var me = this,
proxy = renderTo ? Ext.DomHelper.append(renderTo, config, true) :
Ext.DomHelper.insertBefore(me.dom, config, true);
proxy.setVisibilityMode(Element.DISPLAY);
proxy.hide();
if (matchBox && me.setBox && me.getBox) { // check to make sure Element_position.js is loaded
proxy.setBox(me.getBox());
}
return proxy;
},
/**
* Clears any opacity settings from this element. Required in some cases for IE.
* @return {Ext.dom.Element} this
*/
clearOpacity: function() {
return this.setOpacity('');
},
/**
* Store the current overflow setting and clip overflow on the element - use {@link #unclip} to remove
* @return {Ext.dom.Element} this
*/
clip: function() {
var me = this,
data = me.getData(),
style;
if (!data[ISCLIPPED]) {
data[ISCLIPPED] = true;
style = me.getStyle([OVERFLOW, OVERFLOWX, OVERFLOWY]);
data[ORIGINALCLIP] = {
o: style[OVERFLOW],
x: style[OVERFLOWX],
y: style[OVERFLOWY]
};
me.setStyle(OVERFLOW, HIDDEN);
me.setStyle(OVERFLOWX, HIDDEN);
me.setStyle(OVERFLOWY, HIDDEN);
}
return me;
},
destroy: function() {
var me = this,
dom = me.dom,
data = me.getData(),
maskEl, maskMsg;
if (dom && me.isAnimate) {
me.stopAnimation();
}
me.callParent();
//<feature legacyBrowser>
// prevent memory leaks in IE8
// must not be document, documentElement, body or window object
// Have to use != instead of !== for IE8 or it will not recognize that the window
// objects are equal
if (dom && Ext.isIE8 && (dom.window != dom) && (dom.nodeType !== 9) &&
(dom.tagName !== 'BODY') && (dom.tagName !== 'HTML')) {
garbageBin = garbageBin || DOC.createElement('div');
garbageBin.appendChild(dom);
garbageBin.innerHTML = '';
}
//</feature>
if (data) {
maskEl = data.maskEl;
maskMsg = data.maskMsg;
if (maskEl) {
maskEl.destroy();
}
if (maskMsg) {
maskMsg.destroy();
}
}
},
/**
* Convenience method for setVisibilityMode(Element.DISPLAY).
* @param {String} [display] What to set display to when visible
* @return {Ext.dom.Element} this
*/
enableDisplayMode : function(display) {
var me = this;
me.setVisibilityMode(Element.DISPLAY);
if (display !== undefined) {
me.getData()[ORIGINALDISPLAY] = display;
}
return me;
},
/**
* Fade an element in (from transparent to opaque). The ending opacity can be specified using the `opacity`
* config option. Usage:
*
* // default: fade in from opacity 0 to 100%
* el.fadeIn();
*
* // custom: fade in from opacity 0 to 75% over 2 seconds
* el.fadeIn({ opacity: .75, duration: 2000});
*
* // common config options shown with default values
* el.fadeIn({
* opacity: 1, //can be any value between 0 and 1 (e.g. .5)
* easing: 'easeOut',
* duration: 500
* });
*
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
fadeIn: function(o) {
var me = this,
dom = me.dom;
me.animate(Ext.apply({}, o, {
opacity: 1,
internalListeners: {
beforeanimate: function(anim){
// restore any visibility/display that may have
// been applied by a fadeout animation
var el = Ext.fly(dom, '_anim');
if (el.isStyle('display', 'none')) {
el.setDisplayed('');
} else {
el.show();
}
}
}
}));
return this;
},
/**
* Fade an element out (from opaque to transparent). The ending opacity can be specified using the `opacity`
* config option. Note that IE may require `useDisplay:true` in order to redisplay correctly.
* Usage:
*
* // default: fade out from the element's current opacity to 0
* el.fadeOut();
*
* // custom: fade out from the element's current opacity to 25% over 2 seconds
* el.fadeOut({ opacity: .25, duration: 2000});
*
* // common config options shown with default values
* el.fadeOut({
* opacity: 0, //can be any value between 0 and 1 (e.g. .5)
* easing: 'easeOut',
* duration: 500,
* remove: false,
* useDisplay: false
* });
*
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
fadeOut: function(o) {
var me = this,
dom = me.dom;
o = Ext.apply({
opacity: 0,
internalListeners: {
afteranimate: function(anim){
if (dom && anim.to.opacity === 0) {
var el = Ext.fly(dom, '_anim');
if (o.useDisplay) {
el.setDisplayed(false);
} else {
el.hide();
}
}
}
}
}, o);
me.animate(o);
return me;
},
// private
fixDisplay: function(){
var me = this;
if (me.isStyle(DISPLAY, NONE)) {
me.setStyle(VISIBILITY, HIDDEN);
me.setStyle(DISPLAY, getDisplay(me)); // first try reverting to default
if (me.isStyle(DISPLAY, NONE)) { // if that fails, default to block
me.setStyle(DISPLAY, "block");
}
}
},
/**
* Shows a ripple of exploding, attenuating borders to draw attention to an Element. Usage:
*
* // default: a single light blue ripple
* el.frame();
*
* // custom: 3 red ripples lasting 3 seconds total
* el.frame("#ff0000", 3, { duration: 3000 });
*
* // common config options shown with default values
* el.frame("#C3DAF9", 1, {
* duration: 1000 // duration of each individual ripple.
* // Note: Easing is not configurable and will be ignored if included
* });
*
* @param {String} [color='#C3DAF9'] The hex color value for the border.
* @param {Number} [count=1] The number of ripples to display.
* @param {Object} [options] Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
frame: function(color, count, obj){
var me = this,
dom = me.dom,
beforeAnim;
color = color || '#C3DAF9';
count = count || 1;
obj = obj || {};
beforeAnim = function() {
var el = Ext.fly(dom, '_anim'),
animScope = this,
box,
proxy, proxyAnim;
el.show();
box = el.getBox();
proxy = Ext.getBody().createChild({
role: 'presentation',
id: el.dom.id + '-anim-proxy',
style: {
position : 'absolute',
'pointer-events': 'none',
'z-index': 35000,
border : '0px solid ' + color
}
});
proxyAnim = new Ext.fx.Anim({
target: proxy,
duration: obj.duration || 1000,
iterations: count,
from: {
top: box.y,
left: box.x,
borderWidth: 0,
opacity: 1,
height: box.height,
width: box.width
},
to: {
top: box.y - 20,
left: box.x - 20,
borderWidth: 10,
opacity: 0,
height: box.height + 40,
width: box.width + 40
}
});
proxyAnim.on('afteranimate', function() {
proxy.destroy();
// kill the no-op element animation created below
animScope.end();
});
};
me.animate({
// See "A Note About Wrapped Animations" at the top of this class:
duration: (Math.max(obj.duration, 500) * 2) || 2000,
listeners: {
beforeanimate: {
fn: beforeAnim
}
},
callback: obj.callback,
scope: obj.scope
});
return me;
},
/**
* Return the CSS color for the specified CSS attribute. rgb, 3 digit (like `#fff`)
* and valid values are convert to standard 6 digit hex color.
* @param {String} attr The css attribute
* @param {String} defaultValue The default value to use when a valid color isn't found
* @param {String} [prefix] defaults to #. Use an empty string when working with
* color anims.
* @private
*/
getColor: function(attr, defaultValue, prefix) {
var v = this.getStyle(attr),
color = prefix || prefix === '' ? prefix : '
h, len, i=0;
if (!v || (/transparent|inherit/.test(v))) {
return defaultValue;
}
if (/^r/.test(v)) {
v = v.slice(4, v.length - 1).split(',');
len = v.length;
for (; i<len; i++) {
h = parseInt(v[i], 10);
color += (h < 16 ? '0' : '') + h.toString(16);
}
} else {
v = v.replace('
color += v.length === 3 ? v.replace(/^(\w)(\w)(\w)$/, '$1$1$2$2$3$3') : v;
}
return(color.length > 5 ? color.toLowerCase() : defaultValue);
},
/**
* Gets this element's {@link Ext.ElementLoader ElementLoader}
* @return {Ext.ElementLoader} The loader
*/
getLoader: function() {
var me = this,
data = me.getData(),
loader = data.loader;
if (!loader) {
data.loader = loader = new Ext.ElementLoader({
target: me
});
}
return loader;
},
/**
* Gets an object with all CSS positioning properties. Useful along with
* #setPostioning to get snapshot before performing an update and then restoring
* the element.
* @param {Boolean} [autoPx=false] true to return pixel values for "auto" styles.
* @return {Object}
*/
getPositioning: function(autoPx){
var styles = this.getStyle(['left', 'top', 'position', 'z-index']),
dom = this.dom;
if(autoPx) {
if(styles.left === 'auto') {
styles.left = dom.offsetLeft + 'px';
}
if(styles.top === 'auto') {
styles.top = dom.offsetTop + 'px';
}
}
return styles;
},
/**
* Slides the element while fading it out of view. An anchor point can be optionally passed to set the ending point
* of the effect. Usage:
*
* // default: slide the element downward while fading out
* el.ghost();
*
* // custom: slide the element out to the right with a 2-second duration
* el.ghost('r', { duration: 2000 });
*
* // common config options shown with default values
* el.ghost('b', {
* easing: 'easeOut',
* duration: 500
* });
*
* @param {String} anchor (optional) One of the valid {@link Ext.fx.Anim} anchor positions (defaults to bottom: 'b')
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
ghost: function(anchor, obj) {
var me = this,
dom = me.dom,
beforeAnim;
anchor = anchor || "b";
beforeAnim = function() {
var el = Ext.fly(dom, '_anim'),
width = el.getWidth(),
height = el.getHeight(),
xy = el.getXY(),
position = el.getPositioning(),
to = {
opacity: 0
};
switch (anchor) {
case 't':
to.y = xy[1] - height;
break;
case 'l':
to.x = xy[0] - width;
break;
case 'r':
to.x = xy[0] + width;
break;
case 'b':
to.y = xy[1] + height;
break;
case 'tl':
to.x = xy[0] - width;
to.y = xy[1] - height;
break;
case 'bl':
to.x = xy[0] - width;
to.y = xy[1] + height;
break;
case 'br':
to.x = xy[0] + width;
to.y = xy[1] + height;
break;
case 'tr':
to.x = xy[0] + width;
to.y = xy[1] - height;
break;
}
this.to = to;
this.on('afteranimate', function () {
var el = Ext.fly(dom, '_anim');
if (el) {
el.hide();
el.clearOpacity();
el.setPositioning(position);
}
});
};
me.animate(Ext.applyIf(obj || {}, {
duration: 500,
easing: 'ease-out',
listeners: {
beforeanimate: beforeAnim
}
}));
return me;
},
/**
* @override
* Hide this element - Uses display mode to determine whether to use "display",
* "visibility", or "offsets". See {@link #setVisible}.
* @param {Boolean/Object} [animate] true for the default animation or a standard
* Element animation config object
* @return {Ext.dom.Element} this
*/
hide: function(animate){
// hideMode override
if (typeof animate === 'string'){
this.setVisible(false, animate);
return this;
}
this.setVisible(false, this.anim(animate));
return this;
},
/**
* Highlights the Element by setting a color (applies to the background-color by default, but can be changed using
* the "attr" config option) and then fading back to the original color. If no original color is available, you
* should provide the "endColor" config option which will be cleared after the animation. Usage:
*
* // default: highlight background to yellow
* el.highlight();
*
* // custom: highlight foreground text to blue for 2 seconds
* el.highlight("0000ff", { attr: 'color', duration: 2000 });
*
* // common config options shown with default values
* el.highlight("ffff9c", {
* attr: "backgroundColor", //can be any valid CSS property (attribute) that supports a color value
* endColor: (current color) or "ffffff",
* easing: 'easeIn',
* duration: 1000
* });
*
* @param {String} color (optional) The highlight color. Should be a 6 char hex color without the leading #
* (defaults to yellow: 'ffff9c')
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
highlight: function(color, o) {
var me = this,
dom = me.dom,
from = {},
restore, to, attr, lns, event, fn;
o = o || {};
lns = o.listeners || {};
attr = o.attr || 'backgroundColor';
from[attr] = color || 'ffff9c';
if (!o.to) {
to = {};
to[attr] = o.endColor || me.getColor(attr, 'ffffff', '');
}
else {
to = o.to;
}
// Don't apply directly on lns, since we reference it in our own callbacks below
o.listeners = Ext.apply(Ext.apply({}, lns), {
beforeanimate: function() {
restore = dom.style[attr];
var el = Ext.fly(dom, '_anim');
el.clearOpacity();
el.show();
event = lns.beforeanimate;
if (event) {
fn = event.fn || event;
return fn.apply(event.scope || lns.scope || WIN, arguments);
}
},
afteranimate: function() {
if (dom) {
dom.style[attr] = restore;
}
event = lns.afteranimate;
if (event) {
fn = event.fn || event;
fn.apply(event.scope || lns.scope || WIN, arguments);
}
}
});
me.animate(Ext.apply({}, o, {
duration: 1000,
easing: 'ease-in',
from: from,
to: to
}));
return me;
},
/**
* Sets up event handlers to call the passed functions when the mouse is moved into and out of the Element.
* @param {Function} overFn The function to call when the mouse enters the Element.
* @param {Function} outFn The function to call when the mouse leaves the Element.
* @param {Object} [scope] The scope (`this` reference) in which the functions are executed. Defaults
* to the Element's DOM element.
* @param {Object} [options] Options for the listener. See {@link Ext.util.Observable#addListener the
* options parameter}.
* @return {Ext.dom.Element} this
*/
hover: function(overFn, outFn, scope, options) {
var me = this;
me.on('mouseenter', overFn, scope || me.dom, options);
me.on('mouseleave', outFn, scope || me.dom, options);
return me;
},
/**
* Initializes a {@link Ext.dd.DD} drag drop object for this element.
* @param {String} group The group the DD object is member of
* @param {Object} config The DD config object
* @param {Object} overrides An object containing methods to override/implement on the DD object
* @return {Ext.dd.DD} The DD object
*/
initDD: function(group, config, overrides){
var dd = new Ext.dd.DD(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
},
/**
* Initializes a {@link Ext.dd.DDProxy} object for this element.
* @param {String} group The group the DDProxy object is member of
* @param {Object} config The DDProxy config object
* @param {Object} overrides An object containing methods to override/implement on the DDProxy object
* @return {Ext.dd.DDProxy} The DDProxy object
*/
initDDProxy: function(group, config, overrides){
var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
},
/**
* Initializes a {@link Ext.dd.DDTarget} object for this element.
* @param {String} group The group the DDTarget object is member of
* @param {Object} config The DDTarget config object
* @param {Object} overrides An object containing methods to override/implement on the DDTarget object
* @return {Ext.dd.DDTarget} The DDTarget object
*/
initDDTarget: function(group, config, overrides){
var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config);
return Ext.apply(dd, overrides);
},
/**
* Checks whether this element can be focused programmatically or by clicking.
* To check if an element is in the document tab flow, use {@link #isTabbable}.
*
* @return {Boolean} True if the element is focusable
*/
isFocusable: function() {
var dom = this.dom,
focusable = false,
nodeName;
if (dom && !dom.disabled) {
nodeName = dom.nodeName;
/*
* An element is focusable if:
* - It is naturally focusable, or
* - It is an anchor or link with href attribute, or
* - It has a tabIndex, or
* - It is an editing host (contenteditable="true")
*
* Also note that we can't check dom.tabIndex because IE will return 0
* for elements that have no tabIndex attribute defined, regardless of
* whether they are naturally focusable or not.
*/
focusable = !!Ext.Element.<API key>[nodeName] ||
((nodeName === 'A' || nodeName === 'LINK') && !!dom.href) ||
dom.getAttribute('tabindex') != null ||
dom.contentEditable === 'true';
// In IE8, <input type="hidden"> does not have a corresponding style
// so isVisible() will assume that it's not hidden.
if (Ext.isIE8 && nodeName === 'INPUT' && dom.type === 'hidden') {
focusable = false;
}
// Invisible elements cannot be focused, so check that as well
focusable = focusable && this.isVisible(true);
}
return focusable;
},
/**
* Returns `true` if this Element is an input field, or is editable in any way.
* @returns {Boolean} `true` if this Element is an input field, or is editable in any way.
*/
isInputField: function() {
var dom = this.dom,
contentEditable = dom.contentEditable;
// contentEditable will default to inherit if not specified, only check if the
// attribute has been set or explicitly set to true
// Also skip <input> tags of type="button", we use them for checkboxes
// and radio buttons
if ((inputTags[dom.tagName] && dom.type !== 'button') ||
(contentEditable === '' || contentEditable === 'true')) {
return true;
}
return false;
},
/**
* Checks whether this element participates in the sequential focus navigation,
* and can be reached by using Tab key.
*
* @return {Boolean} True if the element is tabbable.
*/
isTabbable: function() {
var dom = this.dom,
tabbable = false,
nodeName, hasIndex, tabIndex;
if (dom && !dom.disabled) {
nodeName = dom.nodeName;
// Can't use dom.tabIndex here because IE will return 0 for elements
// that have no tabindex attribute defined, regardless of whether they are
// naturally tabbable or not.
tabIndex = dom.getAttribute('tabindex');
hasIndex = tabIndex != null;
tabIndex -= 0;
// Anchors and links are only naturally tabbable if they have href attribute
// See http://www.w3.org/TR/html5/editing.html#specially-focusable
if (nodeName === 'A' || nodeName === 'LINK') {
if (dom.href) {
// It is also possible to make an anchor untabbable by setting
// tabIndex < 0 on it
tabbable = hasIndex && tabIndex < 0 ? false : true;
}
// Anchor w/o href is tabbable if it has tabIndex >= 0,
// or if it's editable
else {
if (dom.contentEditable === 'true') {
tabbable = !hasIndex || (hasIndex && tabIndex >= 0) ? true : false;
}
else {
tabbable = hasIndex && tabIndex >= 0 ? true : false;
}
}
}
// If an element has contenteditable="true" or is naturally tabbable,
// then it is a potential candidate unless its tabIndex is < 0.
else if (dom.contentEditable === 'true' ||
Ext.Element.<API key>[nodeName]) {
tabbable = hasIndex && tabIndex < 0 ? false : true;
}
// That leaves non-editable elements that can only be made tabbable
// by slapping tabIndex >= 0 on them
else {
if (hasIndex && tabIndex >= 0) {
tabbable = true;
}
}
// In IE8, <input type="hidden"> does not have a corresponding style
// so isVisible() will assume that it's not hidden.
if (Ext.isIE8 && nodeName === 'INPUT' && dom.type === 'hidden') {
tabbable = false;
}
// Invisible elements can't be tabbed into. If we have a component ref
// we'll also check if the component itself is visible before incurring
// the expense of DOM style reads.
tabbable = tabbable &&
(!this.component || this.component.isVisible(true)) &&
this.isVisible(true);
}
return tabbable;
},
/**
* Returns true if this element is masked. Also re-centers any displayed message
* within the mask.
*
* @param {Boolean} [deep] Go up the DOM hierarchy to determine if any parent
* element is masked.
*
* @return {Boolean}
*/
isMasked: function(deep) {
var me = this,
data = me.getData(),
maskEl = data.maskEl,
maskMsg = data.maskMsg,
hasMask = false,
parent;
if (maskEl && maskEl.isVisible()) {
if (maskMsg) {
maskMsg.center(me);
}
hasMask = true;
}
else if (deep) {
parent = me.findParentNode();
if (parent) {
return Ext.fly(parent).isMasked(deep);
}
}
return hasMask;
},
/**
* Returns true if this element is scrollable.
* @return {Boolean}
*/
isScrollable: function() {
var dom = this.dom;
return dom.scrollHeight > dom.clientHeight || dom.scrollWidth > dom.clientWidth;
},
/**
* Direct access to the Ext.ElementLoader {@link Ext.ElementLoader#method-load} method.
* The method takes the same object parameter as {@link Ext.ElementLoader#method-load}
* @param {Object} options a options object for Ext.ElementLoader {@link Ext.ElementLoader#method-load}
* @return {Ext.dom.Element} this
*/
load: function(options) {
this.getLoader().load(options);
return this;
},
/**
* Puts a mask over this element to disable user interaction.
* This method can only be applied to elements which accept child nodes. Use
* {@link #unmask} to remove the mask.
*
* @param {String} [msg] A message to display in the mask
* @param {String} [msgCls] A css class to apply to the msg element
* @return {Ext.dom.Element} The mask element
*/
mask: function (msg, msgCls /* private - passed by AbstractComponent.mask to avoid the need to interrogate the DOM to get the height*/, elHeight) {
var me = this,
dom = me.dom,
data = me.getData(),
maskEl = data.maskEl,
maskMsg;
if (!(bodyRe.test(dom.tagName) && me.getStyle('position') === 'static')) {
me.addCls(XMASKEDRELATIVE);
}
// We always needs to recreate the mask since the DOM element may have been re-created
if (maskEl) {
maskEl.destroy();
}
maskEl = Ext.DomHelper.append(dom, {
role: 'presentation',
cls : Ext.baseCSSPrefix + "mask " + Ext.baseCSSPrefix + "border-box",
children: {
role: 'presentation',
cls : msgCls ? EXTELMASKMSG + " " + msgCls : EXTELMASKMSG,
cn : {
tag: 'div',
role: 'presentation',
cls: Ext.baseCSSPrefix + 'mask-msg-inner',
cn: {
tag: 'div',
role: 'presentation',
cls: Ext.baseCSSPrefix + 'mask-msg-text',
html: msg || ''
}
}
}
}, true);
maskMsg = Ext.get(maskEl.dom.firstChild);
data.maskEl = maskEl;
me.addCls(XMASKED);
maskEl.setDisplayed(true);
if (typeof msg === 'string') {
maskMsg.setDisplayed(true);
maskMsg.center(me);
} else {
maskMsg.setDisplayed(false);
}
// When masking the body, don't touch its tabbable state
if (dom === DOC.body) {
maskEl.addCls(Ext.baseCSSPrefix + 'mask-fixed');
}
else {
me.saveTabbableState();
}
me.<API key>();
// ie will not expand full height automatically
if (Ext.isIE9m && dom !== DOC.body && me.isStyle('height', 'auto')) {
maskEl.setSize(undefined, elHeight || me.getHeight());
}
return maskEl;
},
/**
* Monitors this Element for the mouse leaving. Calls the function after the specified delay only if
* the mouse was not moved back into the Element within the delay. If the mouse *was* moved
* back in, the function is not called.
* @param {Number} delay The delay **in milliseconds** to wait for possible mouse re-entry before calling the handler function.
* @param {Function} handler The function to call if the mouse remains outside of this Element for the specified time.
* @param {Object} [scope] The scope (`this` reference) in which the handler function executes. Defaults to this Element.
* @return {Object} The listeners object which was added to this element so that monitoring can be stopped. Example usage:
*
* // Hide the menu if the mouse moves out for 250ms or more
* this.mouseLeaveMonitor = this.menuEl.monitorMouseLeave(250, this.hideMenu, this);
*
* ...
* // Remove mouseleave monitor on menu destroy
* this.menuEl.un(this.mouseLeaveMonitor);
*
*/
monitorMouseLeave: function(delay, handler, scope) {
var me = this,
timer,
listeners = {
mouseleave: function(e) {
//<feature legacyBrowser>
if (Ext.isIE9m) {
e.enableIEAsync();
}
//</feature>
timer = Ext.defer(handler, delay, scope || me, [e]);
},
mouseenter: function() {
clearTimeout(timer);
}
};
me.on(listeners);
return listeners;
},
/**
* Fades the element out while slowly expanding it in all directions. When the effect is completed, the element will
* be hidden (visibility = 'hidden') but block elements will still take up space in the document. Usage:
*
* // default
* el.puff();
*
* // common config options shown with default values
* el.puff({
* easing: 'easeOut',
* duration: 500,
* useDisplay: false
* });
*
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
puff: function(obj) {
var me = this,
dom = me.dom,
beforeAnim,
box = me.getBox(),
originalStyles = me.getStyle(['width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index', 'font-size', 'opacity'], true);
obj = Ext.applyIf(obj || {}, {
easing: 'ease-out',
duration: 500,
useDisplay: false
});
beforeAnim = function() {
var el = Ext.fly(dom, '_anim');
el.clearOpacity();
el.show();
this.to = {
width: box.width * 2,
height: box.height * 2,
x: box.x - (box.width / 2),
y: box.y - (box.height /2),
opacity: 0,
fontSize: '200%'
};
this.on('afteranimate',function() {
var el = Ext.fly(dom, '_anim');
if (el) {
if (obj.useDisplay) {
el.setDisplayed(false);
} else {
el.hide();
}
el.setStyle(originalStyles);
Ext.callback(obj.callback, obj.scope);
}
});
};
me.animate({
duration: obj.duration,
easing: obj.easing,
listeners: {
beforeanimate: {
fn: beforeAnim
}
}
});
return me;
},
/**
* Enable text selection for this element (normalized across browsers)
* @return {Ext.dom.Element} this
*/
selectable: function() {
var me = this;
// We clear this property for all browsers, not just Opera. This is so that rendering templates don't need to
// condition on Opera when making elements unselectable.
me.dom.unselectable = '';
me.removeCls(Element.unselectableCls);
me.addCls(Element.selectableCls);
return me;
},
//<feature legacyBrowser>
// private
// used to ensure the mouseup event is captured if it occurs outside of the
// window in IE9m. The only reason this method exists, (vs just calling
// el.dom.setCapture() directly) is so that we can override it to emptyFn
// during testing because setCapture() can wreak havoc on emulated mouse events
setCapture: function() {
var dom = this.dom;
if (Ext.isIE9m && dom.setCapture) {
dom.setCapture();
}
},
//</feature>
/**
* Sets the CSS display property. Uses originalDisplay if the specified value is a
* boolean true.
* @param {Boolean/String} value Boolean value to display the element using its
* default display, or a string to set the display directly.
* @return {Ext.dom.Element} this
*/
setDisplayed: function(value) {
var me = this;
if (typeof value === "boolean"){
value = value ? getDisplay(me) : NONE;
}
me.setStyle(DISPLAY, value);
if (me.shadow || me.shim) {
me.setUnderlaysVisible(value !== NONE);
}
return me;
},
/**
* Set the height of this Element.
*
* // change the height to 200px and animate with default configuration
* Ext.fly('elementId').setHeight(200, true);
*
* // change the height to 150px and animate with a custom configuration
* Ext.fly('elId').setHeight(150, {
* duration : 500, // animation will have a duration of .5 seconds
* // will change the content to "finished"
* callback: function(){ this.{@link #setHtml}("finished"); }
* });
*
* @param {Number/String} height The new height. This may be one of:
*
* - A Number specifying the new height in pixels.
* - A String used to set the CSS height style. Animation may **not** be used.
*
* @param {Boolean/Object} [animate] a standard Element animation config object or `true` for
* the default animation (`{duration: 350, easing: 'ease-in'}`)
* @return {Ext.dom.Element} this
*/
setHeight: function(height, animate) {
var me = this;
if (!animate || !me.anim) {
me.callParent(arguments);
}
else {
if (!Ext.isObject(animate)) {
animate = {};
}
me.animate(Ext.applyIf({
to: {
height: height
}
}, animate));
}
return me;
},
/**
* Removes "vertical" state from this element (reverses everything done
* by {@link #setVertical}).
* @private
*/
setHorizontal: function() {
var me = this,
cls = me.verticalCls;
delete me.vertical;
if (cls) {
delete me.verticalCls;
me.removeCls(cls);
}
// delete the inverted methods and revert to inheriting from the prototype
delete me.setWidth;
delete me.setHeight;
if (!Ext.isIE8) {
delete me.getWidth;
delete me.getHeight;
}
// revert to inheriting styleHooks from the prototype
delete me.styleHooks;
},
/**
* Updates the *text* value of this element.
* Replaces the content of this element with a *single text node* containing the passed text.
* @param {String} text The text to display in this Element.
*/
updateText: function(text) {
var me = this,
dom,
textNode;
if (dom) {
textNode = dom.firstChild;
if (!textNode || (textNode.nodeType !== 3 || textNode.nextSibling)) {
textNode = DOC.createTextNode();
me.empty();
dom.appendChild(textNode);
}
if (text) {
textNode.data = text;
}
}
},
/**
* Updates the innerHTML of this element, optionally searching for and processing scripts.
* @param {String} html The new HTML
* @param {Boolean} [loadScripts] True to look for and process scripts (defaults to false)
* @param {Function} [callback] For async script loading you can be notified when the update completes
* @return {Ext.dom.Element} this
*/
setHtml: function(html, loadScripts, callback) {
var me = this,
id,
dom,
interval;
if (!me.dom) {
return me;
}
html = html || '';
dom = me.dom;
if (loadScripts !== true) {
dom.innerHTML = html;
Ext.callback(callback, me);
return me;
}
id = Ext.id();
html += '<span id="' + id + '" role="presentation"></span>';
interval = Ext.interval(function() {
var hd,
match,
attrs,
srcMatch,
typeMatch,
el,
s;
if (!(el = DOC.getElementById(id))) {
return false;
}
clearInterval(interval);
Ext.removeNode(el);
hd = Ext.getHead().dom;
while ((match = scriptTagRe.exec(html))) {
attrs = match[1];
srcMatch = attrs ? attrs.match(srcRe) : false;
if (srcMatch && srcMatch[2]) {
s = DOC.createElement("script");
s.src = srcMatch[2];
typeMatch = attrs.match(typeRe);
if (typeMatch && typeMatch[2]) {
s.type = typeMatch[2];
}
hd.appendChild(s);
} else if (match[2] && match[2].length > 0) {
if (WIN.execScript) {
WIN.execScript(match[2]);
} else {
WIN.eval(match[2]);
}
}
}
Ext.callback(callback, me);
}, 20);
dom.innerHTML = html.replace(replaceScriptTagRe, '');
return me;
},
/**
* Set the opacity of the element
* @param {Number} opacity The new opacity. 0 = transparent, .5 = 50% visibile, 1 = fully visible, etc
* @param {Boolean/Object} [animate] a standard Element animation config object or `true` for
* the default animation (`{duration: 350, easing: 'ease-in'}`)
* @return {Ext.dom.Element} this
*/
setOpacity: function(opacity, animate) {
var me = this;
if (!me.dom) {
return me;
}
if (!animate || !me.anim) {
me.setStyle('opacity', opacity);
}
else {
if (typeof animate != 'object') {
animate = {
duration: 350,
easing: 'ease-in'
};
}
me.animate(Ext.applyIf({
to: {
opacity: opacity
}
}, animate));
}
return me;
},
/**
* Set positioning with an object returned by #getPositioning.
* @param {Object} posCfg
* @return {Ext.dom.Element} this
*/
setPositioning: function(pc) {
return this.setStyle(pc);
},
/**
* Changes this Element's state to "vertical" (rotated 90 or 270 degrees).
* This involves inverting the getters and setters for height and width,
* and applying hooks for rotating getters and setters for border/margin/padding.
* (getWidth becomes getHeight and vice versa), setStyle and getStyle will
* also return the inverse when height or width are being operated on.
*
* @param {Number} angle the angle of rotation - either 90 or 270
* @param {String} cls an optional css class that contains the required
* styles for switching the element to vertical orientation. Omit this if
* the element already contains vertical styling. If cls is provided,
* it will be removed from the element when {@link #setHorizontal} is called.
* @private
*/
setVertical: function(angle, cls) {
var me = this,
proto = Element.prototype;
me.vertical = true;
if (cls) {
me.addCls(me.verticalCls = cls);
}
me.setWidth = proto.setHeight;
me.setHeight = proto.setWidth;
if (!Ext.isIE8) {
// In browsers that use CSS3 transforms we must invert getHeight and
// get Width. In IE8 no adjustment is needed because we use
// a BasicImage filter to rotate the element and the element's
// offsetWidth and offsetHeight are automatically inverted.
me.getWidth = proto.getHeight;
me.getHeight = proto.getWidth;
}
// Switch to using the appropriate vertical style hooks
me.styleHooks = (angle === 270) ?
proto.<API key> : proto.<API key>;
},
/**
* Set the size of this Element. If animation is true, both width and height will be animated concurrently.
* @param {Number/String} width The new width. This may be one of:
*
* - A Number specifying the new width in pixels.
* - A String used to set the CSS width style. Animation may **not** be used.
* - A size object in the format `{width: widthValue, height: heightValue}`.
*
* @param {Number/String} height The new height. This may be one of:
*
* - A Number specifying the new height in pixels.
* - A String used to set the CSS height style. Animation may **not** be used.
*
* @param {Boolean/Object} [animate] a standard Element animation config object or `true` for
* the default animation (`{duration: 350, easing: 'ease-in'}`)
*
* @return {Ext.dom.Element} this
*/
setSize: function(width, height, animate) {
var me = this;
if (Ext.isObject(width)) { // in case of object from getSize()
animate = height;
height = width.height;
width = width.width;
}
if (!animate || !me.anim) {
me.dom.style.width = Element.addUnits(width);
me.dom.style.height = Element.addUnits(height);
if (me.shadow || me.shim) {
me.syncUnderlays();
}
}
else {
if (animate === true) {
animate = {};
}
me.animate(Ext.applyIf({
to: {
width: width,
height: height
}
}, animate));
}
return me;
},
/**
* Sets the visibility of the element (see details). If the visibilityMode is set to Element.DISPLAY, it will use
* the display property to hide the element, otherwise it uses visibility. The default is to hide and show using the visibility property.
* @param {Boolean} visible Whether the element is visible
* @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
* @return {Ext.dom.Element} this
*/
setVisible: function(visible, animate) {
var me = this,
dom = me.dom,
visMode = getVisMode(me);
// hideMode string override
if (typeof animate === 'string') {
switch (animate) {
case DISPLAY:
visMode = Element.DISPLAY;
break;
case VISIBILITY:
visMode = Element.VISIBILITY;
break;
case OFFSETS:
visMode = Element.OFFSETS;
break;
}
me.setVisibilityMode(visMode);
animate = false;
}
if (!animate || !me.anim) {
if (visMode === Element.DISPLAY) {
return me.setDisplayed(visible);
} else if (visMode === Element.OFFSETS) {
me[visible?'removeCls':'addCls'](OFFSETCLASS);
} else if (visMode === Element.VISIBILITY) {
me.fixDisplay();
// Show by clearing visibility style. Explicitly setting to "visible" overrides parent visibility setting
dom.style.visibility = visible ? '' : HIDDEN;
}
} else {
// closure for composites
if (visible) {
me.setOpacity(0.01);
me.setVisible(true);
}
if (!Ext.isObject(animate)) {
animate = {
duration: 350,
easing: 'ease-in'
};
}
me.animate(Ext.applyIf({
callback: function() {
if (!visible) {
// Grab the dom again, since the reference may have changed if we use fly
Ext.fly(dom).setVisible(false).setOpacity(1);
}
},
to: {
opacity: (visible) ? 1 : 0
}
}, animate));
}
me.getData()[ISVISIBLE] = visible;
if (me.shadow || me.shim) {
me.setUnderlaysVisible(visible);
}
return me;
},
/**
* Set the width of this Element.
*
* // change the width to 200px and animate with default configuration
* Ext.fly('elementId').setWidth(200, true);
*
* // change the width to 150px and animate with a custom configuration
* Ext.fly('elId').setWidth(150, {
* duration : 500, // animation will have a duration of .5 seconds
* // will change the content to "finished"
* callback: function(){ this.{@link #setHtml}("finished"); }
* });
*
* @param {Number/String} width The new width. This may be one of:
*
* - A Number specifying the new width in pixels.
* - A String used to set the CSS width style. Animation may **not** be used.
*
* @param {Boolean/Object} [animate] a standard Element animation config object or `true` for
* the default animation (`{duration: 350, easing: 'ease-in'}`)
* @return {Ext.dom.Element} this
*/
setWidth: function(width, animate) {
var me = this;
if (!animate || !me.anim) {
me.callParent(arguments);
}
else {
if (!Ext.isObject(animate)) {
animate = {};
}
me.animate(Ext.applyIf({
to: {
width: width
}
}, animate));
}
return me;
},
setX: function(x, animate) {
return this.setXY([x, this.getY()], animate);
},
setXY: function(xy, animate) {
var me = this;
if (!animate || !me.anim) {
me.callParent([xy]);
} else {
if (!Ext.isObject(animate)) {
animate = {};
}
me.animate(Ext.applyIf({ to: { x: xy[0], y: xy[1] } }, animate));
}
return this;
},
setY: function(y, animate) {
return this.setXY([this.getX(), y], animate);
},
/**
* Show this element - Uses display mode to determine whether to use "display",
* "visibility", or "offsets". See {@link #setVisible}.
* @param {Boolean/Object} [animate] true for the default animation or a standard
* Element animation config object
* @return {Ext.dom.Element} this
*/
show: function(animate){
// hideMode override
if (typeof animate === 'string'){
this.setVisible(true, animate);
return this;
}
this.setVisible(true, this.anim(animate));
return this;
},
/**
* Slides the element into view. An anchor point can be optionally passed to set the point of origin for the slide
* effect. This function automatically handles wrapping the element with a fixed-size container if needed. See the
* {@link Ext.fx.Anim} class overview for valid anchor point options. Usage:
*
* // default: slide the element in from the top
* el.slideIn();
*
* // custom: slide the element in from the right with a 2-second duration
* el.slideIn('r', { duration: 2000 });
*
* // common config options shown with default values
* el.slideIn('t', {
* easing: 'easeOut',
* duration: 500
* });
*
* @param {String} anchor (optional) One of the valid {@link Ext.fx.Anim} anchor positions (defaults to top: 't')
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @param {Boolean} options.preserveScroll Set to true if preservation of any descendant elements'
* `scrollTop` values is required. By default the DOM wrapping operation performed by `slideIn` and
* `slideOut` causes the browser to lose all scroll positions.
* @return {Ext.dom.Element} The Element
*/
slideIn: function(anchor, obj, slideOut) {
var me = this,
dom = me.dom,
elStyle = dom.style,
beforeAnim,
wrapAnim,
restoreScroll,
wrapDomParentNode;
anchor = anchor || "t";
obj = obj || {};
beforeAnim = function() {
var animScope = this,
listeners = obj.listeners,
el = Ext.fly(dom, '_anim'),
box, originalStyles, anim, wrap;
if (!slideOut) {
el.fixDisplay();
}
box = el.getBox();
if ((anchor == 't' || anchor == 'b') && box.height === 0) {
box.height = dom.scrollHeight;
}
else if ((anchor == 'l' || anchor == 'r') && box.width === 0) {
box.width = dom.scrollWidth;
}
originalStyles = el.getStyle(['width', 'height', 'left', 'right', 'top', 'bottom', 'position', 'z-index'], true);
el.setSize(box.width, box.height);
// Cache all descendants' scrollTop & scrollLeft values if configured to preserve scroll.
if (obj.preserveScroll) {
restoreScroll = el.cacheScrollValues();
}
wrap = el.wrap({
role: 'presentation',
id: Ext.id() + '-anim-wrap-for-' + el.dom.id,
style: {
visibility: slideOut ? 'visible' : 'hidden'
}
});
wrapDomParentNode = wrap.dom.parentNode;
wrap.setPositioning(el.getPositioning(true));
if (wrap.isStyle('position', 'static')) {
wrap.position('relative');
}
el.clearPositioning('auto');
wrap.clip();
// The wrap will have reset all descendant scrollTops. Restore them if we cached them.
if (restoreScroll) {
restoreScroll();
}
// This element is temporarily positioned absolute within its wrapper.
// Restore to its default, CSS-inherited visibility setting.
// We cannot explicitly poke visibility:visible into its style because that overrides the visibility of the wrap.
el.setStyle({
visibility: '',
position: 'absolute'
});
if (slideOut) {
wrap.setSize(box.width, box.height);
}
switch (anchor) {
case 't':
anim = {
from: {
width: box.width + 'px',
height: '0px'
},
to: {
width: box.width + 'px',
height: box.height + 'px'
}
};
elStyle.bottom = '0px';
break;
case 'l':
anim = {
from: {
width: '0px',
height: box.height + 'px'
},
to: {
width: box.width + 'px',
height: box.height + 'px'
}
};
me.anchorAnimX(anchor);
break;
case 'r':
anim = {
from: {
x: box.x + box.width,
width: '0px',
height: box.height + 'px'
},
to: {
x: box.x,
width: box.width + 'px',
height: box.height + 'px'
}
};
me.anchorAnimX(anchor);
break;
case 'b':
anim = {
from: {
y: box.y + box.height,
width: box.width + 'px',
height: '0px'
},
to: {
y: box.y,
width: box.width + 'px',
height: box.height + 'px'
}
};
break;
case 'tl':
anim = {
from: {
x: box.x,
y: box.y,
width: '0px',
height: '0px'
},
to: {
width: box.width + 'px',
height: box.height + 'px'
}
};
elStyle.bottom = '0px';
me.anchorAnimX('l');
break;
case 'bl':
anim = {
from: {
y: box.y + box.height,
width: '0px',
height: '0px'
},
to: {
y: box.y,
width: box.width + 'px',
height: box.height + 'px'
}
};
me.anchorAnimX('l');
break;
case 'br':
anim = {
from: {
x: box.x + box.width,
y: box.y + box.height,
width: '0px',
height: '0px'
},
to: {
x: box.x,
y: box.y,
width: box.width + 'px',
height: box.height + 'px'
}
};
me.anchorAnimX('r');
break;
case 'tr':
anim = {
from: {
x: box.x + box.width,
width: '0px',
height: '0px'
},
to: {
x: box.x,
width: box.width + 'px',
height: box.height + 'px'
}
};
elStyle.bottom = '0px';
me.anchorAnimX('r');
break;
}
wrap.show();
wrapAnim = Ext.apply({}, obj);
delete wrapAnim.listeners;
wrapAnim = new Ext.fx.Anim(Ext.applyIf(wrapAnim, {
target: wrap,
duration: 500,
easing: 'ease-out',
from: slideOut ? anim.to : anim.from,
to: slideOut ? anim.from : anim.to
}));
// In the absence of a callback, this listener MUST be added first
wrapAnim.on('afteranimate', function() {
var el = Ext.fly(dom, '_anim');
el.setStyle(originalStyles);
if (slideOut) {
if (obj.useDisplay) {
el.setDisplayed(false);
} else {
el.hide();
}
}
if (wrap.dom) {
if (wrap.dom.parentNode) {
wrap.dom.parentNode.insertBefore(el.dom, wrap.dom);
} else {
wrapDomParentNode.appendChild(el.dom);
}
wrap.destroy();
}
// The unwrap will have reset all descendant scrollTops. Restore them if we cached them.
if (restoreScroll) {
restoreScroll();
}
// kill the no-op element animation created below
animScope.end();
});
// Add configured listeners after
if (listeners) {
wrapAnim.on(listeners);
}
};
me.animate({
// See "A Note About Wrapped Animations" at the top of this class:
duration: obj.duration ? Math.max(obj.duration, 500) * 2 : 1000,
listeners: {
beforeanimate: beforeAnim // kick off the wrap animation
}
});
return me;
},
/**
* Slides the element out of view. An anchor point can be optionally passed to set the end point for the slide
* effect. When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will
* still take up space in the document. The element must be removed from the DOM using the 'remove' config option if
* desired. This function automatically handles wrapping the element with a fixed-size container if needed. See the
* {@link Ext.fx.Anim} class overview for valid anchor point options. Usage:
*
* // default: slide the element out to the top
* el.slideOut();
*
* // custom: slide the element out to the right with a 2-second duration
* el.slideOut('r', { duration: 2000 });
*
* // common config options shown with default values
* el.slideOut('t', {
* easing: 'easeOut',
* duration: 500,
* remove: false,
* useDisplay: false
* });
*
* @param {String} anchor (optional) One of the valid {@link Ext.fx.Anim} anchor positions (defaults to top: 't')
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
slideOut: function(anchor, o) {
return this.slideIn(anchor, o, true);
},
/**
* Stops the specified event(s) from bubbling and optionally prevents the default action
* @param {String/String[]} eventName an event / array of events to stop from bubbling
* @param {Boolean} [preventDefault] true to prevent the default action too
* @return {Ext.dom.Element} this
*/
swallowEvent: function(eventName, preventDefault) {
var me = this,
e, eLen,
fn = function(e) {
e.stopPropagation();
if (preventDefault) {
e.preventDefault();
}
};
if (Ext.isArray(eventName)) {
eLen = eventName.length;
for (e = 0; e < eLen; e++) {
me.on(eventName[e], fn);
}
return me;
}
me.on(eventName, fn);
return me;
},
/**
* Blinks the element as if it was clicked and then collapses on its center (similar to switching off a television).
* When the effect is completed, the element will be hidden (visibility = 'hidden') but block elements will still
* take up space in the document. The element must be removed from the DOM using the 'remove' config option if
* desired. Usage:
*
* // default
* el.switchOff();
*
* // all config options shown with default values
* el.switchOff({
* easing: 'easeIn',
* duration: .3,
* remove: false,
* useDisplay: false
* });
*
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
switchOff: function(obj) {
var me = this,
dom = me.dom,
beforeAnim;
obj = Ext.applyIf(obj || {}, {
easing: 'ease-in',
duration: 500,
remove: false,
useDisplay: false
});
beforeAnim = function() {
var el = Ext.fly(dom, '_anim'),
animScope = this,
size = el.getSize(),
xy = el.getXY(),
keyframe, position;
el.clearOpacity();
el.clip();
position = el.getPositioning();
keyframe = new Ext.fx.Animator({
target: dom,
duration: obj.duration,
easing: obj.easing,
keyframes: {
33: {
opacity: 0.3
},
66: {
height: 1,
y: xy[1] + size.height / 2
},
100: {
width: 1,
x: xy[0] + size.width / 2
}
}
});
keyframe.on('afteranimate', function() {
var el = Ext.fly(dom, '_anim');
if (obj.useDisplay) {
el.setDisplayed(false);
} else {
el.hide();
}
el.clearOpacity();
el.setPositioning(position);
el.setSize(size);
// kill the no-op element animation created below
animScope.end();
});
};
me.animate({
// See "A Note About Wrapped Animations" at the top of this class:
duration: (Math.max(obj.duration, 500) * 2),
listeners: {
beforeanimate: {
fn: beforeAnim
}
},
callback: obj.callback,
scope: obj.scope
});
return me;
},
/**
* @private.
* Currently used for updating grid cells without modifying DOM structure
*
* Synchronizes content of this Element with the content of the passed element.
*
* Style and CSS class are copied from source into this Element, and contents are synched
* recursively. If a child node is a text node, the textual data is copied.
*/
syncContent: function(source) {
source = Ext.getDom(source);
var sourceNodes = source.childNodes,
sourceLen = sourceNodes.length,
dest = this.dom,
destNodes = dest.childNodes,
destLen = destNodes.length,
i, destNode, sourceNode,
nodeType, newAttrs, attLen, attName,
elData = dest._extData;
// Copy top node's attributes across. Use IE-specific method if possible.
// In IE10, there is a problem where the className will not get updated
// in the view, even though the className on the dom element is correct.
// See EXTJSIV-9462
if (Ext.isIE9m && dest.mergeAttributes) {
dest.mergeAttributes(source, true);
// EXTJSIV-6803. IE's mergeAttributes appears not to make the source's "src" value available until after the image is ready.
// So programatically copy any src attribute.
dest.src = source.src;
} else {
newAttrs = source.attributes;
attLen = newAttrs.length;
for (i = 0; i < attLen; i++) {
attName = newAttrs[i].name;
if (attName !== 'id') {
dest.setAttribute(attName, newAttrs[i].value);
}
}
}
// The element's data is no longer synchronized. We just overwrite it in the DOM
if (elData) {
elData.isSynchronized = false;
}
// If the number of child nodes does not match, fall back to replacing innerHTML
if (sourceLen !== destLen) {
dest.innerHTML = source.innerHTML;
return;
}
// Loop through source nodes.
// If there are fewer, we must remove excess
for (i = 0; i < sourceLen; i++) {
sourceNode = sourceNodes[i];
destNode = destNodes[i];
nodeType = sourceNode.nodeType;
// If node structure is out of sync, just drop innerHTML in and return
if (nodeType !== destNode.nodeType || (nodeType === 1 && sourceNode.tagName !== destNode.tagName)) {
dest.innerHTML = source.innerHTML;
return;
}
// Update text node
if (nodeType === 3) {
destNode.data = sourceNode.data;
}
// Sync element content
else {
if (sourceNode.id && destNode.id !== sourceNode.id) {
destNode.id = sourceNode.id;
}
destNode.style.cssText = sourceNode.style.cssText;
destNode.className = sourceNode.className;
Ext.fly(destNode, '_syncContent').syncContent(sourceNode);
}
}
},
/**
* Toggles the element's visibility, depending on visibility mode.
* @param {Boolean/Object} [animate] True for the default animation, or a standard Element animation config object
* @return {Ext.dom.Element} this
*/
toggle: function(animate){
var me = this;
me.setVisible(!me.isVisible(), me.anim(animate));
return me;
},
/**
* Hides a previously applied mask.
*/
unmask: function() {
var me = this,
data = me.getData(),
maskEl = data.maskEl,
style;
if (maskEl) {
style = maskEl.dom.style;
// Remove resource-intensive CSS expressions as soon as they are not required.
if (style.clearExpression) {
style.clearExpression('width');
style.clearExpression('height');
}
if (maskEl) {
maskEl.destroy();
delete data.maskEl;
}
me.removeCls([XMASKED, XMASKEDRELATIVE]);
}
me.<API key>();
if (me.dom !== DOC.body) {
me.<API key>();
}
},
/**
* Return clipping (overflow) to original clipping before {@link #clip} was called
* @return {Ext.dom.Element} this
*/
unclip: function() {
var me = this,
data = me.getData(),
clip;
if (data[ISCLIPPED]) {
data[ISCLIPPED] = false;
clip = data[ORIGINALCLIP];
if (clip.o) {
me.setStyle(OVERFLOW, clip.o);
}
if (clip.x) {
me.setStyle(OVERFLOWX, clip.x);
}
if (clip.y) {
me.setStyle(OVERFLOWY, clip.y);
}
}
return me;
},
translate: function(x, y, z) {
if (Ext.supports.CssTransforms && !Ext.isIE9m) {
this.callParent(arguments);
} else {
if (x != null) {
this.dom.style.left = x + 'px';
}
if (y != null) {
this.dom.style.top = y + 'px';
}
}
},
/**
* Disables text selection for this element (normalized across browsers)
* @return {Ext.dom.Element} this
*/
unselectable: function() {
// The approach used to disable text selection combines CSS, HTML attributes and DOM events. Importantly the
// strategy is designed to be expressible in markup, so that elements can be rendered unselectable without
// needing modifications post-render. e.g.:
// <div class="x-unselectable" unselectable="on"></div>
// Changes to this method may need to be reflected elsewhere, e.g. ProtoElement.
var me = this;
// The unselectable property (or similar) is supported by various browsers but Opera is the only browser that
// doesn't support any of the other techniques. The problem with it is that it isn't inherited by child
// elements. Theoretically we could add it to all children but the performance would be terrible. In certain
// key locations (e.g. panel headers) we add unselectable="on" to extra elements during rendering just for
// Opera's benefit.
if (Ext.isOpera) {
me.dom.unselectable = 'on';
}
// In Mozilla and WebKit the CSS properties -moz-user-select and -webkit-user-select prevent a selection
// originating in an element. These are inherited, which is what we want.
// In IE we rely on a listener for the selectstart event instead. We don't need to register a listener on the
// individual element, instead we use a single listener and rely on event propagation to listen for the event at
// the document level. That listener will walk up the DOM looking for nodes that have either of the classes
// x-selectable or x-unselectable. This simulates the CSS inheritance approach.
// IE 10 is expected to support -ms-user-select so the listener may not be required.
me.removeCls(Element.selectableCls);
me.addCls(Element.unselectableCls);
return me;
},
privates: {
needsTabIndex: function() {
var dom = this.dom,
nodeName, isFocusable;
if (dom) {
nodeName = dom.nodeName;
// Note that the code below is identical to isFocusable();
// it is intentionally duplicated for performance reasons.
isFocusable = !!Ext.Element.<API key>[nodeName] ||
((nodeName === 'A' || nodeName === 'LINK') && !!dom.href) ||
dom.getAttribute('tabindex') != null ||
dom.contentEditable === 'true';
// The result we need is the opposite to what we got
return !isFocusable;
}
},
// @private
// The difference between <API key> and <API key>
// is that find() will include `this` element itself if it is tabbable, while
// select() will only find tabbable children following querySelectorAll() logic.
<API key>: function(asDom, selector, /* private */ limit, backward) {
asDom = asDom != undefined ? asDom : true;
var me = this,
selection;
selection = me.<API key>(asDom, selector, limit, backward);
if (me.isTabbable()) {
selection.unshift(asDom ? me.dom : me);
}
return selection;
},
// @private
<API key>: function(asDom, selector, /* private */ limit, backward) {
var selection = [],
nodes, node, el, i, len, to, step, tabIndex;
asDom = asDom != undefined ? asDom : true;
nodes = this.dom.querySelectorAll(selector || Ext.Element.tabbableSelector);
len = nodes.length;
if (!len) {
return selection;
}
if (backward) {
i = len - 1;
to = 0;
step = -1;
}
else {
i = 0;
to = len - 1;
step = 1;
}
// We're only interested in the elements that an user can *tab into*,
// not all programmatically focusable elements. So we have to filter
// these out.
for (;; i += step) {
if ((step > 0 && i > to) || (step < 0 && i < to)) {
break;
}
node = nodes[i];
// A node with tabIndex < 0 absolutely can't be tabbable
// so we can save a function call if that is the case.
// Note that we can't use node.tabIndex here because IE
// will return 0 for elements that have no tabindex
// attribute defined, regardless of whether they are
// tabbable or not.
tabIndex = node.getAttribute('tabindex') - 0; // quicker than parseInt
// tabIndex value may be null for nodes with no tabIndex defined;
// most of those may be naturally tabbable. We don't want to
// check this here, that's isTabbable()'s job and it's not trivial.
// We explicitly check that tabIndex is not negative; the expression
// below is purposeful.
if (!(tabIndex < 0)) {
el = asDom ? Ext.fly(node) : Ext.get(node);
if (el.isTabbable()) {
selection.push(asDom ? node : el);
}
}
if (selection.length >= limit) {
return selection;
}
}
return selection;
},
// @private
<API key>: function(asDom, selector) {
var els = this.<API key>(asDom, selector, 1, false);
return els[0];
},
// @private
<API key>: function(asDom, selector) {
var el = this.<API key>(true, selector, 1, true)[0];
return (asDom !== false) ? el : Ext.get(el);
},
// @private
saveTabbableState: function(attribute) {
var <API key> = Ext.Element.<API key>,
dom = this.dom;
// Prevent tabIndex from being munged more than once
if (dom.hasAttribute(<API key>)) {
return;
}
attribute = attribute || Ext.Element.<API key>;
// tabIndex could be set on both naturally tabbable and generic elements.
// Either way we need to save it to restore later.
if (dom.hasAttribute('tabindex')) {
dom.setAttribute(attribute, dom.getAttribute('tabindex'));
}
// When no tabIndex is specified, that means a naturally tabbable element.
else {
dom.setAttribute(attribute, 'none');
}
// We disable the tabbable state by setting tabIndex to -1.
// The element can still be focused programmatically though.
dom.setAttribute('tabindex', -1);
dom.setAttribute(<API key>, true);
return this;
},
// @private
<API key>: function(attribute) {
var <API key> = Ext.Element.<API key>,
dom = this.dom,
idx;
attribute = attribute || Ext.Element.<API key>;
if (!dom.hasAttribute(<API key>) ||
!dom.hasAttribute(attribute)) {
return;
}
idx = dom.getAttribute(attribute);
// That is a naturally tabbable element
if (idx === 'none') {
dom.removeAttribute('tabindex');
}
else {
dom.setAttribute('tabindex', idx);
}
dom.removeAttribute(attribute);
dom.removeAttribute(<API key>);
return this;
},
// @private
<API key>: function(attribute) {
var children, child, i, len;
if (this.dom) {
children = this.<API key>();
for (i = 0, len = children.length; i < len; i++) {
child = Ext.fly(children[i]);
child.saveTabbableState(attribute);
}
}
return children;
},
// @private
<API key>: function(attribute, children) {
var child, i, len;
if (this.dom) {
attribute = attribute || Ext.Element.<API key>;
children = children || this.dom.querySelectorAll('[' + attribute + ']');
for (i = 0, len = children.length; i < len; i++) {
child = Ext.fly(children[i]);
child.<API key>(attribute);
}
}
return children;
}
},
deprecated: {
'4.0': {
methods: {
/**
* Creates a pause before any subsequent queued effects begin. If there are no effects queued after the pause it will
* have no effect. Usage:
*
* el.pause(1);
*
* @deprecated 4.0 Use the `delay` config to {@link #animate} instead.
* @param {Number} seconds The length of time to pause (in seconds)
* @return {Ext.dom.Element} The Element
*/
pause: function(ms) {
var me = this;
Ext.fx.Manager.setFxDefaults(me.id, {
delay: ms
});
return me;
},
/**
* Animates the transition of an element's dimensions from a starting height/width to an ending height/width. This
* method is a convenience implementation of {@link #shift}. Usage:
*
* // change height and width to 100x100 pixels
* el.scale(100, 100);
*
* // common config options shown with default values. The height and width will default to
* // the element's existing values if passed as null.
* el.scale(
* [element's width],
* [element's height], {
* easing: 'easeOut',
* duration: 350
* }
* );
*
* @deprecated 4.0 Just use {@link #animate} instead.
* @param {Number} width The new width (pass undefined to keep the original width)
* @param {Number} height The new height (pass undefined to keep the original height)
* @param {Object} options (optional) Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
scale: function(w, h, o) {
this.animate(Ext.apply({}, o, {
width: w,
height: h
}));
return this;
},
/**
* Animates the transition of any combination of an element's dimensions, xy position and/or opacity. Any of these
* properties not specified in the config object will not be changed. This effect requires that at least one new
* dimension, position or opacity setting must be passed in on the config object in order for the function to have
* any effect. Usage:
*
* // slide the element horizontally to x position 200 while changing the height and opacity
* el.shift({ x: 200, height: 50, opacity: .8 });
*
* // common config options shown with default values.
* el.shift({
* width: [element's width],
* height: [element's height],
* x: [element's x position],
* y: [element's y position],
* opacity: [element's opacity],
* easing: 'easeOut',
* duration: 350
* });
*
* @deprecated 4.0 Just use {@link #animate} instead.
* @param {Object} options Object literal with any of the {@link Ext.fx.Anim} config options
* @return {Ext.dom.Element} The Element
*/
shift: function(config) {
this.animate(config);
return this;
}
}
},
'4.2': {
methods: {
/**
* Sets the position of the element in page coordinates.
* @param {Number} x X value for new position (coordinates are page-based)
* @param {Number} y Y value for new position (coordinates are page-based)
* @param {Boolean/Object} [animate] True for the default animation, or a standard
* Element animation config object
* @return {Ext.dom.Element} this
* @deprecated 4.2.0 Use {@link #setXY} instead.
*/
moveTo: function(x, y, animate) {
return this.setXY([x, y], animate);
},
/**
* Sets the element's position and size in one shot. If animation is true then
* width, height, x and y will be animated concurrently.
*
* @param {Number} x X value for new position (coordinates are page-based)
* @param {Number} y Y value for new position (coordinates are page-based)
* @param {Number/String} width The new width. This may be one of:
*
* - A Number specifying the new width in pixels
* - A String used to set the CSS width style. Animation may **not** be used.
*
* @param {Number/String} height The new height. This may be one of:
*
* - A Number specifying the new height in pixels
* - A String used to set the CSS height style. Animation may **not** be used.
*
* @param {Boolean/Object} [animate] true for the default animation or
* a standard Element animation config object
*
* @return {Ext.dom.Element} this
* @deprecated 4.2.0 Use {@link Ext.util.Positionable#setBox} instead.
*/
setBounds: function(x, y, width, height, animate) {
return this.setBox({
x: x,
y: y,
width: width,
height: height
}, animate);
},
/**
* Sets the element's left and top positions directly using CSS style
* @param {Number/String} left Number of pixels or CSS string value to
* set as the left CSS property value
* @param {Number/String} top Number of pixels or CSS string value to
* set as the top CSS property value
* @return {Ext.dom.Element} this
* @deprecated 4.2.0 Use {@link #setLocalXY} instead
*/
setLeftTop: function(left, top) {
var me = this,
style = me.dom.style;
style.left = Element.addUnits(left);
style.top = Element.addUnits(top);
if (me.shadow || me.shim) {
me.syncUnderlays();
}
return me;
},
/**
* Sets the position of the element in page coordinates.
* @param {Number} x X value for new position
* @param {Number} y Y value for new position
* @param {Boolean/Object} [animate] True for the default animation, or a standard
* Element animation config object
* @return {Ext.dom.Element} this
* @deprecated 4.2.0 Use {@link #setXY} instead.
*/
setLocation: function(x, y, animate) {
return this.setXY([x, y], animate);
}
}
},
'5.0': {
methods: {
/**
* Returns the value of a namespaced attribute from the element's underlying DOM node.
* @param {String} namespace The namespace in which to look for the attribute
* @param {String} name The attribute name
* @return {String} The attribute value
* @deprecated 5.0.0 Please use {@link #getAttribute} instead.
*/
getAttributeNS: function(namespace, name) {
return this.getAttribute(name, namespace);
},
/**
* Calculates the x, y to center this element on the screen
* @return {Number[]} The x, y values [x, y]
* @deprecated 5.0.0
*/
getCenterXY: function(){
return this.getAlignToXY(DOC, 'c-c');
},
/**
* Returns either the offsetHeight or the height of this element based on CSS height adjusted by padding or borders
* when needed to simulate offsetHeight when offsets aren't available. This may not work on display:none elements
* if a height has not been set using CSS.
* @return {Number}
* @deprecated 5.0.0
*/
getComputedHeight: function() {
return Math.max(this.dom.offsetHeight, this.dom.clientHeight) ||
parseFloat(this.getStyle(HEIGHT)) || 0;
},
/**
* Returns either the offsetWidth or the width of this element based on CSS width adjusted by padding or borders
* when needed to simulate offsetWidth when offsets aren't available. This may not work on display:none elements
* if a width has not been set using CSS.
* @return {Number}
* @deprecated 5.0.0
*/
getComputedWidth: function() {
return Math.max(this.dom.offsetWidth, this.dom.clientWidth) ||
parseFloat(this.getStyle(WIDTH)) || 0;
},
/**
* Returns the dimensions of the element available to lay content out in.
*
* getStyleSize utilizes prefers style sizing if present, otherwise it chooses the larger of offsetHeight/clientHeight and
* offsetWidth/clientWidth. To obtain the size excluding scrollbars, use getViewSize.
*
* Sizing of the document body is handled at the adapter level which handles special cases for IE and strict modes, etc.
*
* @return {Object} Object describing width and height.
* @return {Number} return.width
* @return {Number} return.height
* @deprecated 5.0.0
*/
getStyleSize: function() {
var me = this,
d = this.dom,
isDoc = (d === DOC || d === DOC.body),
s,
w, h;
// If the body, use static methods
if (isDoc) {
return {
width : Element.getViewportWidth(),
height : Element.getViewportHeight()
};
}
s = me.getStyle(['height', 'width'], true); //seek inline
// Use Styles if they are set
if (s.width && s.width !== 'auto') {
w = parseFloat(s.width);
}
// Use Styles if they are set
if (s.height && s.height !== 'auto') {
h = parseFloat(s.height);
}
// Use getWidth/getHeight if style not set.
return {width: w || me.getWidth(true), height: h || me.getHeight(true)};
},
/**
* Returns true if this element uses the border-box-sizing model. This method is
* deprecated as of version 5.0 because border-box sizing is forced upon all elements
* via a stylesheet rule, and the browsers that do not support border-box (IE6/7 strict
* mode) are no longer supported.
* @deprecated 5.0.0
* @return {Boolean}
*/
isBorderBox: function() {
return true;
},
/**
* Returns true if display is not "none"
* @return {Boolean}
* @deprecated 5.0.0 use element.isStyle('display', 'none');
*/
isDisplayed: function() {
return !this.isStyle('display', 'none');
},
/**
* Checks whether this element can be focused.
* @return {Boolean} True if the element is focusable
* @deprecated 5.0.0 use {@link #isFocusable} instead
*/
focusable: 'isFocusable'
}
}
}
};
})(), function() {
var Element = Ext.dom.Element,
proto = Element.prototype,
useDocForId = !Ext.isIE8,
DOC = document,
view = DOC.defaultView,
opacityRe = /alpha\(opacity=(.*)\)/i,
trimRe = /^\s+|\s+$/g,
styleHooks = proto.styleHooks,
supports = Ext.supports,
removeNode, garbageBin, <API key>, <API key>, edges, k,
edge, borderWidth;
proto._init(Element);
delete proto._init;
Ext.plainTableCls = Ext.baseCSSPrefix + 'table-plain';
Ext.plainListCls = Ext.baseCSSPrefix + 'list-plain';
// ensure that any methods added by this override are also added to Ext.<API key>
if (Ext.<API key>) {
Ext.<API key>.<API key>();
}
styleHooks.opacity = {
name: 'opacity',
afterSet: function(dom, value, el) {
var shadow = el.shadow;
if (shadow) {
shadow.setOpacity(value);
}
}
};
if (!supports.Opacity && Ext.isIE) {
Ext.apply(styleHooks.opacity, {
get: function (dom) {
var filter = dom.style.filter,
match, opacity;
if (filter.match) {
match = filter.match(opacityRe);
if (match) {
opacity = parseFloat(match[1]);
if (!isNaN(opacity)) {
return opacity ? opacity / 100 : 0;
}
}
}
return 1;
},
set: function (dom, value) {
var style = dom.style,
val = style.filter.replace(opacityRe, '').replace(trimRe, '');
style.zoom = 1; // ensure dom.hasLayout
// value can be a number or '' or null... so treat falsey as no opacity
if (typeof(value) === 'number' && value >= 0 && value < 1) {
value *= 100;
style.filter = val + (val.length ? ' ' : '') + 'alpha(opacity='+value+')';
} else {
style.filter = val;
}
}
});
}
if (!supports.matchesSelector) {
// Match basic tagName.ClassName selector syntax for is implementation
var simpleSelectorRe = /^([a-z]+|\*)?(?:\.([a-z][a-z\-_0-9]*))?$/i,
dashRe = /\-/g,
fragment,
classMatcher = function (tag, cls) {
var classRe = new RegExp('(?:^|\\s+)' +cls.replace(dashRe, '\\-') + '(?:\\s+|$)');
if (tag && tag !== '*') {
tag = tag.toUpperCase();
return function (el) {
return el.tagName === tag && classRe.test(el.className);
};
}
return function (el) {
return classRe.test(el.className);
};
},
tagMatcher = function (tag) {
tag = tag.toUpperCase();
return function (el) {
return el.tagName === tag;
};
},
cache = {};
proto.matcherCache = cache;
proto.is = function(selector) {
// Empty selector always matches
if (!selector) {
return true;
}
var dom = this.dom,
cls, match, testFn, root, isOrphan, is, tag;
// Only Element node types can be matched.
if (dom.nodeType !== 1) {
return false;
}
if (!(testFn = Ext.isFunction(selector) ? selector : cache[selector])) {
if (!(match = selector.match(simpleSelectorRe))) {
// Not a simple tagName.className selector, do it the hard way
root = dom.parentNode;
if (!root) {
isOrphan = true;
root = fragment || (fragment = DOC.<API key>());
fragment.appendChild(dom);
}
is = Ext.Array.indexOf(Ext.fly(root, '_is').query(selector), dom) !== -1;
if (isOrphan) {
fragment.removeChild(dom);
}
return is;
}
tag = match[1];
cls = match[2];
cache[selector] = testFn = cls ? classMatcher(tag, cls) : tagMatcher(tag);
}
return testFn(dom);
};
}
// IE8 needs its own implementation of getStyle because it doesn't support getComputedStyle
if (!view || !view.getComputedStyle) {
proto.getStyle = function (property, inline) {
var me = this,
dom = me.dom,
multiple = typeof property !== 'string',
prop = property,
props = prop,
len = 1,
isInline = inline,
styleHooks = me.styleHooks,
camel, domStyle, values, hook, out, style, i;
if (multiple) {
values = {};
prop = props[0];
i = 0;
if (!(len = props.length)) {
return values;
}
}
if (!dom || dom.documentElement) {
return values || '';
}
domStyle = dom.style;
if (inline) {
style = domStyle;
} else {
style = dom.currentStyle;
// fallback to inline style if rendering context not available
if (!style) {
isInline = true;
style = domStyle;
}
}
do {
hook = styleHooks[prop];
if (!hook) {
styleHooks[prop] = hook = { name: Element.normalize(prop) };
}
if (hook.get) {
out = hook.get(dom, me, isInline, style);
} else {
camel = hook.name;
out = style[camel];
}
if (!multiple) {
return out;
}
values[prop] = out;
prop = props[++i];
} while (i < len);
return values;
};
}
// override getStyle for border-*-width
if (Ext.isIE8) {
function getBorderWidth (dom, el, inline, style) {
if (style[this.styleName] === 'none') {
return '0px';
}
return style[this.name];
}
edges = ['Top','Right','Bottom','Left'];
k = edges.length;
while (k
edge = edges[k];
borderWidth = 'border' + edge + 'Width';
styleHooks['border-'+edge.toLowerCase()+'-width'] = styleHooks[borderWidth] = {
name: borderWidth,
styleName: 'border' + edge + 'Style',
get: getBorderWidth
};
}
}
Ext.apply(Ext, {
/**
* `true` to automatically uncache orphaned Ext.Elements periodically. If set to
* `false`, the application will be required to clean up orpaned Ext.Elements and
* it's listeners as to not cause memory leakage.
* @member Ext
*/
<API key>: true,
// In sencha v5 isBorderBox is no longer needed since all supported browsers
// suppport border-box, but it is hard coded to true for backward compatibility
isBorderBox: true,
/**
* @property {Boolean} useShims
* @member Ext
* Set to `true` to use a {@link Ext.util.Floating#shim shim} on all floating Components
* and {@link Ext.LoadMask LoadMasks}
*/
useShims: false,
/**
* @private
* Returns an HTML div element into which {@link Ext.container.Container#method-remove removed} components
* are placed so that their DOM elements are not garbage collected as detached Dom trees.
* @returns {Ext.dom.Element}
* @member Ext
*/
getDetachedBody: function () {
var detachedEl = Ext.detachedBodyEl;
if (!detachedEl) {
detachedEl = DOC.createElement('div');
Ext.detachedBodyEl = detachedEl = new Ext.dom.Fly(detachedEl);
detachedEl.isDetachedBody = true;
}
return detachedEl;
},
getElementById: function (id) {
var el = DOC.getElementById(id),
detachedBodyEl;
if (!el && (detachedBodyEl = Ext.detachedBodyEl)) {
el = detachedBodyEl.dom.querySelector(Ext.makeIdSelector(id));
}
return el;
},
/**
* Applies event listeners to elements by selectors when the document is ready.
* The event name is specified with an `@` suffix.
*
* Ext.addBehaviors({
* // add a listener for click on all anchors in element with id foo
* '#foo a@click': function(e, t){
* // do something
* },
*
* // add the same listener to multiple selectors (separated by comma BEFORE the @)
* '#foo a, #bar span.some-class@mouseover': function(){
* // do something
* }
* });
*
* @param {Object} obj The list of behaviors to apply
*/
addBehaviors: function(o){
if(!Ext.isReady){
Ext.onReady(function(){
Ext.addBehaviors(o);
});
} else {
var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
parts,
b,
s;
for (b in o) {
if ((parts = b.split('@'))[1]) { // for Object prototype breakers
s = parts[0];
if(!cache[s]){
cache[s] = Ext.fly(document).select(s, true);
}
cache[s].on(parts[1], o[b]);
}
}
cache = null;
}
}
});
if (Ext.isIE8) {
// save a reference to the removeNode function defined in sencha-core
removeNode = Ext.removeNode;
Ext.removeNode = function(node) {
removeNode(node);
// prevent memory leaks in IE8
garbageBin = garbageBin || DOC.createElement('div');
garbageBin.appendChild(node);
garbageBin.innerHTML = '';
};
}
if (Ext.isIE9m) {
Ext.getElementById = function (id) {
var el = DOC.getElementById(id),
detachedBodyEl;
if (!el && (detachedBodyEl = Ext.detachedBodyEl)) {
el = detachedBodyEl.dom.all[id];
}
return el;
};
proto.getById = function (id, asDom) {
var dom = this.dom,
ret = null,
entry, el;
if (dom) {
// for normal elements getElementById is the best solution, but if the el is
// not part of the document.body, we need to use all[]
el = (useDocForId && DOC.getElementById(id)) || dom.all[id];
if (el) {
if (asDom) {
ret = el;
} else {
// calling Element.get here is a real hit (2x slower) because it has to
// redetermine that we are giving it a dom el.
entry = Ext.cache[id];
if (entry) {
if (entry.<API key> || !Ext.isGarbage(entry.dom)) {
ret = entry;
} else {
//<debug>
Ext.Error.raise("Stale Element with id '" + el.id +
"' found in Element cache. " +
"Make sure to clean up Element instances using destroy()" );
//</debug>
entry.destroy();
}
}
ret = ret || new Ext.Element(el)
}
}
}
return ret;
};
} else if (!DOC.querySelector) {
Ext.getDetachedBody = Ext.getBody;
Ext.getElementById = function (id) {
return DOC.getElementById(id);
};
proto.getById = function (id, asDom) {
var dom = DOC.getElementById(id);
return asDom ? dom : (dom ? Ext.get(dom) : null);
};
}
if (Ext.isIE && !(Ext.isIE9p && DOC.documentMode >= 9)) {
// Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab,
// as a non-exhaustive list) return null when the specified attribute does not exist on the specified element.
// The DOM specification says that the correct return value in this case is actually the empty string, and some
// DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows
// the specification and returns an empty string. Consequently, you should use hasAttribute to check for an attribute's
// existence prior to calling getAttribute() if it is possible that the requested attribute does not exist on the specified element.
// http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614
proto.getAttribute = function(name, ns) {
var d = this.dom,
type;
if (ns) {
type = typeof d[ns + ":" + name];
if (type != 'undefined' && type != 'unknown') {
return d[ns + ":" + name] || null;
}
return null;
}
if (name === "for") {
name = "htmlFor";
}
return d[name] || null;
};
}
Ext.onReady(function () {
var transparentRe = /^(?:transparent|(?:rgba[(](?:\s*\d+\s*[,]){3}\s*0\s*[)]))$/i,
bodyCls = [],
//htmlCls = [],
origSetWidth = proto.setWidth,
origSetHeight = proto.setHeight,
origSetSize = proto.setSize,
pxRe = /^\d+(?:\.\d*)?px$/i,
colorStyles, i, name, camel;
if (supports.FixedTableWidthBug) {
// EXTJSIV-12665
// Webkit browsers fail to layout correctly when a form field's width is less
// than the min-width of the body element. The only way to fix it seems to be
// to toggle the display style of the field's element before and after setting
// the width. Note: once the bug has been corrected by toggling the element's
// display, successive calls to setWidth will work without the hack. It's only
// when going from naturally widthed to having an explicit width that the bug
// occurs.
styleHooks.width = {
name: 'width',
set: function(dom, value, el) {
var style = dom.style,
needsFix = el._needsTableWidthFix,
origDisplay = style.display;
if (needsFix) {
style.display = 'none';
}
style.width = value;
if (needsFix) {
dom.scrollWidth; // repaint
style.display = origDisplay;
}
}
};
proto.setWidth = function(width, animate) {
var me = this,
dom = me.dom,
style = dom.style,
needsFix = me._needsTableWidthFix,
origDisplay = style.display;
if (needsFix && !animate) {
style.display = 'none';
}
origSetWidth.call(me, width, animate);
if (needsFix && !animate) {
dom.scrollWidth; // repaint
style.display = origDisplay;
}
return me;
};
proto.setSize = function(width, height, animate) {
var me = this,
dom = me.dom,
style = dom.style,
needsFix = me._needsTableWidthFix,
origDisplay = style.display;
if (needsFix && !animate) {
style.display = 'none';
}
origSetSize.call(me, width, height, animate);
if (needsFix && !animate) {
dom.scrollWidth; // repaint
style.display = origDisplay;
}
return me;
};
}
//<feature legacyBrowser>
if (Ext.isIE8) {
styleHooks.height = {
name: 'height',
set: function(dom, value, el) {
var component = el.component,
frameInfo, frameBodyStyle;
if (component && component._syncFrameHeight && this === component.el) {
frameBodyStyle = component.frameBody.dom.style;
if (pxRe.test(value)) {
frameInfo = component.getFrameInfo();
if (frameInfo) {
frameBodyStyle.height = (parseInt(value, 10) - frameInfo.height) + 'px';
}
} else if (!value || value === 'auto') {
frameBodyStyle.height = '';
}
}
dom.style.height = value;
}
};
proto.setHeight = function(height, animate) {
var component = this.component,
frameInfo, frameBodyStyle;
if (component && component._syncFrameHeight && this === component.el) {
frameBodyStyle = component.frameBody.dom.style;
if (!height || height === 'auto') {
frameBodyStyle.height = '';
} else {
frameInfo = component.getFrameInfo();
if (frameInfo) {
frameBodyStyle.height = (height - frameInfo.height) + 'px';
}
}
}
return origSetHeight.call(this, height, animate);
};
proto.setSize = function(width, height, animate) {
var component = this.component,
frameInfo, frameBodyStyle;
if (component && component._syncFrameHeight && this === component.el) {
frameBodyStyle = component.frameBody.dom.style;
if (!height || height === 'auto') {
frameBodyStyle.height = '';
} else {
frameInfo = component.getFrameInfo();
if (frameInfo) {
frameBodyStyle.height = (height - frameInfo.height) + 'px';
}
}
}
return origSetSize.call(this, width, height, animate);
};
}
//</feature>
// Element.unselectable relies on this listener to prevent selection in IE. Some other browsers support the event too
// but it is only strictly required for IE. In WebKit this listener causes subtle differences to how the browser handles
// the non-selection, e.g. whether or not the mouse cursor changes when attempting to select text.
Ext.getDoc().on('selectstart', function(ev, dom) {
var selectableCls = Element.selectableCls,
unselectableCls = Element.unselectableCls,
tagName = dom && dom.tagName;
tagName = tagName && tagName.toLowerCase();
// Element.unselectable is not really intended to handle selection within text fields and it is important that
// fields inside menus or panel headers don't inherit the unselectability. In most browsers this is automatic but in
// IE 9 the selectstart event can bubble up from text fields so we have to explicitly handle that case.
if (tagName === 'input' || tagName === 'textarea') {
return;
}
// Walk up the DOM checking the nodes. This may be 'slow' but selectstart events don't fire very often
while (dom && dom.nodeType === 1 && dom !== DOC.documentElement) {
var el = Ext.fly(dom);
// If the node has the class x-selectable then stop looking, the text selection is allowed
if (el.hasCls(selectableCls)) {
return;
}
// If the node has class x-unselectable then the text selection needs to be stopped
if (el.hasCls(unselectableCls)) {
ev.stopEvent();
return;
}
dom = dom.parentNode;
}
});
function fixTransparent (dom, el, inline, style) {
var value = style[this.name] || '';
return transparentRe.test(value) ? 'transparent' : value;
}
/*
* Helper function to create the function that will restore the selection.
*/
function <API key> (activeEl, start, end) {
return function () {
activeEl.selectionStart = start;
activeEl.selectionEnd = end;
};
}
/**
* Creates a function to call to clean up problems with the work-around for the
* WebKit RightMargin bug. The work-around is to add "display: 'inline-block'" to
* the element before calling getComputedStyle and then to restore its original
* display value. The problem with this is that it corrupts the selection of an
* INPUT or TEXTAREA element (as in the "I-beam" goes away but ths focus remains).
* To cleanup after this, we need to capture the selection of any such element and
* then restore it after we have restored the display style.
*
* @param {HTMLElement} target The top-most element being adjusted.
* @private
*/
function <API key>(target) {
var hasInputBug = supports.<API key>,
hasTextAreaBug = supports.<API key>,
activeEl, tag, start, end;
if (hasInputBug || hasTextAreaBug) {
activeEl = Element.getActiveElement();
tag = activeEl && activeEl.tagName;
if ((hasTextAreaBug && tag === 'TEXTAREA') ||
(hasInputBug && tag === 'INPUT' && activeEl.type === 'text')) {
if (Ext.fly(target).isAncestor(activeEl)) {
start = activeEl.selectionStart;
end = activeEl.selectionEnd;
if (Ext.isNumber(start) && Ext.isNumber(end)) { // to be safe...
// We don't create the raw closure here inline because that
// will be costly even if we don't want to return it (nested
// function decls and exprs are often instantiated on entry
// regardless of whether execution ever reaches them):
return <API key>(activeEl, start, end);
}
}
}
}
return Ext.emptyFn; // avoid special cases, just return a nop
}
function fixRightMargin (dom, el, inline, style) {
var result = style.marginRight,
domStyle, display;
// Ignore cases when the margin is correctly reported as 0, the bug only shows
// numbers larger.
if (result !== '0px') {
domStyle = dom.style;
display = domStyle.display;
domStyle.display = 'inline-block';
result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, null)).marginRight;
domStyle.display = display;
}
return result;
}
function <API key> (dom, el, inline, style) {
var result = style.marginRight,
domStyle, cleaner, display;
if (result !== '0px') {
domStyle = dom.style;
cleaner = <API key>(dom);
display = domStyle.display;
domStyle.display = 'inline-block';
result = (inline ? style : dom.ownerDocument.defaultView.getComputedStyle(dom, '')).marginRight;
domStyle.display = display;
cleaner();
}
return result;
}
if (!supports.RightMargin) {
styleHooks.marginRight = styleHooks['margin-right'] = {
name: 'marginRight',
// TODO - Touch should use conditional compilation here or ensure that the
// underlying Ext.supports flags are set correctly...
get: (supports.<API key> || supports.<API key>) ?
<API key> : fixRightMargin
};
}
if (!supports.TransparentColor) {
colorStyles = ['background-color', 'border-color', 'color', 'outline-color'];
for (i = colorStyles.length; i
name = colorStyles[i];
camel = Element.normalize(name);
styleHooks[name] = styleHooks[camel] = {
name: camel,
get: fixTransparent
};
}
}
// When elements are rotated 80 or 270 degrees, their border, margin and padding hooks
// need to be rotated as well.
proto.<API key> = <API key> = Ext.Object.chain(styleHooks);
proto.<API key> = <API key> = Ext.Object.chain(styleHooks);
<API key>.width = styleHooks.height || { name: 'height' };
<API key>.height = styleHooks.width || { name: 'width' };
<API key>['margin-top'] = { name: 'marginLeft' };
<API key>['margin-right'] = { name: 'marginTop' };
<API key>['margin-bottom'] = { name: 'marginRight' };
<API key>['margin-left'] = { name: 'marginBottom' };
<API key>['padding-top'] = { name: 'paddingLeft' };
<API key>['padding-right'] = { name: 'paddingTop' };
<API key>['padding-bottom'] = { name: 'paddingRight' };
<API key>['padding-left'] = { name: 'paddingBottom' };
<API key>['border-top'] = { name: 'borderLeft' };
<API key>['border-right'] = { name: 'borderTop' };
<API key>['border-bottom'] = { name: 'borderRight' };
<API key>['border-left'] = { name: 'borderBottom' };
<API key>.width = styleHooks.height || { name: 'height' };
<API key>.height = styleHooks.width || { name: 'width' };
<API key>['margin-top'] = { name: 'marginRight' };
<API key>['margin-right'] = { name: 'marginBottom' };
<API key>['margin-bottom'] = { name: 'marginLeft' };
<API key>['margin-left'] = { name: 'marginTop' };
<API key>['padding-top'] = { name: 'paddingRight' };
<API key>['padding-right'] = { name: 'paddingBottom' };
<API key>['padding-bottom'] = { name: 'paddingLeft' };
<API key>['padding-left'] = { name: 'paddingTop' };
<API key>['border-top'] = { name: 'borderRight' };
<API key>['border-right'] = { name: 'borderBottom' };
<API key>['border-bottom'] = { name: 'borderLeft' };
<API key>['border-left'] = { name: 'borderTop' };
/**
* @property {Boolean} scopeCss
* @member Ext
* Set this to true before onReady to prevent any styling from being added to
* the body element. By default a few styles such as font-family, and color
* are added to the body element via a "x-body" class. When this is set to
* `true` the "x-body" class is not added to the body element, but is added
* to the elements of root-level containers instead.
*/
if (!Ext.scopeCss) {
bodyCls.push(Ext.baseCSSPrefix + 'body');
}
if (supports.Touch) {
bodyCls.push(Ext.baseCSSPrefix + 'touch');
}
if (Ext.isIE && Ext.isIE9m) {
bodyCls.push(Ext.baseCSSPrefix + 'ie',
Ext.baseCSSPrefix + 'ie9m');
// very often CSS needs to do checks like "IE7+" or "IE6 or 7". To help
// reduce the clutter (since CSS/SCSS cannot do these tests), we add some
// additional classes:
// x-ie7p : IE7+ : 7 <= ieVer
// x-ie7m : IE7- : ieVer <= 7
// x-ie8p : IE8+ : 8 <= ieVer
// x-ie8m : IE8- : ieVer <= 8
// x-ie9p : IE9+ : 9 <= ieVer
// x-ie78 : IE7 or 8 : 7 <= ieVer <= 8
bodyCls.push(Ext.baseCSSPrefix + 'ie8p');
if (Ext.isIE8) {
bodyCls.push(Ext.baseCSSPrefix + 'ie8');
} else {
bodyCls.push(Ext.baseCSSPrefix + 'ie9',
Ext.baseCSSPrefix + 'ie9p');
}
if (Ext.isIE8m) {
bodyCls.push(Ext.baseCSSPrefix + 'ie8m');
}
}
if (Ext.isIE10) {
bodyCls.push(Ext.baseCSSPrefix + 'ie10');
}
if (Ext.isIE11) {
bodyCls.push(Ext.baseCSSPrefix + 'ie11');
}
if (Ext.isGecko) {
bodyCls.push(Ext.baseCSSPrefix + 'gecko');
}
if (Ext.isOpera) {
bodyCls.push(Ext.baseCSSPrefix + 'opera');
}
if (Ext.isOpera12m) {
bodyCls.push(Ext.baseCSSPrefix + 'opera12m');
}
if (Ext.isWebKit) {
bodyCls.push(Ext.baseCSSPrefix + 'webkit');
}
if (Ext.isSafari) {
bodyCls.push(Ext.baseCSSPrefix + 'safari');
}
if (Ext.isChrome) {
bodyCls.push(Ext.baseCSSPrefix + 'chrome');
}
if (Ext.isMac) {
bodyCls.push(Ext.baseCSSPrefix + 'mac');
}
if (Ext.isLinux) {
bodyCls.push(Ext.baseCSSPrefix + 'linux');
}
if (!supports.CSS3BorderRadius) {
bodyCls.push(Ext.baseCSSPrefix + 'nbr');
}
if (!supports.CSS3LinearGradient) {
bodyCls.push(Ext.baseCSSPrefix + 'nlg');
}
if (supports.Touch) {
bodyCls.push(Ext.baseCSSPrefix + 'touch');
}
//Ext.fly(document.documentElement).addCls(htmlCls);
Ext.getBody().addCls(bodyCls);
}, null, { priority: 1500 }); // onReady
}); |
var edge = require('../lib/edge');
var hello = edge.func('103_hello_file.csx');
hello('Node.js', function (error, result) {
if (error) throw error;
console.log(result);
}); |
<?php
final class <API key> extends PhabricatorWorker {
public static function <API key>($phid, $parameters = null) {
if ($parameters === null) {
$parameters = array();
}
parent::scheduleTask(
__CLASS__,
array(
'documentPHID' => $phid,
'parameters' => $parameters,
),
array(
'priority' => parent::PRIORITY_IMPORT,
));
}
protected function doWork() {
$data = $this->getTaskData();
$object_phid = idx($data, 'documentPHID');
$object = $this-><API key>($object_phid);
$engine = id(new <API key>())
->setObject($object);
$parameters = idx($data, 'parameters', array());
$engine->setParameters($parameters);
if (!$engine->shouldIndexObject()) {
return;
}
$key = "index.{$object_phid}";
$lock = <API key>::newLock($key);
$lock->lock(1);
try {
// Reload the object now that we have a lock, to make sure we have the
// most current version.
$object = $this-><API key>($object->getPHID());
$engine->setObject($object);
$engine->indexObject();
} catch (Exception $ex) {
$lock->unlock();
if (!($ex instanceof <API key>)) {
$ex = new <API key>(
pht(
'Failed to update search index for document "%s": %s',
$object_phid,
$ex->getMessage()));
}
throw $ex;
}
$lock->unlock();
}
private function <API key>($phid) {
$viewer = PhabricatorUser::getOmnipotentUser();
$object = id(new <API key>())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$object) {
throw new <API key>(
pht(
'Unable to load object "%s" to rebuild indexes.',
$phid));
}
return $object;
}
} |
// This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: '<API key>',
name: 'Azure Storage DM Dev',
user: {
name: 'user@domain.example',
type: 'user'
},
tenantId: '<API key>',
registeredProviders: [],
isDefault: true
}, newProfile.environments['AzureCloud']));
return newProfile;
};
exports.setEnvironment = function() {
process.env['<API key>'] = '<API key>=http;AccountName=xplat;AccountKey=null';
};
exports.scopes = [[function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:80')
.head('/<API key>/blockblobname')
.reply(200, "", { 'content-length': '10',
'content-type': 'text/plain',
'content-md5': '<API key>==',
'last-modified': 'Wed, 01 Jul 2015 06:34:32 GMT',
'accept-ranges': 'bytes',
etag: '"0x8D281DF2023E6C2"',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '<API key>',
'x-ms-version': '2015-02-21',
'x-ms-lease-status': 'unlocked',
'x-ms-lease-state': 'available',
'x-ms-blob-type': 'BlockBlob',
date: 'Wed, 01 Jul 2015 06:34:41 GMT' });
return result; },
function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:80')
.get('/<API key>/blockblobname')
.reply(200, "HelloWorld", { 'content-length': '10',
'content-type': 'text/plain',
'content-md5': '<API key>==',
'last-modified': 'Wed, 01 Jul 2015 06:34:32 GMT',
'accept-ranges': 'bytes',
etag: '"0x8D281DF2023E6C2"',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '<API key>',
'x-ms-version': '2015-02-21',
'x-ms-lease-status': 'unlocked',
'x-ms-lease-state': 'available',
'x-ms-blob-type': 'BlockBlob',
date: 'Wed, 01 Jul 2015 06:34:41 GMT' });
return result; },
function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:80')
.head('/<API key>/blockblobname')
.reply(200, "", { 'content-length': '10',
'content-type': 'text/plain',
'content-md5': '<API key>==',
'last-modified': 'Wed, 01 Jul 2015 06:34:32 GMT',
'accept-ranges': 'bytes',
etag: '"0x8D281DF2023E6C2"',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '<API key>',
'x-ms-version': '2015-02-21',
'x-ms-lease-status': 'unlocked',
'x-ms-lease-state': 'available',
'x-ms-blob-type': 'BlockBlob',
date: 'Wed, 01 Jul 2015 06:34:41 GMT' });
return result; },
function (nock) {
var result =
nock('http://xplat.blob.core.windows.net:80')
.head('/<API key>/blockblobname')
.reply(200, "", { 'content-length': '10',
'content-type': 'text/plain',
'content-md5': '<API key>==',
'last-modified': 'Wed, 01 Jul 2015 06:34:32 GMT',
'accept-ranges': 'bytes',
etag: '"0x8D281DF2023E6C2"',
server: 'Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0',
'x-ms-request-id': '<API key>',
'x-ms-version': '2015-02-21',
'x-ms-lease-status': 'unlocked',
'x-ms-lease-state': 'available',
'x-ms-blob-type': 'BlockBlob',
date: 'Wed, 01 Jul 2015 06:34:42 GMT' });
return result; }]]; |
import random
import re
import socket
import threading
import time
import <API key>
from NativeLog import NativeLog
from TCAction import PerformanceTCBase
DELAY_RANGE = [10, 3000]
<API key> = ("Connection handler", "PC socket", "Target socket id",
"Target port", "PC port", "PC state", "Target state")
# max fail count for one connection during test
MAX_FAIL_COUNT = 10
class CheckerBase(threading.Thread):
CHECK_ITEM = ("CONDITION", "NOTIFIER", "ID", "DATA")
SLEEP_TIME = 0.1 # sleep 100ms between each check action
def __init__(self):
threading.Thread.__init__(self)
self.setDaemon(True)
self.exit_event = threading.Event()
self.sync_lock = threading.Lock()
self.check_item_list = []
self.check_item_id = 0
def run(self):
while self.exit_event.isSet() is False:
self.process()
pass
def process(self):
pass
def add_check_item(self, condition, notifier):
with self.sync_lock:
check_item_id = self.check_item_id
self.check_item_id += 1
self.check_item_list.append(dict(zip(self.CHECK_ITEM, (condition, notifier, check_item_id, str()))))
return check_item_id
def remove_check_item(self, check_item_id):
ret = None
with self.sync_lock:
check_items = filter(lambda x: x["ID"] == check_item_id, self.check_item_list)
if len(check_items) > 0:
self.check_item_list.remove(check_items[0])
ret = check_items[0]["DATA"]
return ret
def exit(self):
self.exit_event.set()
pass
# check on serial port
class SerialPortChecker(CheckerBase):
def __init__(self, serial_reader):
CheckerBase.__init__(self)
self.serial_reader = serial_reader
pass
# check condition for serial is compiled regular expression pattern
@staticmethod
def do_check(check_item, data):
match = check_item["CONDITION"].search(data)
if match is not None:
pos = data.find(match.group()) + len(match.group())
# notify user
check_item["NOTIFIER"]("serial", match)
else:
pos = -1
return pos
def process(self):
# do check
with self.sync_lock:
# read data
new_data = self.serial_reader()
# NativeLog.add_trace_info("[debug][read data] %s" % new_data)
# do check each item
for check_item in self.check_item_list:
# NativeLog.add_trace_info("[debug][read data][ID][%s]" % check_item["ID"])
check_item["DATA"] += new_data
self.do_check(check_item, check_item["DATA"])
time.sleep(self.SLEEP_TIME)
# handle PC TCP server accept and notify user
class TCPServerChecker(CheckerBase):
def __init__(self, server_sock):
CheckerBase.__init__(self)
self.server_sock = server_sock
server_sock.settimeout(self.SLEEP_TIME)
self.<API key> = []
# check condition for tcp accepted sock is tcp source port
@staticmethod
def do_check(check_item, data):
for sock_addr_pair in data:
addr = sock_addr_pair[1]
if addr[1] == check_item["CONDITION"]:
# same port, so this is the socket that matched, notify and remove it from list
check_item["NOTIFIER"]("tcp", sock_addr_pair[0])
data.remove(sock_addr_pair)
def process(self):
# do accept
try:
client_sock, addr = self.server_sock.accept()
self.<API key>.append((client_sock, addr))
except socket.error:
pass
# do check
with self.sync_lock:
check_item_list = self.check_item_list
for check_item in check_item_list:
self.do_check(check_item, self.<API key>)
pass
# this thread handles one tcp connection.
class ConnectionHandler(threading.Thread):
CHECK_FREQ = CheckerBase.SLEEP_TIME/2
def __init__(self, utility, serial_checker, tcp_checker, connect_method, disconnect_method, test_case):
threading.Thread.__init__(self)
self.setDaemon(True)
self.utility = utility
self.connect_method = connect_method
self.disconnect_method = disconnect_method
self.exit_event = threading.Event()
# following members are used in communication with checker threads
self.serial_checker = serial_checker
self.tcp_checker = tcp_checker
self.serial_notify_event = threading.Event()
self.tcp_notify_event = threading.Event()
self.serial_result = None
self.tcp_result = None
self.<API key> = None
self.tcp_check_item_id = None
self.data_cache = None
self.fail_count = 0
self.test_case = test_case
pass
def log_error(self):
self.fail_count += 1
if self.fail_count > MAX_FAIL_COUNT:
self.test_case.error_detected()
def <API key>(self):
connection = dict.fromkeys(<API key>, None)
connection["Connection handler"] = self
return connection
def run(self):
while self.exit_event.isSet() is False:
connection = self.<API key>()
# do connect
<API key> = random.choice(self.connect_method)
if self.utility.execute_tcp_method(<API key>, connection) is False:
self.log_error()
# check if established
if self.utility.<API key>(connection) is True:
time.sleep(float(random.randint(DELAY_RANGE[0], DELAY_RANGE[1]))/1000)
# do disconnect if established
<API key> = random.choice(self.disconnect_method)
if self.utility.execute_tcp_method(<API key>, connection) is False:
self.log_error()
# make sure target socket closed
self.utility.close_connection(connection)
time.sleep(float(random.randint(DELAY_RANGE[0], DELAY_RANGE[1]))/1000)
pass
# serial_condition: re string
# tcp_condition: target local port
def add_checkers(self, serial_condition=None, tcp_condition=None):
# cleanup
self.serial_result = None
self.tcp_result = None
self.serial_notify_event.clear()
self.tcp_notify_event.clear()
# serial_checker
if serial_condition is not None:
pattern = re.compile(serial_condition)
self.<API key> = self.serial_checker.add_check_item(pattern, self.notifier)
else:
# set event so that serial check always pass
self.serial_notify_event.set()
if tcp_condition is not None:
self.tcp_check_item_id = self.tcp_checker.add_check_item(tcp_condition, self.notifier)
else:
# set event so that tcp check always pass
self.tcp_notify_event.set()
# NativeLog.add_trace_info("[Debug] add check item %s, connection is %s" % (self.<API key>, self))
pass
def get_checker_results(self, timeout=5):
time1 = time.time()
while time.time() - time1 < timeout:
# if one type of checker is not set, its event will be set in add_checkers
if self.serial_notify_event.isSet() is True and self.tcp_notify_event.isSet() is True:
break
time.sleep(self.CHECK_FREQ)
# do cleanup
# NativeLog.add_trace_info("[Debug] remove check item %s, connection is %s" % (self.<API key>, self))
self.data_cache = self.serial_checker.remove_check_item(self.<API key>)
self.tcp_checker.remove_check_item(self.tcp_check_item_id)
# self.<API key> = None
# self.tcp_check_item_id = None
return self.serial_result, self.tcp_result
def notifier(self, typ, result):
if typ == "serial":
self.serial_notify_event.set()
self.serial_result = result
elif typ == "tcp":
self.tcp_notify_event.set()
self.tcp_result = result
def exit(self):
self.exit_event.set()
pass
class TestCase(PerformanceTCBase.PerformanceTCBase):
def __init__(self, test_case, test_env, timeout=120, log_path=None):
PerformanceTCBase.PerformanceTCBase.__init__(self, test_case, test_env,
timeout=timeout, log_path=log_path)
self.max_connection = 5
self.execute_time = 120 # execute time default 120 minutes
self.pc_ip = "pc_ip"
self.target_ip = "target_ip"
self.connect_method = ["C_01"]
self.disconnect_method = ["D_05"]
cmd_set = test_case["cmd set"]
# load param from excel
for i in range(1, len(cmd_set)):
if cmd_set[i][0] != "dummy":
cmd_string = "self." + cmd_set[i][0]
exec cmd_string
self.error_event = threading.Event()
self.serial_lock = threading.Lock()
pass
def serial_reader(self):
return self.serial_read_data("SSC1")
def send_ssc_command(self, data):
with self.serial_lock:
time.sleep(0.05)
self.serial_write_line("SSC1", data)
def error_detected(self):
self.error_event.set()
def process(self):
# parameters
max_connection = self.max_connection
execute_time = self.execute_time * 60
pc_ip = self.get_parameter(self.pc_ip)
target_ip = self.get_parameter(self.target_ip)
connect_method = self.connect_method
disconnect_method = self.disconnect_method
server_port = random.randint(30000, 50000)
# step 1, create TCP server on target and PC
# create TCP server on target
self.serial_write_line("SSC1", "soc -B -t TCP -p %s" % server_port)
match = self.<API key>("SSC1", re.compile("BIND:(\d+),OK"))
if match is None:
NativeLog.add_prompt_trace("Failed to create TCP server on target")
return
target_sock_id = match.group(1)
self.serial_write_line("SSC1", "soc -L -s %s" % target_sock_id)
if self.check_response("SSC1", "+LISTEN:%s,OK" % target_sock_id) is False:
NativeLog.add_prompt_trace("Failed to create TCP server on target")
return
# create TCP server on PC
try:
server_sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
server_sock.bind((pc_ip, server_port))
server_sock.listen(5)
except StandardError:
NativeLog.add_prompt_trace("Failed to create TCP server on PC")
return
# step 2, create checker
serial_port_checker = SerialPortChecker(self.serial_reader)
tcp_server_checker = TCPServerChecker(server_sock)
serial_port_checker.start()
tcp_server_checker.start()
# step 3, create 5 thread and do connection
utility = <API key>.Utility(self, server_port, server_port, pc_ip, target_ip)
work_thread = []
for i in range(max_connection):
t = ConnectionHandler(utility, serial_port_checker, tcp_server_checker,
connect_method, disconnect_method, self)
work_thread.append(t)
t.start()
# step 4, wait and exit
self.error_event.wait(execute_time)
# close all threads
for t in work_thread:
t.exit()
t.join()
serial_port_checker.exit()
tcp_server_checker.exit()
serial_port_checker.join()
tcp_server_checker.join()
if self.error_event.isSet() is False:
# no error detected
self.set_result("Succeed")
pass
def main():
pass
if __name__ == '__main__':
main() |
<p><code>List of <i>features</i>. Default is the empty list.</code></p>
<p><i>Features</i> on a rule modify the <i>features</i> currently enabled on
the <a href="#package">package</a> level via the <i>features</i> attribute.<br/>
For example, if the features ['a', 'b'] are enabled on the package level,
and a rule <i>features</i> attribute contains ['-a', 'c'], the features
enabled for the rule will be 'b' and 'c'.
</p> |
/ [<API key>.ts]
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
class C {
private foo: string;
private static bar: string;
}
class D extends C {
baz: number;
}
module D {
export var y = D.bar; // error
}
/ [<API key>.js]
// Any attempt to access a private property member outside the class body that contains its declaration results in a compile-time error.
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 C = (function () {
function C() {
}
return C;
}());
var D = (function (_super) {
__extends(D, _super);
function D() {
_super.apply(this, arguments);
}
return D;
}(C));
var D;
(function (D) {
D.y = D.bar; // error
})(D || (D = {})); |
package org.mamute.integration.pages;
import static java.util.Arrays.asList;
import static org.openqa.selenium.By.tagName;
import java.util.ArrayList;
import java.util.List;
import org.mamute.model.VoteType;
import org.openqa.selenium.By;
import org.openqa.selenium.<API key>;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class QuestionPage extends PageObject{
public QuestionPage(WebDriver driver) {
super(driver);
}
public EditQuestionPage toEditQuestionPage(){
byClassName("edit-question").click();
return new EditQuestionPage(driver);
}
public boolean hasInformation(String title, String description, String tags) {
return hasTitle(title) && hasDescription(description) && hasTags(tags);
}
private boolean hasTitle(String questionTitle) {
return questionTitle.equals(byClassName("question-title").getText());
}
private boolean hasDescription(String questionDescription) {
return questionDescription.equals(byClassName("<API key>").getText());
}
private boolean hasTags(String tags) {
WebElement question = byClassName("question-area");
List<String> tagNames = asList(tags.split(" "));
List<WebElement> tagsElements = question.findElements(By.className("tag"));
for (WebElement tagElement: tagsElements) {
if(!tagNames.contains(tagElement.getText())) return false;
}
return true;
}
public QuestionPage voteQuestion(VoteType type) {
int voteCount = questionVoteCount();
String voteTypeClass = type.name().toLowerCase() + "-vote";
byCSS(".question-area ." + voteTypeClass).click();
Integer finalVoteCount = voteCount + type.getCountValue();
waitForTextIn(By.cssSelector(<API key>()), finalVoteCount.toString(), 5);
return this;
}
public int questionVoteCount() {
byCSS(<API key>()).getText();
return Integer.parseInt(byCSS(<API key>()).getText());
}
private String <API key>() {
return ".question-area .vote-count";
}
public QuestionPage voteFirstAnswer(VoteType type) {
int initialVoteCount = <API key>();
String voteTypeClass = type.name().toLowerCase() + "-vote";
byCSS(".answer ." + voteTypeClass).click();
Integer finalVoteCount = initialVoteCount + type.getCountValue();
waitForTextIn(By.cssSelector(".answer .vote-count"), finalVoteCount.toString(), 10);
return this;
}
public int <API key>() {
String text = firstAnswer().findElement(By.className("vote-count")).getText();
return Integer.parseInt(text);
}
public EditAnswerPage <API key>() {
firstAnswer().findElement(By.className("edit")).click();
return new EditAnswerPage(driver);
}
public QuestionPage answer(String description) {
WebElement answerForm = byClassName("answer-form");
byCSS("#wmd-input").sendKeys("");
By buttonSelector = By.cssSelector(".<API key> button");
if (isElementPresent(buttonSelector, answerForm)) {
<API key>(buttonSelector, 5);
answerForm.findElement(buttonSelector).click();
}
byCSS("#wmd-input").sendKeys(description);
answerForm.submit();
return new QuestionPage(driver);
}
public boolean <API key>(String newDescription) {
return newDescription.equals(firstAnswer().findElement(By.className("post-text")).getText());
}
private WebElement firstAnswer() {
waitForElement(By.className("answer"), 3);
return byClassName("answer");
}
public QuestionPage commentQuestion(String comment) {
comment(".post-container", comment);
return this;
}
public QuestionPage commentFirstAnswer(String comment) {
comment(".answer .post-container", comment);
return this;
}
private void comment(String postContainer, String comment) {
byCSS(postContainer + " .add-comment").click();
waitForElement(By.cssSelector(postContainer + " textarea[name=comment]"), 2);
byCSS(postContainer + " textarea[name=comment]").sendKeys(comment);
byCSS(postContainer + " .simple-ajax-form form .post-submit").click();
waitForElement(By.cssSelector(postContainer + " .comment-container span"), 10);
}
public boolean <API key>() {
try{
byClassName("answer-form");
return true;
}catch(<API key> e){
return false;
}
}
public boolean editedTouchHasImage() {
WebElement edited = byClassName("post-touchs").findElement(By.cssSelector(".touch.edited-touch"));
return isElementPresent(tagName("img"), edited);
}
public List<String> firstAnswerComments() {
List<WebElement> commentsElements = allByCSS(".answer .comment span p");
return toListString(commentsElements);
}
public List<String> questionComments() {
List<WebElement> commentsElements = allByCSS(".comment-container span");
return toListString(commentsElements);
}
private List<String> toListString(List<WebElement> elements) {
List<String> listString = new ArrayList<>();
for (WebElement e : elements) {
listString.add(e.getText());
}
return listString;
}
} |
// "Merge with 'case 1'" "<API key>"
class C {
void foo(int n) {
switch (n) {
case 1 -> bar("A");
case 2 -> bar("B");
case 3 -> bar("A");
case 4 -> bar("A");<caret>
}
}
void bar(String s){}
} |
<!
mermaid-js loader
<script src="https://cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js"></script>
<script>
$(function() {
let initTheme = "default";
if ($("html[mode=dark]").length > 0
|| ($("html[mode]").length == 0
&& window.matchMedia("(<API key>: dark)").matches ) ) {
initTheme = "dark";
}
let mermaidConf = {
theme: initTheme /* <default|dark|forest|neutral> */
};
/* Markdown converts to HTML */
$("pre").has("code.language-mermaid").each(function() {
let svgCode = $(this).children().html();
$(this).addClass("unloaded");
$(this).after(`<div class=\"mermaid\">${svgCode}</div>`);
});
mermaid.initialize(mermaidConf);
});
</script> |
using System;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using BindingFlags = System.Reflection.BindingFlags;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class ResultsViewTests : <API key>
{
// IEnumerable pattern not supported.
[Fact]
public void IEnumerablePattern()
{
var source =
@"using System.Collections;
class C
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", <API key>.Expandable | <API key>.ReadOnly));
}
}
// IEnumerable<T> pattern not supported.
[Fact]
public void <API key>()
{
var source =
@"using System.Collections.Generic;
class C<T>
{
private readonly IEnumerable<T> e;
internal C(IEnumerable<T> e)
{
this.e = e;
}
public IEnumerator<T> GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.Generic.IEnumerable<int> {int[]}", "o.e", <API key>.Expandable | <API key>.ReadOnly));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.IEnumerable {int[]}",
"o.e",
<API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.<API key>(o).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.<API key>(o).Items[1]"));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
struct S<T> : IEnumerable<T>
{
private readonly IEnumerable<T> e;
internal S(IEnumerable<T> e)
{
this.e = e;
}
public IEnumerator<T> GetEnumerator()
{
return this.e.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("S`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{S<int>}", "S<int>", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"o.e",
<API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "int", "new System.Linq.<API key><int>(o).Items[0]"),
EvalResult("[1]", "2", "int", "new System.Linq.<API key><int>(o).Items[1]"));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.IEnumerable {int[]}",
"o.e",
<API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.<API key>(o).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.<API key>(o).Items[1]"));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C<T> : IEnumerable<T>
{
private readonly IEnumerable<T> e;
internal C(IEnumerable<T> e)
{
this.e = e;
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return this.e.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C`1").MakeGenericType(typeof(int));
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C<int>}", "C<int>", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"e",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"o.e",
<API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult("[0]", "1", "int", "new System.Linq.<API key><int>(o).Items[0]"),
EvalResult("[1]", "2", "int", "new System.Linq.<API key><int>(o).Items[1]"));
}
}
// Results View not supported for
// IEnumerator implementation.
[Fact]
public void IEnumerator()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class C : IEnumerator<int>
{
private int[] c = new[] { 1, 2, 3 };
private int i = 0;
object IEnumerator.Current
{
get { return this.c[this.i]; }
}
int IEnumerator<int>.Current
{
get { return this.c[this.i]; }
}
bool IEnumerator.MoveNext()
{
this.i++;
return this.i < this.c.Length;
}
void IEnumerator.Reset()
{
this.i = 0;
}
void IDisposable.Dispose()
{
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"System.Collections.Generic.IEnumerator<int>.Current",
"1",
"int",
"((System.Collections.Generic.IEnumerator<int>)o).Current",
<API key>.ReadOnly),
EvalResult(
"System.Collections.IEnumerator.Current",
"1",
"object {int}",
"((System.Collections.IEnumerator)o).Current",
<API key>.ReadOnly),
EvalResult("c", "{int[3]}", "int[]", "o.c", <API key>.Expandable),
EvalResult("i", "0", "int", "o.i"));
}
}
[Fact]
public void Overrides()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A : IEnumerable<object>
{
public virtual IEnumerator<object> GetEnumerator()
{
yield return 0;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class B1 : A
{
public override IEnumerator<object> GetEnumerator()
{
yield return 1;
}
}
class B2 : A, IEnumerable<int>
{
public new IEnumerator<int> GetEnumerator()
{
yield return 2;
}
}
class B3 : A
{
public new IEnumerable<int> GetEnumerator()
{
yield return 3;
}
}
class B4 : A
{
}
class C
{
A _1 = new B1();
A _2 = new B2();
A _3 = new B3();
A _4 = new B4();
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{B1}", "A {B1}", "o._1", <API key>.Expandable),
EvalResult("_2", "{B2}", "A {B2}", "o._2", <API key>.Expandable),
EvalResult("_3", "{B3}", "A {B3}", "o._3", <API key>.Expandable),
EvalResult("_4", "{B4}", "A {B4}", "o._4", <API key>.Expandable));
// A _1 = new B1();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "1", "object {int}", "new System.Linq.<API key><object>(o._1).Items[0]"));
// A _2 = new B2();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "2", "int", "new System.Linq.<API key><int>(o._2).Items[0]"));
// A _3 = new B3();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "0", "object {int}", "new System.Linq.<API key><object>(o._3).Items[0]"));
// A _4 = new B4();
moreChildren = GetChildren(children[3]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._4, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("[0]", "0", "object {int}", "new System.Linq.<API key><object>(o._4).Items[0]"));
}
}
<summary>
Include Results View on base types
(matches legacy EE behavior).
</summary>
[Fact]
public void BaseTypes()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class A1
{
}
class B1 : A1, IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 0;
}
}
class A2
{
public IEnumerator GetEnumerator()
{
yield return 1;
}
}
class B2 : A2, IEnumerable<object>
{
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
yield return 2;
}
}
struct S : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 3;
}
}
class C
{
A1 _1 = new B1();
B2 _2 = new B2();
System.ValueType _3 = new S();
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{B1}", "A1 {B1}", "o._1", <API key>.Expandable),
EvalResult("_2", "{B2}", "B2", "o._2", <API key>.Expandable),
EvalResult("_3", "{S}", "System.ValueType {S}", "o._3", <API key>.Expandable));
// A1 _1 = new B1();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "0", "object {int}", "new System.Linq.<API key>(o._1).Items[0]"));
// B2 _2 = new B2();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "2", "object {int}", "new System.Linq.<API key><object>(o._2).Items[0]"));
// System.ValueType _3 = new S();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
Verify(GetChildren(moreChildren[0]),
EvalResult("[0]", "3", "object {int}", "new System.Linq.<API key>(o._3).Items[0]"));
}
}
[Fact]
public void Nullable()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
struct S : IEnumerable<object>
{
internal readonly object[] c;
internal S(object[] c)
{
this.c = c;
}
public IEnumerator<object> GetEnumerator()
{
foreach (var o in this.c)
{
yield return o;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class C
{
S? F = new S(new object[] { null });
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("F", "{S}", "S?", "o.F", <API key>.Expandable));
children = GetChildren(children[0]);
Verify(children,
EvalResult("c", "{object[1]}", "object[]", "o.F.c", <API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o.F, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[1]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.<API key><object>(o.F).Items[0]"));
}
}
[Fact]
public void ConstructedType()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A<T> : IEnumerable<T>
{
private readonly T[] items;
internal A(T[] items)
{
this.items = items;
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in items)
{
yield return item;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class B
{
internal object F;
}
class C : A<B>
{
internal C() : base(new[] { new B() })
{
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"items",
"{B[1]}",
"B[]",
"o.items",
<API key>.Expandable | <API key>.ReadOnly),
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
var moreChildren = GetChildren(children[1]);
Verify(moreChildren,
// The legacy EE treats the Items elements as readonly, but since
// Items is a T[], we treat the elements as read/write. However, Items
// is not updated when modifying elements so this is harmless.
EvalResult(
"[0]",
"{B}",
"B",
"new System.Linq.<API key><B>(o).Items[0]",
<API key>.Expandable));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult("F", "null", "object", "(new System.Linq.<API key><B>(o).Items[0]).F"));
}
}
<summary>
System.Array should not have Results View.
</summary>
[Fact]
public void Array()
{
var source =
@"using System;
using System.Collections;
class C
{
char[] _1 = new char[] { '1' };
Array _2 = new char[] { '2' };
IEnumerable _3 = new char[] { '3' };
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "{char[1]}", "char[]", "o._1", <API key>.Expandable),
EvalResult("_2", "{char[1]}", "System.Array {char[]}", "o._2", <API key>.Expandable),
EvalResult("_3", "{char[1]}", "System.Collections.IEnumerable {char[]}", "o._3", <API key>.Expandable));
Verify(GetChildren(children[0]),
EvalResult("[0]", "49 '1'", "char", "o._1[0]", editableValue: "'1'"));
Verify(GetChildren(children[1]),
EvalResult("[0]", "50 '2'", "char", "((char[])o._2)[0]", editableValue: "'2'"));
children = GetChildren(children[2]);
Verify(children,
EvalResult("[0]", "51 '3'", "char", "((char[])o._3)[0]", editableValue: "'3'"));
}
}
<summary>
String should not have Results View.
</summary>
[Fact]
public void String()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C
{
string _1 = ""1"";
object _2 = ""2"";
IEnumerable _3 = ""3"";
IEnumerable<char> _4 = ""4"";
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_1", "\"1\"", "string", "o._1", <API key>.RawString, editableValue: "\"1\""),
EvalResult("_2", "\"2\"", "object {string}", "o._2", <API key>.RawString, editableValue: "\"2\""),
EvalResult("_3", "\"3\"", "System.Collections.IEnumerable {string}", "o._3", <API key>.RawString, editableValue: "\"3\""),
EvalResult("_4", "\"4\"", "System.Collections.Generic.IEnumerable<char> {string}", "o._4", <API key>.RawString, editableValue: "\"4\""));
}
}
[WorkItem(1006160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1006160")]
[Fact]
public void <API key>()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A<T> : IEnumerable<T>
{
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
yield return default(T);
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class B1 : A<object>, IEnumerable<int>
{
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
}
class B2 : A<int>, IEnumerable<object>
{
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
yield return null;
}
}
class B3 : A<object>, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
yield return 3;
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
// class B1 : A<object>, IEnumerable<int>
var type = assembly.GetType("B1");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B1}", "B1", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"1",
"int",
"new System.Linq.<API key><int>(o).Items[0]"));
// class B2 : A<int>, IEnumerable<object>
type = assembly.GetType("B2");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B2}", "B2", "o", <API key>.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.<API key><object>(o).Items[0]"));
// class B3 : A<object>, IEnumerable
type = assembly.GetType("B3");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{B3}", "B3", "o", <API key>.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"object",
"new System.Linq.<API key><object>(o).Items[0]"));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
class A : IEnumerable<int>, IEnumerable<string>
{
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
yield return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class B : IEnumerable<string>, IEnumerable<int>
{
IEnumerator<string> IEnumerable<string>.GetEnumerator()
{
yield return null;
}
IEnumerator<int> IEnumerable<int>.GetEnumerator()
{
yield return 1;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
// class A : IEnumerable<int>, IEnumerable<string>
var type = assembly.GetType("A");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("a", value);
Verify(evalResult,
EvalResult("a", "{A}", "A", "a", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"a, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"1",
"int",
"new System.Linq.<API key><int>(a).Items[0]"));
// class B : IEnumerable<string>, IEnumerable<int>
type = assembly.GetType("B");
value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
evalResult = FormatResult("b", value);
Verify(evalResult,
EvalResult("b", "{B}", "B", "b", <API key>.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"b, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalResult(
"[0]",
"null",
"string",
"new System.Linq.<API key><string>(b).Items[0]"));
}
}
<summary>
Types with [DebuggerTypeProxy] should not have Results View.
</summary>
[Fact]
public void DebuggerTypeProxy()
{
var source =
@"using System.Collections;
using System.Diagnostics;
public class P : IEnumerable
{
private readonly C c;
public P(C c)
{
this.c = c;
}
public IEnumerator GetEnumerator()
{
return this.c.GetEnumerator();
}
public int Length
{
get { return this.c.o.Length; }
}
}
[DebuggerTypeProxy(typeof(P))]
public class C : IEnumerable
{
internal readonly object[] o;
public C(object[] o)
{
this.o = o;
}
public IEnumerator GetEnumerator()
{
return this.o.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new object[] { new object[] { string.Empty } }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("Length", "1", "int", "new P(o).Length", <API key>.ReadOnly),
EvalResult("Raw View", null, "", "o, raw", <API key>.Expandable | <API key>.ReadOnly, <API key>.Data));
children = GetChildren(children[1]);
Verify(children,
EvalResult("o", "{object[1]}", "object[]", "o.o", <API key>.Expandable | <API key>.ReadOnly));
}
}
<summary>
Do not expose Results View if the proxy type is missing.
</summary>
[Fact]
public void MissingProxyType()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = new[] { assembly };
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", <API key>.Expandable | <API key>.ReadOnly));
}
}
<summary>
Proxy type not in System.Core.dll.
</summary>
[Fact]
public void <API key>()
{
// "System.Core.dll"
var source0 = "";
var compilation0 = CSharpTestBase.CreateCompilation(source0, assemblyName: "system.core");
var assembly0 = ReflectionUtilities.Load(compilation0.EmitToArray());
var source =
@"using System.Collections;
class C : IEnumerable
{
private readonly IEnumerable e;
internal C(IEnumerable e)
{
this.e = e;
}
public IEnumerator GetEnumerator()
{
return this.e.GetEnumerator();
}
}";
var assembly = GetAssembly(source);
var assemblies = new[] { assembly0, assembly };
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(new[] { 1, 2 }),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("e", "{int[2]}", "System.Collections.IEnumerable {int[]}", "o.e", <API key>.Expandable | <API key>.ReadOnly));
// Verify the module was found but ResolveTypeName failed.
var module = runtime.Modules.Single(m => m.Assembly == assembly0);
Assert.Equal(module.<API key>, 1);
}
}
<summary>
Report "Enumeration yielded no results" when
GetEnumerator returns an empty collection or null.
</summary>
[Fact]
public void <API key>()
{
var source =
@"using System;
using System.Collections;
using System.Collections.Generic;
// IEnumerable returns empty collection.
class C0 : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield break;
}
}
// IEnumerable<T> returns empty collection.
class C1<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
yield break;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
// IEnumerable returns null.
class C2 : IEnumerable
{
public IEnumerator GetEnumerator()
{
return null;
}
}
// IEnumerable<T> returns null.
class C3<T> : IEnumerable<T>
{
public IEnumerator<T> GetEnumerator()
{
return null;
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new <API key>();
}
}
class C
{
C0 _0 = new C0();
C1<object> _1 = new C1<object>();
C2 _2 = new C2();
C3<object> _3 = new C3<object>();
}";
using (new <API key>())
{
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("_0", "{C0}", "C0", "o._0", <API key>.Expandable),
EvalResult("_1", "{C1<object>}", "C1<object>", "o._1", <API key>.Expandable),
EvalResult("_2", "{C2}", "C2", "o._2", <API key>.Expandable),
EvalResult("_3", "{C3<object>}", "C3<object>", "o._3", <API key>.Expandable));
// C0 _0 = new C0();
var moreChildren = GetChildren(children[0]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._0, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
<API key>.ReadOnly | <API key>.RawString));
// C1<object> _1 = new C1<object>();
moreChildren = GetChildren(children[1]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._1, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
<API key>.ReadOnly | <API key>.RawString));
// C2 _2 = new C2();
moreChildren = GetChildren(children[2]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._2, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
<API key>.ReadOnly | <API key>.RawString));
// C3<object> _3 = new C3<object>();
moreChildren = GetChildren(children[3]);
Verify(moreChildren,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o._3, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
moreChildren = GetChildren(moreChildren[0]);
Verify(moreChildren,
EvalResult(
"Empty",
"\"Enumeration yielded no results\"",
"string",
null,
<API key>.ReadOnly | <API key>.RawString));
}
}
}
<summary>
Do not instantiate proxy type for null IEnumerable.
</summary>
[WorkItem(1009646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1009646")]
[Fact]
public void IEnumerableNull()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
interface I : IEnumerable
{
}
class C
{
IEnumerable<char> E = null;
I F = null;
string S = null;
}";
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("E", "null", "System.Collections.Generic.IEnumerable<char>", "o.E"),
EvalResult("F", "null", "I", "o.F"),
EvalResult("S", "null", "string", "o.S"));
}
}
[Fact]
public void <API key>()
{
var source =
@"using System;
using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new <API key>();
}
}";
using (new <API key>())
{
var assembly = GetAssembly(source);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var type = assembly.GetType("C");
var value = CreateDkmClrValue(
value: type.Instantiate(),
type: runtime.GetType((TypeImpl)type));
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children[6],
EvalResult("Message", "\"The method or operation is not implemented.\"", "string", null, <API key>.RawString | <API key>.ReadOnly));
}
}
}
[Fact]
[WorkItem(1145125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1145125")]
[WorkItem(5666, "https://github.com/dotnet/roslyn/issues/5666")]
public void <API key>()
{
var source =
@"using System;
using System.Collections;
class E : Exception, IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
yield return 1;
}
}
class C
{
internal IEnumerable P
{
get { throw new <API key>(); }
}
internal IEnumerable Q
{
get { throw new E(); }
}
}";
using (new <API key>())
{
var runtime = new <API key>(ReflectionUtilities.<API key>(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"P",
"'o.P' threw an exception of type 'System.<API key>'",
"System.Collections.IEnumerable {System.<API key>}",
"o.P",
<API key>.Expandable | <API key>.ReadOnly | <API key>.ExceptionThrown),
EvalResult(
"Q",
"'o.Q' threw an exception of type 'E'",
"System.Collections.IEnumerable {E}",
"o.Q",
<API key>.Expandable | <API key>.ReadOnly | <API key>.ExceptionThrown));
children = GetChildren(children[1]);
Verify(children[6],
EvalResult(
"Message",
"\"Exception of type 'E' was thrown.\"",
"string",
null,
<API key>.RawString | <API key>.ReadOnly));
}
}
}
[Fact]
public void GetEnumerableError()
{
var source =
@"using System.Collections;
class C
{
bool f;
internal ArrayList P
{
get { while (!this.f) { } return new ArrayList(); }
}
}";
<API key> runtime = null;
VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "P") ? CreateErrorValue(runtime.GetType(typeof(System.Collections.ArrayList)), "Function evaluation timed out") : null;
runtime = new <API key>(ReflectionUtilities.<API key>(GetAssembly(source)), getMemberValue: getMemberValue);
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var memberValue = value.GetMemberValue("P", (int)System.Reflection.MemberTypes.Property, "C", <API key>);
var evalResult = FormatResult("o.P", memberValue);
Verify(evalResult,
EvalFailedResult("o.P", "Function evaluation timed out", "System.Collections.ArrayList", "o.P"));
}
}
<summary>
If evaluation of the proxy Items property returns an error
(say, evaluation of the enumerable requires func-eval and
either func-eval is disabled or we're debugging a .dmp),
we should include a row that reports the error rather than
having an empty expansion (since the container Items property
is [DebuggerBrowsable(<API key>.RootHidden)]).
Note, the native EE has an empty expansion when .dmp debugging.
</summary>
[WorkItem(1043746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1043746")]
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
class C : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return 1;
}
}";
<API key> runtime = null;
VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue getMemberValue(VisualStudio.Debugger.Evaluation.ClrCompilation.DkmClrValue v, string m) => (m == "Items") ? CreateErrorValue(runtime.GetType(typeof(object)).MakeArrayType(), string.Format("Unable to evaluate '{0}'", m)) : null;
runtime = new <API key>(ReflectionUtilities.<API key>(GetAssembly(source)), getMemberValue: getMemberValue);
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.Instantiate();
var evalResult = FormatResult("o", value);
Verify(evalResult,
EvalResult("o", "{C}", "C", "o", <API key>.Expandable));
var children = GetChildren(evalResult);
Verify(children,
EvalResult(
"Results View",
"Expanding the Results View will enumerate the IEnumerable",
"",
"o, results",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(children[0]);
Verify(children,
EvalFailedResult("Error", "Unable to evaluate 'Items'", flags: <API key>.None));
}
}
<summary>
Root-level synthetic values declared as IEnumerable or
IEnumerable<T> should be expanded directly
without intermediate "Results View" row.
</summary>
[WorkItem(1114276, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114276")]
[Fact]
public void <API key>()
{
var source =
@"using System.Collections;
using System.Collections.Generic;
class C
{
IEnumerable P { get { yield return 1; yield return 2; } }
IEnumerable<int> Q { get { yield return 3; } }
IEnumerable R { get { return null; } }
IEnumerable S { get { return string.Empty; } }
IEnumerable<int> T { get { return new int[] { 4, 5 }; } }
IList<int> U { get { return new List<int>(new int[] { 6 }); } }
}";
var runtime = new <API key>(ReflectionUtilities.<API key>(GetAssembly(source)));
using (runtime.Load())
{
var type = runtime.GetType("C");
var value = type.UnderlyingType.Instantiate();
// IEnumerable
var evalResult = FormatPropertyValue(runtime, value, "P");
Verify(evalResult,
EvalResult(
"P",
"{C.<get_P>d__1}",
"System.Collections.IEnumerable {C.<get_P>d__1}",
"P",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
var children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "1", "object {int}", "new System.Linq.<API key>(P).Items[0]"),
EvalResult("[1]", "2", "object {int}", "new System.Linq.<API key>(P).Items[1]"));
// IEnumerable<int>
evalResult = FormatPropertyValue(runtime, value, "Q");
Verify(evalResult,
EvalResult(
"Q",
"{C.<get_Q>d__3}",
"System.Collections.Generic.IEnumerable<int> {C.<get_Q>d__3}",
"Q",
<API key>.Expandable | <API key>.ReadOnly,
<API key>.Method));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "3", "int", "new System.Linq.<API key><int>(Q).Items[0]"));
// null (unchanged)
evalResult = FormatPropertyValue(runtime, value, "R");
Verify(evalResult,
EvalResult(
"R",
"null",
"System.Collections.IEnumerable",
"R",
<API key>.None));
// string (unchanged)
evalResult = FormatPropertyValue(runtime, value, "S");
Verify(evalResult,
EvalResult(
"S",
"\"\"",
"System.Collections.IEnumerable {string}",
"S",
<API key>.RawString,
<API key>.Other,
editableValue: "\"\""));
// array (unchanged)
evalResult = FormatPropertyValue(runtime, value, "T");
Verify(evalResult,
EvalResult(
"T",
"{int[2]}",
"System.Collections.Generic.IEnumerable<int> {int[]}",
"T",
<API key>.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "4", "int", "((int[])T)[0]"),
EvalResult("[1]", "5", "int", "((int[])T)[1]"));
// IList<int> declared type (unchanged)
evalResult = FormatPropertyValue(runtime, value, "U");
Verify(evalResult,
EvalResult(
"U",
"Count = 1",
"System.Collections.Generic.IList<int> {System.Collections.Generic.List<int>}",
"U",
<API key>.Expandable));
children = GetChildren(evalResult);
Verify(children,
EvalResult("[0]", "6", "int", "new System.Collections.Generic.<API key><int>(U).Items[0]"),
EvalResult("Raw View", null, "", "U, raw", <API key>.Expandable | <API key>.ReadOnly, <API key>.Data));
}
}
[WorkItem(4098, "https://github.com/dotnet/roslyn/issues/4098")]
[Fact]
public void <API key>()
{
var code =
@"using System.Collections.Generic;
using System.Linq;
class C
{
static void M(List<int> list)
{
var result = from x in list from y in list where x > 0 select new { x, y };
}
}";
var assembly = GetAssembly(code);
var assemblies = ReflectionUtilities.<API key>(assembly);
using (ReflectionUtilities.LoadAssemblies(assemblies))
{
var runtime = new <API key>(assemblies);
var anonymousType = assembly.GetType("<>f__AnonymousType0`2").MakeGenericType(typeof(int), typeof(int));
var type = typeof(Enumerable).GetNestedType("<API key>`2", BindingFlags.NonPublic).MakeGenericType(anonymousType, anonymousType);
var displayClass = assembly.GetType("C+<>c");
var instance = displayClass.Instantiate();
var ctor = type.GetConstructors().Single();
var parameters = ctor.GetParameters();
var listType = typeof(List<>).MakeGenericType(anonymousType);
var source = listType.Instantiate();
listType.GetMethod("Add").Invoke(source, new[] { anonymousType.Instantiate(1, 1) });
var predicate = Delegate.CreateDelegate(parameters[1].ParameterType, instance, displayClass.GetMethod("<M>b__0_2", BindingFlags.Instance | BindingFlags.NonPublic));
var selector = Delegate.CreateDelegate(parameters[2].ParameterType, instance, displayClass.GetMethod("<M>b__0_3", BindingFlags.Instance | BindingFlags.NonPublic));
var value = CreateDkmClrValue(
value: type.Instantiate(source, predicate, selector),
type: runtime.GetType((TypeImpl)type));
var expr = "from x in my_list from y in my_list where x > 0 select new { x, y }";
var typeName = "System.Linq.Enumerable.<API key><<>f__AnonymousType0<int, int>, <>f__AnonymousType0<int, int>>";
var name = expr + ";";
var evalResult = FormatResult(name, value);
Verify(evalResult,
EvalResult(name, $"{{{typeName}}}", typeName, expr, <API key>.Expandable));
var resultsViewRow = GetChildren(evalResult).Last();
Verify(GetChildren(resultsViewRow),
EvalResult(
"[0]",
"{{ x = 1, y = 1 }}",
"<>f__AnonymousType0<int, int>",
null,
<API key>.Expandable));
name = expr + ", results";
evalResult = FormatResult(name, value, inspectionContext: <API key>(DkmEvaluationFlags.ResultsOnly));
Verify(evalResult,
EvalResult(name, $"{{{typeName}}}", typeName, name, <API key>.Expandable | <API key>.ReadOnly));
Verify(GetChildren(evalResult),
EvalResult(
"[0]",
"{{ x = 1, y = 1 }}",
"<>f__AnonymousType0<int, int>",
null,
<API key>.Expandable));
}
}
private DkmEvaluationResult FormatPropertyValue(<API key> runtime, object value, string propertyName)
{
var propertyInfo = value.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var propertyValue = propertyInfo.GetValue(value);
var propertyType = runtime.GetType(propertyInfo.PropertyType);
var valueType = (propertyValue == null) ? propertyType : runtime.GetType(propertyValue.GetType());
return FormatResult(
propertyName,
CreateDkmClrValue(propertyValue, type: valueType, valueFlags: DkmClrValueFlags.Synthetic),
declaredType: propertyType);
}
}
} |
#ifndef R600_PRIV_H
#define R600_PRIV_H
#include "radeonsi_pipe.h"
#include "util/u_hash_table.h"
#include "os/os_thread.h"
#define <API key> 18
#define PKT_COUNT_C 0xC000FFFF
#define PKT_COUNT_S(x) (((x) & 0x3FFF) << 16)
static INLINE unsigned <API key>(struct r600_context *ctx, struct si_resource *rbo,
enum radeon_bo_usage usage)
{
assert(usage);
return ctx->ws->cs_add_reloc(ctx->cs, rbo->cs_buf, usage, rbo->domains) * 4;
}
#endif |
import {
moduleForComponent,
test
} from 'ember-qunit';
moduleForComponent('<API key>', '<API key>', {
// specify the other units that are required for this test
needs: ['component:text-area', 'component:bs-button']
});
test('it renders', function() {
expect(2);
// creates the component instance
var component = this.subject();
equal(component._state, 'preRender');
// appends the component to the page
this.append();
equal(component._state, 'inDOM');
}); |
#include "layout.h"
#include <limits>
#include <vector>
#include "gdef.h"
// OpenType Layout Common Table Formats
namespace {
// The 'DFLT' tag of script table.
const uint32_t kScriptTableTagDflt = 0x44464c54;
// The value which represents there is no required feature index.
const uint16_t <API key> = 0xFFFF;
// The lookup flag bit which indicates existence of MarkFilteringSet.
const uint16_t <API key> = 0x0010;
// The lookup flags which require GDEF table.
const uint16_t kGdefRequiredFlags = 0x0002 | 0x0004 | 0x0008;
// The mask for MarkAttachmentType.
const uint16_t <API key> = 0xFF00;
// The maximum type number of format for device tables.
const uint16_t kMaxDeltaFormatType = 3;
// The maximum number of class value.
const uint16_t kMaxClassDefValue = 0xFFFF;
struct ScriptRecord {
uint32_t tag;
uint16_t offset;
};
struct LangSysRecord {
uint32_t tag;
uint16_t offset;
};
struct FeatureRecord {
uint32_t tag;
uint16_t offset;
};
bool ParseLangSysTable(ots::Buffer *subtable, const uint32_t tag,
const uint16_t num_features) {
uint16_t offset_lookup_order = 0;
uint16_t req_feature_index = 0;
uint16_t feature_count = 0;
if (!subtable->ReadU16(&offset_lookup_order) ||
!subtable->ReadU16(&req_feature_index) ||
!subtable->ReadU16(&feature_count)) {
return OTS_FAILURE();
}
// |offset_lookup_order| is reserved and should be NULL.
if (offset_lookup_order != 0) {
return OTS_FAILURE();
}
if (req_feature_index != <API key> &&
req_feature_index >= num_features) {
return OTS_FAILURE();
}
if (feature_count > num_features) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < feature_count; ++i) {
uint16_t feature_index = 0;
if (!subtable->ReadU16(&feature_index)) {
return OTS_FAILURE();
}
if (feature_index >= num_features) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseScriptTable(const uint8_t *data, const size_t length,
const uint32_t tag, const uint16_t num_features) {
ots::Buffer subtable(data, length);
uint16_t <API key> = 0;
uint16_t lang_sys_count = 0;
if (!subtable.ReadU16(&<API key>) ||
!subtable.ReadU16(&lang_sys_count)) {
return OTS_FAILURE();
}
// The spec requires a script table for 'DFLT' tag must contain non-NULL
// |<API key>| and |lang_sys_count| == 0
if (tag == kScriptTableTagDflt &&
(<API key> == 0 || lang_sys_count != 0)) {
OTS_WARNING("DFLT table doesn't satisfy the spec.");
return OTS_FAILURE();
}
const unsigned lang_sys_record_end =
6 * static_cast<unsigned>(lang_sys_count) + 4;
if (lang_sys_record_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
std::vector<LangSysRecord> lang_sys_records;
lang_sys_records.resize(lang_sys_count);
uint32_t last_tag = 0;
for (unsigned i = 0; i < lang_sys_count; ++i) {
if (!subtable.ReadU32(&lang_sys_records[i].tag) ||
!subtable.ReadU16(&lang_sys_records[i].offset)) {
return OTS_FAILURE();
}
// The record array must store the records alphabetically by tag
if (last_tag != 0 && last_tag > lang_sys_records[i].tag) {
return OTS_FAILURE();
}
if (lang_sys_records[i].offset < lang_sys_record_end ||
lang_sys_records[i].offset >= length) {
OTS_WARNING("bad offset to lang sys table: %x",
lang_sys_records[i].offset);
return OTS_FAILURE();
}
last_tag = lang_sys_records[i].tag;
}
// Check lang sys tables
for (unsigned i = 0; i < lang_sys_count; ++i) {
subtable.set_offset(lang_sys_records[i].offset);
if (!ParseLangSysTable(&subtable, lang_sys_records[i].tag, num_features)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseFeatureTable(const uint8_t *data, const size_t length,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t <API key> = 0;
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&<API key>) ||
!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
const unsigned feature_table_end =
2 * static_cast<unsigned>(lookup_count) + 4;
if (feature_table_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
// |<API key>| is generally set to NULL.
if (<API key> != 0 &&
(<API key> < feature_table_end ||
<API key> >= length)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookup_count; ++i) {
uint16_t lookup_index = 0;
if (!subtable.ReadU16(&lookup_index)) {
return OTS_FAILURE();
}
// lookup index starts with 0.
if (lookup_index >= num_lookups) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseLookupTable(ots::OpenTypeFile *file, const uint8_t *data,
const size_t length,
const ots::<API key>* parser) {
ots::Buffer subtable(data, length);
uint16_t lookup_type = 0;
uint16_t lookup_flag = 0;
uint16_t subtable_count = 0;
if (!subtable.ReadU16(&lookup_type) ||
!subtable.ReadU16(&lookup_flag) ||
!subtable.ReadU16(&subtable_count)) {
return OTS_FAILURE();
}
if (lookup_type == 0 || lookup_type > parser->num_types) {
return OTS_FAILURE();
}
// Check lookup flags.
if ((lookup_flag & kGdefRequiredFlags) &&
(!file->gdef || !file->gdef->has_glyph_class_def)) {
return OTS_FAILURE();
}
if ((lookup_flag & <API key>) &&
(!file->gdef || !file->gdef-><API key>)) {
return OTS_FAILURE();
}
bool <API key> = false;
if (lookup_flag & <API key>) {
if (!file->gdef || !file->gdef-><API key>) {
return OTS_FAILURE();
}
<API key> = true;
}
std::vector<uint16_t> subtables;
subtables.reserve(subtable_count);
// If the |<API key>| of |lookup_flag| is set,
// extra 2 bytes will follow after subtable offset array.
const unsigned lookup_table_end = 2 * static_cast<unsigned>(subtable_count) +
(<API key> ? 8 : 6);
if (lookup_table_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < subtable_count; ++i) {
uint16_t offset_subtable = 0;
if (!subtable.ReadU16(&offset_subtable)) {
return OTS_FAILURE();
}
if (offset_subtable < lookup_table_end ||
offset_subtable >= length) {
return OTS_FAILURE();
}
subtables.push_back(offset_subtable);
}
if (subtables.size() != subtable_count) {
return OTS_FAILURE();
}
if (<API key>) {
uint16_t mark_filtering_set = 0;
if (!subtable.ReadU16(&mark_filtering_set)) {
return OTS_FAILURE();
}
if (file->gdef->num_mark_glyph_sets == 0 ||
mark_filtering_set >= file->gdef->num_mark_glyph_sets) {
return OTS_FAILURE();
}
}
// Parse lookup subtables for this lookup type.
for (unsigned i = 0; i < subtable_count; ++i) {
if (!parser->Parse(file, data + subtables[i], length - subtables[i],
lookup_type)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t num_classes) {
ots::Buffer subtable(data, length);
// Skip format field.
if (!subtable.Skip(2)) {
return OTS_FAILURE();
}
uint16_t start_glyph = 0;
if (!subtable.ReadU16(&start_glyph)) {
return OTS_FAILURE();
}
if (start_glyph > num_glyphs) {
OTS_WARNING("bad start glyph ID: %u", start_glyph);
return OTS_FAILURE();
}
uint16_t glyph_count = 0;
if (!subtable.ReadU16(&glyph_count)) {
return OTS_FAILURE();
}
if (glyph_count > num_glyphs) {
OTS_WARNING("bad glyph count: %u", glyph_count);
return OTS_FAILURE();
}
for (unsigned i = 0; i < glyph_count; ++i) {
uint16_t class_value = 0;
if (!subtable.ReadU16(&class_value)) {
return OTS_FAILURE();
}
if (class_value > num_classes) {
OTS_WARNING("bad class value: %u", class_value);
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t num_classes) {
ots::Buffer subtable(data, length);
// Skip format field.
if (!subtable.Skip(2)) {
return OTS_FAILURE();
}
uint16_t range_count = 0;
if (!subtable.ReadU16(&range_count)) {
return OTS_FAILURE();
}
if (range_count > num_glyphs) {
OTS_WARNING("bad range count: %u", range_count);
return OTS_FAILURE();
}
uint16_t last_end = 0;
for (unsigned i = 0; i < range_count; ++i) {
uint16_t start = 0;
uint16_t end = 0;
uint16_t class_value = 0;
if (!subtable.ReadU16(&start) ||
!subtable.ReadU16(&end) ||
!subtable.ReadU16(&class_value)) {
return OTS_FAILURE();
}
if (start > end || (last_end && start <= last_end)) {
OTS_WARNING("glyph range is overlapping.");
return OTS_FAILURE();
}
if (class_value > num_classes) {
OTS_WARNING("bad class value: %u", class_value);
return OTS_FAILURE();
}
last_end = end;
}
return true;
}
bool <API key>(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t expected_num_glyphs) {
ots::Buffer subtable(data, length);
// Skip format field.
if (!subtable.Skip(2)) {
return OTS_FAILURE();
}
uint16_t glyph_count = 0;
if (!subtable.ReadU16(&glyph_count)) {
return OTS_FAILURE();
}
if (glyph_count > num_glyphs) {
OTS_WARNING("bad glyph count: %u", glyph_count);
return OTS_FAILURE();
}
for (unsigned i = 0; i < glyph_count; ++i) {
uint16_t glyph = 0;
if (!subtable.ReadU16(&glyph)) {
return OTS_FAILURE();
}
if (glyph > num_glyphs) {
OTS_WARNING("bad glyph ID: %u", glyph);
return OTS_FAILURE();
}
}
if (expected_num_glyphs && expected_num_glyphs != glyph_count) {
OTS_WARNING("unexpected number of glyphs: %u", glyph_count);
return OTS_FAILURE();
}
return true;
}
bool <API key>(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t expected_num_glyphs) {
ots::Buffer subtable(data, length);
// Skip format field.
if (!subtable.Skip(2)) {
return OTS_FAILURE();
}
uint16_t range_count = 0;
if (!subtable.ReadU16(&range_count)) {
return OTS_FAILURE();
}
if (range_count > num_glyphs) {
OTS_WARNING("bad range count: %u", range_count);
return OTS_FAILURE();
}
uint16_t last_end = 0;
uint16_t <API key> = 0;
for (unsigned i = 0; i < range_count; ++i) {
uint16_t start = 0;
uint16_t end = 0;
uint16_t <API key> = 0;
if (!subtable.ReadU16(&start) ||
!subtable.ReadU16(&end) ||
!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
// Some of the Adobe Pro fonts have ranges that overlap by one element: the
// start of one range is equal to the end of the previous range. Therefore
// the < in the following condition should be <= were it not for this.
// See crbug.com/134135.
if (start > end || (last_end && start < last_end)) {
OTS_WARNING("glyph range is overlapping.");
return OTS_FAILURE();
}
if (<API key> != <API key>) {
OTS_WARNING("bad start coverage index.");
return OTS_FAILURE();
}
last_end = end;
<API key> += end - start + 1;
}
if (expected_num_glyphs &&
expected_num_glyphs != <API key>) {
OTS_WARNING("unexpected number of glyphs: %u", <API key>);
return OTS_FAILURE();
}
return true;
}
// Parsers for Contextual subtables in GSUB/GPOS tables.
bool ParseLookupRecord(ots::Buffer *subtable, const uint16_t num_glyphs,
const uint16_t num_lookups) {
uint16_t sequence_index = 0;
uint16_t lookup_list_index = 0;
if (!subtable->ReadU16(&sequence_index) ||
!subtable->ReadU16(&lookup_list_index)) {
return OTS_FAILURE();
}
if (sequence_index >= num_glyphs) {
return OTS_FAILURE();
}
if (lookup_list_index >= num_lookups) {
return OTS_FAILURE();
}
return true;
}
bool ParseRuleSubtable(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t glyph_count = 0;
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&glyph_count) ||
!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
if (glyph_count == 0 || glyph_count >= num_glyphs) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < glyph_count - static_cast<unsigned>(1); ++i) {
uint16_t glyph_id = 0;
if (!subtable.ReadU16(&glyph_id)) {
return OTS_FAILURE();
}
if (glyph_id > num_glyphs) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseRuleSetTable(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t rule_count = 0;
if (!subtable.ReadU16(&rule_count)) {
return OTS_FAILURE();
}
const unsigned rule_end = 2 * static_cast<unsigned>(rule_count) + 2;
if (rule_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < rule_count; ++i) {
uint16_t offset_rule = 0;
if (!subtable.ReadU16(&offset_rule)) {
return OTS_FAILURE();
}
if (offset_rule < rule_end || offset_rule >= length) {
return OTS_FAILURE();
}
if (!ParseRuleSubtable(data + offset_rule, length - offset_rule,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseContextFormat1(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t offset_coverage = 0;
uint16_t rule_set_count = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&offset_coverage) ||
!subtable.ReadU16(&rule_set_count)) {
return OTS_FAILURE();
}
const unsigned rule_set_end = static_cast<unsigned>(6) +
rule_set_count * 2;
if (rule_set_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
if (offset_coverage < rule_set_end || offset_coverage >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offset_coverage,
length - offset_coverage, num_glyphs)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < rule_set_count; ++i) {
uint16_t offset_rule = 0;
if (!subtable.ReadU16(&offset_rule)) {
return OTS_FAILURE();
}
if (offset_rule < rule_set_end || offset_rule >= length) {
return OTS_FAILURE();
}
if (!ParseRuleSetTable(data + offset_rule, length - offset_rule,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseClassRuleTable(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t glyph_count = 0;
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&glyph_count) ||
!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
if (glyph_count == 0 || glyph_count >= num_glyphs) {
return OTS_FAILURE();
}
// ClassRule table contains an array of classes. Each value of classes
// could take arbitrary values including zero so we don't check these value.
const unsigned num_classes = glyph_count - static_cast<unsigned>(1);
if (!subtable.Skip(2 * num_classes)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseClassSetTable(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t class_rule_count = 0;
if (!subtable.ReadU16(&class_rule_count)) {
return OTS_FAILURE();
}
const unsigned class_rule_end =
2 * static_cast<unsigned>(class_rule_count) + 2;
if (class_rule_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < class_rule_count; ++i) {
uint16_t offset_class_rule = 0;
if (!subtable.ReadU16(&offset_class_rule)) {
return OTS_FAILURE();
}
if (offset_class_rule < class_rule_end || offset_class_rule >= length) {
return OTS_FAILURE();
}
if (!ParseClassRuleTable(data + offset_class_rule,
length - offset_class_rule, num_glyphs,
num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseContextFormat2(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t offset_coverage = 0;
uint16_t offset_class_def = 0;
uint16_t class_set_cnt = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&offset_coverage) ||
!subtable.ReadU16(&offset_class_def) ||
!subtable.ReadU16(&class_set_cnt)) {
return OTS_FAILURE();
}
const unsigned class_set_end = 2 * static_cast<unsigned>(class_set_cnt) + 8;
if (class_set_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
if (offset_coverage < class_set_end || offset_coverage >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offset_coverage,
length - offset_coverage, num_glyphs)) {
return OTS_FAILURE();
}
if (offset_class_def < class_set_end || offset_class_def >= length) {
return OTS_FAILURE();
}
if (!ots::ParseClassDefTable(data + offset_class_def,
length - offset_class_def,
num_glyphs, kMaxClassDefValue)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < class_set_cnt; ++i) {
uint16_t offset_class_rule = 0;
if (!subtable.ReadU16(&offset_class_rule)) {
return OTS_FAILURE();
}
if (offset_class_rule) {
if (offset_class_rule < class_set_end || offset_class_rule >= length) {
return OTS_FAILURE();
}
if (!ParseClassSetTable(data + offset_class_rule,
length - offset_class_rule, num_glyphs,
num_lookups)) {
return OTS_FAILURE();
}
}
}
return true;
}
bool ParseContextFormat3(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t glyph_count = 0;
uint16_t lookup_count = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&glyph_count) ||
!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
if (glyph_count >= num_glyphs) {
return OTS_FAILURE();
}
const unsigned lookup_record_end = 2 * static_cast<unsigned>(glyph_count) +
4 * static_cast<unsigned>(lookup_count) + 6;
if (lookup_record_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < glyph_count; ++i) {
uint16_t offset_coverage = 0;
if (!subtable.ReadU16(&offset_coverage)) {
return OTS_FAILURE();
}
if (offset_coverage < lookup_record_end || offset_coverage >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offset_coverage,
length - offset_coverage, num_glyphs)) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
// Parsers for Chaning Contextual subtables in GSUB/GPOS tables.
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t backtrack_count = 0;
if (!subtable.ReadU16(&backtrack_count)) {
return OTS_FAILURE();
}
if (backtrack_count >= num_glyphs) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < backtrack_count; ++i) {
uint16_t glyph_id = 0;
if (!subtable.ReadU16(&glyph_id)) {
return OTS_FAILURE();
}
if (glyph_id > num_glyphs) {
return OTS_FAILURE();
}
}
uint16_t input_count = 0;
if (!subtable.ReadU16(&input_count)) {
return OTS_FAILURE();
}
if (input_count == 0 || input_count >= num_glyphs) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < input_count - static_cast<unsigned>(1); ++i) {
uint16_t glyph_id = 0;
if (!subtable.ReadU16(&glyph_id)) {
return OTS_FAILURE();
}
if (glyph_id > num_glyphs) {
return OTS_FAILURE();
}
}
uint16_t lookahead_count = 0;
if (!subtable.ReadU16(&lookahead_count)) {
return OTS_FAILURE();
}
if (lookahead_count >= num_glyphs) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookahead_count; ++i) {
uint16_t glyph_id = 0;
if (!subtable.ReadU16(&glyph_id)) {
return OTS_FAILURE();
}
if (glyph_id > num_glyphs) {
return OTS_FAILURE();
}
}
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t chain_rule_count = 0;
if (!subtable.ReadU16(&chain_rule_count)) {
return OTS_FAILURE();
}
const unsigned chain_rule_end =
2 * static_cast<unsigned>(chain_rule_count) + 2;
if (chain_rule_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < chain_rule_count; ++i) {
uint16_t offset_chain_rule = 0;
if (!subtable.ReadU16(&offset_chain_rule)) {
return OTS_FAILURE();
}
if (offset_chain_rule < chain_rule_end || offset_chain_rule >= length) {
return OTS_FAILURE();
}
if (!<API key>(data + offset_chain_rule,
length - offset_chain_rule,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t offset_coverage = 0;
uint16_t <API key> = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&offset_coverage) ||
!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
const unsigned chain_rule_set_end =
2 * static_cast<unsigned>(<API key>) + 6;
if (chain_rule_set_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
if (offset_coverage < chain_rule_set_end || offset_coverage >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offset_coverage,
length - offset_coverage, num_glyphs)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < <API key>; ++i) {
uint16_t <API key> = 0;
if (!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
if (<API key> < chain_rule_set_end ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!<API key>(data + <API key>,
length - <API key>,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
// In this subtable, we don't check the value of classes for now since
// these could take arbitrary values.
uint16_t backtrack_count = 0;
if (!subtable.ReadU16(&backtrack_count)) {
return OTS_FAILURE();
}
if (backtrack_count >= num_glyphs) {
return OTS_FAILURE();
}
if (!subtable.Skip(2 * backtrack_count)) {
return OTS_FAILURE();
}
uint16_t input_count = 0;
if (!subtable.ReadU16(&input_count)) {
return OTS_FAILURE();
}
if (input_count == 0 || input_count >= num_glyphs) {
return OTS_FAILURE();
}
if (!subtable.Skip(2 * (input_count - 1))) {
return OTS_FAILURE();
}
uint16_t lookahead_count = 0;
if (!subtable.ReadU16(&lookahead_count)) {
return OTS_FAILURE();
}
if (lookahead_count >= num_glyphs) {
return OTS_FAILURE();
}
if (!subtable.Skip(2 * lookahead_count)) {
return OTS_FAILURE();
}
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t <API key> = 0;
if (!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
const unsigned <API key> =
2 * static_cast<unsigned>(<API key>) + 2;
if (<API key> > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < <API key>; ++i) {
uint16_t <API key> = 0;
if (!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
if (<API key> < <API key> ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!<API key>(data + <API key>,
length - <API key>,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t offset_coverage = 0;
uint16_t <API key> = 0;
uint16_t <API key> = 0;
uint16_t <API key> = 0;
uint16_t <API key> = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&offset_coverage) ||
!subtable.ReadU16(&<API key>) ||
!subtable.ReadU16(&<API key>) ||
!subtable.ReadU16(&<API key>) ||
!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
const unsigned chain_class_set_end =
2 * static_cast<unsigned>(<API key>) + 12;
if (chain_class_set_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
if (offset_coverage < chain_class_set_end || offset_coverage >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offset_coverage,
length - offset_coverage, num_glyphs)) {
return OTS_FAILURE();
}
// Classes for backtrack/lookahead sequences might not be defined.
if (<API key>) {
if (<API key> < chain_class_set_end ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!ots::ParseClassDefTable(data + <API key>,
length - <API key>,
num_glyphs, kMaxClassDefValue)) {
return OTS_FAILURE();
}
}
if (<API key> < chain_class_set_end ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!ots::ParseClassDefTable(data + <API key>,
length - <API key>,
num_glyphs, kMaxClassDefValue)) {
return OTS_FAILURE();
}
if (<API key>) {
if (<API key> < chain_class_set_end ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!ots::ParseClassDefTable(data + <API key>,
length - <API key>,
num_glyphs, kMaxClassDefValue)) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < <API key>; ++i) {
uint16_t <API key> = 0;
if (!subtable.ReadU16(&<API key>)) {
return OTS_FAILURE();
}
// |<API key>| could be NULL.
if (<API key>) {
if (<API key> < chain_class_set_end ||
<API key> >= length) {
return OTS_FAILURE();
}
if (!<API key>(data + <API key>,
length - <API key>,
num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
ots::Buffer subtable(data, length);
uint16_t backtrack_count = 0;
// Skip format field.
if (!subtable.Skip(2) ||
!subtable.ReadU16(&backtrack_count)) {
return OTS_FAILURE();
}
if (backtrack_count >= num_glyphs) {
return OTS_FAILURE();
}
std::vector<uint16_t> offsets_backtrack;
offsets_backtrack.reserve(backtrack_count);
for (unsigned i = 0; i < backtrack_count; ++i) {
uint16_t offset = 0;
if (!subtable.ReadU16(&offset)) {
return OTS_FAILURE();
}
offsets_backtrack.push_back(offset);
}
if (offsets_backtrack.size() != backtrack_count) {
return OTS_FAILURE();
}
uint16_t input_count = 0;
if (!subtable.ReadU16(&input_count)) {
return OTS_FAILURE();
}
if (input_count >= num_glyphs) {
return OTS_FAILURE();
}
std::vector<uint16_t> offsets_input;
offsets_input.reserve(input_count);
for (unsigned i = 0; i < input_count; ++i) {
uint16_t offset = 0;
if (!subtable.ReadU16(&offset)) {
return OTS_FAILURE();
}
offsets_input.push_back(offset);
}
if (offsets_input.size() != input_count) {
return OTS_FAILURE();
}
uint16_t lookahead_count = 0;
if (!subtable.ReadU16(&lookahead_count)) {
return OTS_FAILURE();
}
if (lookahead_count >= num_glyphs) {
return OTS_FAILURE();
}
std::vector<uint16_t> offsets_lookahead;
offsets_lookahead.reserve(lookahead_count);
for (unsigned i = 0; i < lookahead_count; ++i) {
uint16_t offset = 0;
if (!subtable.ReadU16(&offset)) {
return OTS_FAILURE();
}
offsets_lookahead.push_back(offset);
}
if (offsets_lookahead.size() != lookahead_count) {
return OTS_FAILURE();
}
uint16_t lookup_count = 0;
if (!subtable.ReadU16(&lookup_count)) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < lookup_count; ++i) {
if (!ParseLookupRecord(&subtable, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
}
const unsigned lookup_record_end =
2 * (static_cast<unsigned>(backtrack_count) +
static_cast<unsigned>(input_count) +
static_cast<unsigned>(lookahead_count)) +
4 * static_cast<unsigned>(lookup_count) + 10;
if (lookup_record_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < backtrack_count; ++i) {
if (offsets_backtrack[i] < lookup_record_end ||
offsets_backtrack[i] >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offsets_backtrack[i],
length - offsets_backtrack[i], num_glyphs)) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < input_count; ++i) {
if (offsets_input[i] < lookup_record_end || offsets_input[i] >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offsets_input[i],
length - offsets_input[i], num_glyphs)) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < lookahead_count; ++i) {
if (offsets_lookahead[i] < lookup_record_end ||
offsets_lookahead[i] >= length) {
return OTS_FAILURE();
}
if (!ots::ParseCoverageTable(data + offsets_lookahead[i],
length - offsets_lookahead[i], num_glyphs)) {
return OTS_FAILURE();
}
}
return true;
}
} // namespace
namespace ots {
bool <API key>::Parse(const OpenTypeFile *file, const uint8_t *data,
const size_t length,
const uint16_t lookup_type) const {
for (unsigned i = 0; i < num_types; ++i) {
if (parsers[i].type == lookup_type && parsers[i].parse) {
if (!parsers[i].parse(file, data, length)) {
return OTS_FAILURE();
}
return true;
}
}
return OTS_FAILURE();
}
// Parsing ScriptListTable requires number of features so we need to
// parse FeatureListTable before calling this function.
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_features) {
Buffer subtable(data, length);
uint16_t script_count = 0;
if (!subtable.ReadU16(&script_count)) {
return OTS_FAILURE();
}
const unsigned script_record_end =
6 * static_cast<unsigned>(script_count) + 2;
if (script_record_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
std::vector<ScriptRecord> script_list;
script_list.reserve(script_count);
uint32_t last_tag = 0;
for (unsigned i = 0; i < script_count; ++i) {
ScriptRecord record;
if (!subtable.ReadU32(&record.tag) ||
!subtable.ReadU16(&record.offset)) {
return OTS_FAILURE();
}
// Script tags should be arranged alphabetically by tag
if (last_tag != 0 && last_tag > record.tag) {
// Several fonts don't arrange tags alphabetically.
// It seems that the order of tags might not be a security issue
// so we just warn it.
OTS_WARNING("tags aren't arranged alphabetically.");
}
last_tag = record.tag;
if (record.offset < script_record_end || record.offset >= length) {
return OTS_FAILURE();
}
script_list.push_back(record);
}
if (script_list.size() != script_count) {
return OTS_FAILURE();
}
// Check script records.
for (unsigned i = 0; i < script_count; ++i) {
if (!ParseScriptTable(data + script_list[i].offset,
length - script_list[i].offset,
script_list[i].tag, num_features)) {
return OTS_FAILURE();
}
}
return true;
}
// Parsing FeatureListTable requires number of lookups so we need to parse
// LookupListTable before calling this function.
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_lookups,
uint16_t* num_features) {
Buffer subtable(data, length);
uint16_t feature_count = 0;
if (!subtable.ReadU16(&feature_count)) {
return OTS_FAILURE();
}
std::vector<FeatureRecord> feature_records;
feature_records.resize(feature_count);
const unsigned feature_record_end =
6 * static_cast<unsigned>(feature_count) + 2;
if (feature_record_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
uint32_t last_tag = 0;
for (unsigned i = 0; i < feature_count; ++i) {
if (!subtable.ReadU32(&feature_records[i].tag) ||
!subtable.ReadU16(&feature_records[i].offset)) {
return OTS_FAILURE();
}
// Feature record array should be arranged alphabetically by tag
if (last_tag != 0 && last_tag > feature_records[i].tag) {
// Several fonts don't arrange tags alphabetically.
// It seems that the order of tags might not be a security issue
// so we just warn it.
OTS_WARNING("tags aren't arranged alphabetically.");
}
last_tag = feature_records[i].tag;
if (feature_records[i].offset < feature_record_end ||
feature_records[i].offset >= length) {
return OTS_FAILURE();
}
}
for (unsigned i = 0; i < feature_count; ++i) {
if (!ParseFeatureTable(data + feature_records[i].offset,
length - feature_records[i].offset, num_lookups)) {
return OTS_FAILURE();
}
}
*num_features = feature_count;
return true;
}
// For parsing GPOS/GSUB tables, this function should be called at first to
// obtain the number of lookups because parsing FeatureTableList requires
// the number.
bool <API key>(OpenTypeFile *file, const uint8_t *data,
const size_t length,
const <API key>* parser,
uint16_t *num_lookups) {
Buffer subtable(data, length);
if (!subtable.ReadU16(num_lookups)) {
return OTS_FAILURE();
}
std::vector<uint16_t> lookups;
lookups.reserve(*num_lookups);
const unsigned lookup_end =
2 * static_cast<unsigned>(*num_lookups) + 2;
if (lookup_end > std::numeric_limits<uint16_t>::max()) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < *num_lookups; ++i) {
uint16_t offset = 0;
if (!subtable.ReadU16(&offset)) {
return OTS_FAILURE();
}
if (offset < lookup_end || offset >= length) {
return OTS_FAILURE();
}
lookups.push_back(offset);
}
if (lookups.size() != *num_lookups) {
return OTS_FAILURE();
}
for (unsigned i = 0; i < *num_lookups; ++i) {
if (!ParseLookupTable(file, data + lookups[i], length - lookups[i],
parser)) {
return OTS_FAILURE();
}
}
return true;
}
bool ParseClassDefTable(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t num_classes) {
Buffer subtable(data, length);
uint16_t format = 0;
if (!subtable.ReadU16(&format)) {
return OTS_FAILURE();
}
if (format == 1) {
return <API key>(data, length, num_glyphs, num_classes);
} else if (format == 2) {
return <API key>(data, length, num_glyphs, num_classes);
}
return OTS_FAILURE();
}
bool ParseCoverageTable(const uint8_t *data, size_t length,
const uint16_t num_glyphs,
const uint16_t expected_num_glyphs) {
Buffer subtable(data, length);
uint16_t format = 0;
if (!subtable.ReadU16(&format)) {
return OTS_FAILURE();
}
if (format == 1) {
return <API key>(data, length, num_glyphs, expected_num_glyphs);
} else if (format == 2) {
return <API key>(data, length, num_glyphs, expected_num_glyphs);
}
return OTS_FAILURE();
}
bool ParseDeviceTable(const uint8_t *data, size_t length) {
Buffer subtable(data, length);
uint16_t start_size = 0;
uint16_t end_size = 0;
uint16_t delta_format = 0;
if (!subtable.ReadU16(&start_size) ||
!subtable.ReadU16(&end_size) ||
!subtable.ReadU16(&delta_format)) {
return OTS_FAILURE();
}
if (start_size > end_size) {
OTS_WARNING("bad size range: %u > %u", start_size, end_size);
return OTS_FAILURE();
}
if (delta_format == 0 || delta_format > kMaxDeltaFormatType) {
OTS_WARNING("bad delta format: %u", delta_format);
return OTS_FAILURE();
}
// The number of delta values per uint16. The device table should contain
// at least |num_units| * 2 bytes compressed data.
const unsigned num_units = (end_size - start_size) /
(1 << (4 - delta_format)) + 1;
// Just skip |num_units| * 2 bytes since the compressed data could take
// arbitrary values.
if (!subtable.Skip(num_units * 2)) {
return OTS_FAILURE();
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
Buffer subtable(data, length);
uint16_t format = 0;
if (!subtable.ReadU16(&format)) {
return OTS_FAILURE();
}
if (format == 1) {
if (!ParseContextFormat1(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else if (format == 2) {
if (!ParseContextFormat2(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else if (format == 3) {
if (!ParseContextFormat3(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else {
return OTS_FAILURE();
}
return true;
}
bool <API key>(const uint8_t *data, const size_t length,
const uint16_t num_glyphs,
const uint16_t num_lookups) {
Buffer subtable(data, length);
uint16_t format = 0;
if (!subtable.ReadU16(&format)) {
return OTS_FAILURE();
}
if (format == 1) {
if (!<API key>(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else if (format == 2) {
if (!<API key>(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else if (format == 3) {
if (!<API key>(data, length, num_glyphs, num_lookups)) {
return OTS_FAILURE();
}
} else {
return OTS_FAILURE();
}
return true;
}
bool <API key>(const OpenTypeFile *file,
const uint8_t *data, const size_t length,
const <API key>* parser) {
Buffer subtable(data, length);
uint16_t format = 0;
uint16_t lookup_type = 0;
uint32_t offset_extension = 0;
if (!subtable.ReadU16(&format) ||
!subtable.ReadU16(&lookup_type) ||
!subtable.ReadU32(&offset_extension)) {
return OTS_FAILURE();
}
if (format != 1) {
return OTS_FAILURE();
}
// |lookup_type| should be other than |parser->extension_type|.
if (lookup_type < 1 || lookup_type > parser->num_types ||
lookup_type == parser->extension_type) {
return OTS_FAILURE();
}
const unsigned format_end = static_cast<unsigned>(8);
if (offset_extension < format_end ||
offset_extension >= length) {
return OTS_FAILURE();
}
// Parse the extension subtable of |lookup_type|.
if (!parser->Parse(file, data + offset_extension, length - offset_extension,
lookup_type)) {
return OTS_FAILURE();
}
return true;
}
} // namespace ots |
<?php
if (!defined('PHPUnit_MAIN_METHOD')) {
define('PHPUnit_MAIN_METHOD', 'Zend_Oauth_AllTests::main');
}
require_once 'OauthTest.php';
require_once 'Oauth/ConsumerTest.php';
require_once 'Oauth/Signature/AbstractTest.php';
require_once 'Oauth/Signature/PlaintextTest.php';
require_once 'Oauth/Signature/HmacTest.php';
require_once 'Oauth/Signature/RsaTest.php';
require_once 'Oauth/Http/RequestTokenTest.php';
require_once 'Oauth/Http/<API key>.php';
require_once 'Oauth/Http/AccessTokenTest.php';
require_once 'Oauth/Http/UtilityTest.php';
require_once 'Oauth/Token/RequestTest.php';
require_once 'Oauth/Token/<API key>.php';
require_once 'Oauth/Token/AccessTest.php';
class Zend_Oauth_AllTests
{
public static function main()
{
<API key>::run(self::suite());
}
public static function suite()
{
$suite = new <API key>('Zend Framework - Zend_Oauth');
$suite->addTestSuite('Zend_OauthTest');
$suite->addTestSuite('<API key>');
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
$suite->addTestSuite('Zend_O<API key>);
return $suite;
}
}
if (PHPUnit_MAIN_METHOD == 'Zend_Oauth_AllTests::main') {
Zend_Oauth_AllTests::main();
} |
#ifndef <API key>
#define <API key>
#include "AliAnalysisTaskSE.h"
#include "<API key>.h"
#include "TGrid.h"
class TString;
class TList;
class TProfile2D;
class AliFlowEventSimple;
class AliFlowEvent;
class AliFlowAnalysisCRC;
class AliAnalysisTaskCRC : public AliAnalysisTaskSE{
public:
AliAnalysisTaskCRC();
AliAnalysisTaskCRC(const char *name, Bool_t useParticleWeights=kFALSE);
virtual ~AliAnalysisTaskCRC(){};
virtual void <API key>();
virtual void UserExec(Option_t *option);
virtual void Terminate(Option_t *);
virtual void NotifyRun();
// Common:
void SetBookOnlyBasicCCH(Bool_t const bobcch) {this->fBookOnlyBasicCCH = bobcch;};
Bool_t GetBookOnlyBasicCCH() const {return this->fBookOnlyBasicCCH;};
void <API key>(Bool_t const fmch) {this-><API key> = fmch;};
Bool_t <API key>() const {return this-><API key>;};
void SetHarmonic(Int_t const harmonic) {this->fHarmonic = harmonic;};
Int_t GetHarmonic() const {return this->fHarmonic;};
void <API key>(Bool_t const <API key>) {this-><API key> = <API key>;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const <API key>) {this-><API key> = <API key>;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const peafNIT) {this-><API key> = peafNIT;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const calculateDiffFlow) {this->fCalculateDiffFlow = calculateDiffFlow;};
Bool_t <API key>() const {return this->fCalculateDiffFlow;};
void <API key>(Bool_t const calculate2DDiffFlow) {this-><API key> = calculate2DDiffFlow;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const cdfve) {this-><API key> = cdfve;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const storeDistributions) {this->fStoreDistributions = storeDistributions;};
Bool_t <API key>() const {return this->fStoreDistributions;};
void <API key>(Bool_t const ccvm) {this-><API key> = ccvm;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const cacvm) {this-><API key> = cacvm;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const cmh) {this-><API key> = cmh;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const cmhvm) {this-><API key> = cmhvm;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const sch) {this-><API key> = sch;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const mmrf) {this-><API key> = mmrf;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const fac) {this-><API key> = fac;};
Bool_t <API key>() const {return this-><API key>;};
void SetStoreVarious(Bool_t const spdfoe) {this->fStoreVarious = spdfoe;};
Bool_t GetStoreVarious() const {return this->fStoreVarious;};
void SetExactNoRPs(Int_t const enr) {this->fExactNoRPs = enr;};
Int_t GetExactNoRPs() const {return this->fExactNoRPs;};
void SetUse2DHistograms(Bool_t const u2dh){this->fUse2DHistograms = u2dh;if(u2dh){this-><API key> = kTRUE;}};
Bool_t GetUse2DHistograms() const {return this->fUse2DHistograms;};
void <API key>(Bool_t const fpvmuw){this-><API key> = fpvmuw;};
Bool_t <API key>() const {return this-><API key>;};
void SetUseQvectorTerms(Bool_t const uqvt){this->fUseQvectorTerms = uqvt;if(uqvt){this-><API key> = kTRUE;}};
Bool_t GetUseQvectorTerms() const {return this->fUseQvectorTerms;};
void SetWeightsList(TList* const kList) {this->fWeightsList = (TList*)kList->Clone();};
TList* GetWeightsList() const {return this->fWeightsList;};
// Multiparticle correlations vs multiplicity:
void SetnBinsMult(Int_t const nbm) {this->fnBinsMult = nbm;};
Int_t GetnBinsMult() const {return this->fnBinsMult;};
void SetMinMult(Double_t const minm) {this->fMinMult = minm;};
Double_t GetMinMult() const {return this->fMinMult;};
void SetMaxMult(Double_t const maxm) {this->fMaxMult = maxm;};
Double_t GetMaxMult() const {return this->fMaxMult;};
// Particle weights:
void SetUsePhiWeights(Bool_t const uPhiW) {this->fUsePhiWeights = uPhiW;};
Bool_t GetUsePhiWeights() const {return this->fUsePhiWeights;};
void SetUsePtWeights(Bool_t const uPtW) {this->fUsePtWeights = uPtW;};
Bool_t GetUsePtWeights() const {return this->fUsePtWeights;};
void SetUseEtaWeights(Bool_t const uEtaW) {this->fUseEtaWeights = uEtaW;};
Bool_t GetUseEtaWeights() const {return this->fUseEtaWeights;};
void SetUseTrackWeights(Bool_t const uTrackW) {this->fUseTrackWeights = uTrackW;};
Bool_t GetUseTrackWeights() const {return this->fUseTrackWeights;};
void SetUsePhiEtaWeights(Bool_t const uPhiEtaW) {this->fUsePhiEtaWeights = uPhiEtaW;};
Bool_t GetUsePhiEtaWeights() const {return this->fUsePhiEtaWeights;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
void SetUsePhiEtaCuts(Bool_t const uPhiEtaW) {this->fUsePhiEtaCuts = uPhiEtaW;};
Bool_t GetUsePhiEtaCuts() const {return this->fUsePhiEtaCuts;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
// Event weights:
void <API key>(const char *multiplicityWeight) {*this->fMultiplicityWeight = multiplicityWeight;};
void SetMultiplicityIs(<API key>::ERefMultSource mi) {this->fMultiplicityIs = mi;};
// # of bins for correlation axis in fDistributions[4], <API key>[4] and <API key>[1]
void <API key>(Int_t const nb) {this-><API key> = nb;};
Int_t <API key>() const {return this-><API key>;};
// Boundaries for distributions of correlations:
void <API key>(Int_t const ci, Double_t const minValue) {this-><API key>[ci] = minValue;};
Double_t <API key>(Int_t ci) const {return this-><API key>[ci];};
void <API key>(Int_t const ci, Double_t const maxValue) {this-><API key>[ci] = maxValue;};
Double_t <API key>(Int_t ci) const {return this-><API key>[ci];};
// min and max values of correlation products:
void <API key>(Int_t const cpi, Double_t const minValue) {this-><API key>[cpi] = minValue;};
Double_t <API key>(Int_t cpi) const {return this-><API key>[cpi];};
void <API key>(Int_t const cpi, Double_t const maxValue) {this-><API key>[cpi] = maxValue;};
Double_t <API key>(Int_t cpi) const {return this-><API key>[cpi];};
// min and max values of QvectorTerms:
void <API key>(Int_t const qvti, Double_t const minValue) {this-><API key>[qvti] = minValue;};
Double_t <API key>(Int_t qvti) const {return this-><API key>[qvti];};
void <API key>(Int_t const qvti, Double_t const maxValue) {this-><API key>[qvti] = maxValue;};
Double_t <API key>(Int_t qvti) const {return this-><API key>[qvti];};
// bootstrap:
void SetUseBootstrap(Bool_t const ub) {this->fUseBootstrap = ub;};
Bool_t GetUseBootstrap() const {return this->fUseBootstrap;};
void SetUseBootstrapVsM(Bool_t const ubVsM) {this->fUseBootstrapVsM = ubVsM;};
Bool_t GetUseBootstrapVsM() const {return this->fUseBootstrapVsM;};
void SetnSubsamples(Int_t const ns) {this->fnSubsamples = ns;};
Int_t GetnSubsamples() const {return this->fnSubsamples;};
// Charge-Rapidity Correlations:
void SetCalculateCRC(Bool_t const cCRC) {this->fCalculateCRC = cCRC;};
Bool_t GetCalculateCRC() const {return this->fCalculateCRC;};
void SetCalculateCRCPt(Bool_t const cCRC) {this->fCalculateCRCPt = cCRC;};
Bool_t GetCalculateCRCPt() const {return this->fCalculateCRCPt;};
void SetCalculateCME(Bool_t const cCRC) {this->fCalculateCME = cCRC;};
Bool_t GetCalculateCME() const {return this->fCalculateCME;};
void SetCalculateCRCInt(Bool_t const cCRC) {this->fCalculateCRCInt = cCRC;};
Bool_t GetCalculateCRCInt() const {return this->fCalculateCRCInt;};
void SetCalculateCRC2(Bool_t const cCRC) {this->fCalculateCRC2 = cCRC;};
Bool_t GetCalculateCRC2() const {return this->fCalculateCRC2;};
void SetCalculateCRCVZ(Bool_t const cCRC) {this->fCalculateCRCVZ = cCRC;};
Bool_t GetCalculateCRCVZ() const {return this->fCalculateCRCVZ;};
void SetCalculateCRCZDC(Bool_t const cCRC) {this->fCalculateCRCZDC = cCRC;};
Bool_t GetCalculateCRCZDC() const {return this->fCalculateCRCZDC;};
void SetCalculateEbEFlow(Bool_t const cCRC) {this->fCalculateEbEFlow = cCRC;};
Bool_t GetCalculateEbEFlow() const {return this->fCalculateEbEFlow;};
void <API key>(Bool_t const cCRC) {this->fStoreZDCQVecVtxPos = cCRC;};
Bool_t <API key>() const {return this->fStoreZDCQVecVtxPos;};
void SetCRC2nEtaBins(Int_t NB) {this->fCRC2nEtaBins = NB;};
Int_t GetCRC2nEtaBins() {return this->fCRC2nEtaBins;};
void SetCalculateFlowQC(Bool_t const cCRC) {this->fCalculateFlowQC = cCRC;};
Bool_t GetCalculateFlowQC() const {return this->fCalculateFlowQC;};
void SetCalculateFlowZDC(Bool_t const cCRC) {this->fCalculateFlowZDC = cCRC;};
Bool_t GetCalculateFlowZDC() const {return this->fCalculateFlowZDC;};
void SetCalculateFlowVZ(Bool_t const cCRC) {this->fCalculateFlowVZ = cCRC;};
Bool_t GetCalculateFlowVZ() const {return this->fCalculateFlowVZ;};
void SetUseVZERO(Bool_t const cCRC) {this->fUseVZERO = cCRC;};
Bool_t GetUseVZERO() const {return this->fUseVZERO;};
void SetUseZDC(Bool_t const cCRC) {this->fUseZDC = cCRC;};
Bool_t GetUseZDC() const {return this->fUseZDC;};
void <API key>(Bool_t const uPhiEtaW) {this-><API key> = uPhiEtaW;};
Bool_t <API key>() const {return this-><API key>;};
void SetRecenterZDC(Bool_t const cCRC) {this->fRecenterZDC = cCRC;};
Bool_t GetRecenterZDC() const {return this->fRecenterZDC;};
void SetDivSigma(Bool_t const cCRC) {this->fDivSigma = cCRC;};
Bool_t GetDivSigma() const {return this->fDivSigma;};
void SetInvertZDC(Bool_t const cCRC) {this->fInvertZDC = cCRC;};
Bool_t GetInvertZDC() const {return this->fInvertZDC;};
void SetTestSin(Bool_t const cCRC) {this->fCRCTestSin = cCRC;};
Bool_t GetTestSin() const {return this->fCRCTestSin;};
void <API key>(Bool_t const cCRC) {this->fVtxRbR = cCRC;};
Bool_t <API key>() const {return this->fVtxRbR;};
void SetNUAforCRC(Bool_t const cCRC) {this->fUseNUAforCRC = cCRC;};
Bool_t GetNUAforCRC() const {return this->fUseNUAforCRC;};
void SetUseCRCRecenter(Bool_t const cCRC) {this->fUseCRCRecenter = cCRC;};
Bool_t GetUseCRCRecenter() const {return this->fUseCRCRecenter;};
void SetCRCEtaRange(Double_t const etamin, Double_t const etamax) {this->fCRCEtaMin = etamin; this->fCRCEtaMax = etamax;};
void SetQVecList(TList* const kList) {this->fQVecList = (TList*)kList->Clone();};
TList* GetQVecList() const {return this->fQVecList;};
void SetZDCESEList(TList* const kList) {this->fZDCESEList = (TList*)kList->Clone();};
TList* GetZDCESEList() const {return this->fZDCESEList;};
void SetCRCZDCCalibList(TList* const wlist) {this->fCRCZDCCalibList = (TList*)wlist->Clone();}
TList* GetCRCZDCCalibList() const {return this->fCRCZDCCalibList;}
void SetCRCZDC2DCutList(TList* const wlist) {this->fCRCZDC2DCutList = (TList*)wlist->Clone();}
void <API key>(TList* const wlist) {this->fCRCVZEROCalibList = (TList*)wlist->Clone();}
TList* <API key>() const {return this->fCRCVZEROCalibList;}
void SetCRCZDCResList(TList* const wlist) {this->fCRCZDCResList = (TList*)wlist->Clone();}
TList* GetCRCZDCResList() const {return this->fCRCZDCResList;}
void SetnCenBin(Int_t const n) {this->fnCenBin = n;};
Int_t GetnCenBin() const {return this->fnCenBin;};
void SetFlowQCCenBin(Int_t const TL) {this->fFlowQCCenBin = TL;};
Int_t GetFlowQCCenBin() const {return this->fFlowQCCenBin;};
void SetFlowQCDeltaEta(Double_t const TL) {this->fFlowQCDeltaEta = TL;};
Double_t GetFlowQCDeltaEta() const {return this->fFlowQCDeltaEta;};
void SetCenBinWidth(Double_t const n) {this->fCenBinWidth = n;};
Double_t GetCenBinWidth() const {return this->fCenBinWidth;};
void SetDataSet(TString const n) {this->fDataSet = n;};
TString GetDataSet() const {return this->fDataSet;};
void SetInteractionRate(TString const n) {this->fInteractionRate = n;};
TString GetInteractionRate() const {return this->fInteractionRate;}
void SetSelectCharge(TString const n) {this->fSelectCharge = n;};
TString GetSelectCharge() const {return this->fSelectCharge;}
void SetPOIExtraWeights(TString const n) {this->fPOIExtraWeights = n;};
TString GetPOIExtraWeights() const {return this->fPOIExtraWeights;}
void SetCorrWeight(TString const n) {this->fCorrWeight = n;};
TString GetCorrWeight() const {return this->fCorrWeight;};
void SetCenWeightsHist(TH1D* const n) {this->fCenWeightsHist = n;};
TH1D* GetCenWeightsHist() const {return this->fCenWeightsHist;};
void SetRefMultRbRPro(TProfile2D* const n) {this->fRefMultRbRPro = n;};
void SetAvEZDCRbRPro(TProfile2D* const A, TProfile2D* const B) {this->fAvEZDCCRbRPro = A; this->fAvEZDCARbRPro = B;};
void SetPhiExclZoneHist(TH2D* const n) {this->fPhiExclZoneHist = n;};
TH2D* GetPhiExclZoneHist() const {return this->fPhiExclZoneHist;};
void SetPtWeightsHist(TH1D* const n, Int_t c) {this->fPtWeightsHist[c] = n;};
TH1D* GetPtWeightsHist(Int_t c) const {return this->fPtWeightsHist[c];};
void SetEtaWeightsHist(TH1D* const n, Int_t h, Int_t b, Int_t c) {this->fEtaWeightsHist[h][b][c] = n;};
TH1D* GetEtaWeightsHist(Int_t h, Int_t b, Int_t c) const {return this->fEtaWeightsHist[h][b][c];};
void <API key>(TH2F* const n, Int_t h) {this-><API key>[h] = n;};
TH2F* <API key>(Int_t h) const {return this-><API key>[h];};
void <API key>(TH2F* const n, Int_t h) {this-><API key>[h] = n;};
TH2F* <API key>(Int_t h) const {return this-><API key>[h];};
void SetNvsCenCut(TH1D* const n, Int_t c, Int_t h) {this->fNvsCenCut[c][h] = n;};
TH1D* GetNvsCenCut(Int_t c, Int_t h) const {return this->fNvsCenCut[c][h];};
void SetQAZDCCuts(Bool_t const cCRC) {this->fQAZDCCuts = cCRC;};
Bool_t GetQAZDCCuts() const {return this->fQAZDCCuts;};
void SetMinMulZN(Int_t weights) {this->fMinMulZN = weights;};
Int_t GetMinMulZN() const {return this->fMinMulZN;};
void SetMaxDevZN(Float_t weights) {this->fMaxDevZN = weights;};
Float_t GetMaxDevZN() const {return this->fMaxDevZN;};
void SetZDCGainAlpha( Float_t a ) { fZDCGainAlpha = a; }
void SetUseTracklets(Bool_t const cCRC) {this->fUseTracklets = cCRC;};
void <API key>(Bool_t b) {this-><API key> = b;};
//@Shi set store QA for diff event planes
void <API key>(Bool_t const cCRC) {this-><API key> = cCRC;};
Bool_t <API key>() const {return this-><API key>;};
//@Shi set histogram for recentering
void <API key>(TList* const kList) {this-><API key> = (TList*)kList->Clone();};
TList* <API key>() const {return this-><API key>;};
private:
AliAnalysisTaskCRC(const AliAnalysisTaskCRC& aatqc);
AliAnalysisTaskCRC& operator=(const AliAnalysisTaskCRC& aatqc);
AliFlowEvent *fEvent; // the input event
AliFlowAnalysisCRC *fQC; // CRC object
TList *fListHistos; // collection of output
// Common:
Bool_t fBookOnlyBasicCCH; // book only basis common control histrograms (by default book them all)
Bool_t <API key>; // fill separately control histos for events with >= 2, 4, 6 and 8 particles
Int_t fHarmonic; // harmonic
Bool_t <API key>; // apply correction for non-uniform acceptance
Bool_t <API key>; // apply correction for non-uniform acceptance versus M
Bool_t <API key>; // propagate error by taking into account also non-isotrpic terms
Bool_t fCalculateDiffFlow; // calculate differential flow in pt or eta
Bool_t <API key>; // calculate differential flow in (pt,eta) (Remark: this is very expensive in terms of CPU time)
Bool_t <API key>; // if you set kFALSE only differential flow vs pt is calculated
Bool_t fStoreDistributions; // store or not distributions of correlations
Bool_t <API key>; // calculate cumulants versus multiplicity
Bool_t <API key>; // calculate all correlations versus multiplicity
Bool_t <API key>; // calculate all mixed harmonics correlations
Bool_t <API key>; // calculate all mixed harmonics correlations versus multiplicity
Bool_t <API key>; // store or not control histograms
Bool_t <API key>; // store as reference flow in <API key> the minimum bias result (kFALSE by default)
Bool_t <API key>; // when propagating error forget about the covariances
Bool_t fStoreVarious; // store phi distribution for one event to illustrate flow
Int_t fExactNoRPs; // when shuffled, select only this number of RPs for the analysis
Bool_t fUse2DHistograms; // use TH2D instead of TProfile to improve numerical stability in reference flow calculation
Bool_t <API key>; // if the width of multiplicity bin is 1, weights are not needed
Bool_t fUseQvectorTerms; // use TH2D with separate Q-vector terms instead of TProfile to improve numerical stability in reference flow calculation
// Multiparticle correlations vs multiplicity:
Int_t fnBinsMult; // number of multiplicity bins for flow analysis versus multiplicity
Double_t fMinMult; // minimal multiplicity for flow analysis versus multiplicity
Double_t fMaxMult; // maximal multiplicity for flow analysis versus multiplicity
// Particle weights:
Bool_t fUseParticleWeights; // use any particle weights
Bool_t fUsePhiWeights; // use phi weights
Bool_t fUsePtWeights; // use pt weights
Bool_t fUseEtaWeights; // use eta weights
Bool_t fUseTrackWeights; // use track weights (e.g. VZERO sector weights)
Bool_t fUsePhiEtaWeights; // use phi,eta weights
Bool_t <API key>; // use phi,eta weights ch dep
Bool_t <API key>; // use phi,eta weights vtx dep
Bool_t fUsePhiEtaCuts; // use phi,eta cuts (for NUA)
Bool_t <API key>; // use ZDC-ESE mult. weights
Bool_t <API key>; // use ZDC-ESE mult. weights
Bool_t <API key>; // cut on reference multiplicity
TList *fWeightsList; // list with weights
// Event weights:
TString *fMultiplicityWeight; // event-by-event weights for multiparticle correlations ("combinations","unit" or "multiplicity")
<API key>::ERefMultSource fMultiplicityIs; // by default "#RPs", other supported options are "RefMultFromESD" = ref. mult. from ESD, and "#POIs"
Int_t <API key>; // # of bins for correlation axis in fDistributions[4], <API key>[4] and <API key>[1]
// Boundaries for distributions of correlations:
Double_t <API key>[4]; // min values of <2>, <4>, <6> and <8>
Double_t <API key>[4]; // max values of <2>, <4>, <6> and <8>
Double_t <API key>[1]; // min values of <2><4>, <2><6>, <2><8>, <4><6> etc. TBI add the other ones when needed first time
Double_t <API key>[1]; // max values of <2><4>, <2><6>, <2><8>, <4><6> etc. TBI add the other ones when needed first time
Double_t <API key>[4]; // min value of Q-vector terms
Double_t <API key>[4]; // max value of Q-vector terms
// Bootstrap:
Bool_t fUseBootstrap; // use bootstrap to estimate statistical spread
Bool_t fUseBootstrapVsM; // use bootstrap to estimate statistical spread for results vs M
Int_t fnSubsamples; // number of subsamples (SS), by default 10
// Charge-Eta Asymmetry
Bool_t fCalculateCRC; // calculate CRC quantities
Bool_t fCalculateCRCPt;
Bool_t fCalculateCME;
Bool_t fCalculateCRCInt;
Bool_t fCalculateCRC2;
Bool_t fCalculateCRCVZ;
Bool_t fCalculateCRCZDC;
Bool_t fCalculateEbEFlow;
Bool_t fStoreZDCQVecVtxPos;
Int_t fCRC2nEtaBins; // CRC2 n eta bins
Bool_t fCalculateFlowQC;
Bool_t fCalculateFlowZDC;
Bool_t fCalculateFlowVZ;
Bool_t fUseVZERO;
Bool_t fUseZDC;
Bool_t <API key>;
Bool_t fRecenterZDC;
Bool_t fDivSigma;
Bool_t fInvertZDC;
Bool_t fCRCTestSin;
Bool_t fVtxRbR;
Bool_t fUseNUAforCRC;
Bool_t fUseCRCRecenter;
Bool_t <API key>; //@Shi
Double_t fCRCEtaMin;
Double_t fCRCEtaMax;
Int_t fnCenBin;
Int_t fFlowQCCenBin;
Double_t fFlowQCDeltaEta;
Double_t fCenBinWidth;
TString fDataSet;
TString fInteractionRate;
TString fSelectCharge;
TString fPOIExtraWeights;
TString fCorrWeight;
TList *fQVecList; // list with weights
TList *fCRCZDCCalibList; // ZDC calibration
TList *fCRCZDC2DCutList; // ZDC calibration
TList *fCRCVZEROCalibList; // ZDC calibration
TList *fCRCZDCResList; // ZDC rescaling
TList *fZDCESEList; // list with weights
TH1D* fCenWeightsHist;
TProfile2D *fRefMultRbRPro;
TProfile2D *fAvEZDCCRbRPro;
TProfile2D *fAvEZDCARbRPro;
TH1D* fPtWeightsHist[10];
TH1D* fEtaWeightsHist[10][21][2];
TH1D* fNvsCenCut[2][2]; //! ZDC mult cuts
TH2F* <API key>[5];
TH2F* <API key>[5];
TH2D* fPhiExclZoneHist;
Bool_t fQAZDCCuts;
Bool_t fUseTracklets;
Bool_t <API key>;
Int_t fMinMulZN;
Float_t fMaxDevZN;
Float_t fZDCGainAlpha;
//@Shi ZDC calib recenter TList
TList *<API key>;
ClassDef(AliAnalysisTaskCRC,15);
};
#endif |
"""
This module provides code to generate and sample probability distributions.
The class RandProbDist provides an interface to randomly generate probability
distributions. Random samples can then be drawn from these distributions.
"""
import random
import const
import obfsproxy.common.log as logging
log = logging.get_obfslogger()
class RandProbDist:
"""
Provides code to generate, sample and dump probability distributions.
"""
def __init__( self, genSingleton, seed=None ):
"""
Initialise a discrete probability distribution.
The parameter `genSingleton' is expected to be a function which yields
singletons for the probability distribution. The optional `seed' can
be used to seed the PRNG so that the probability distribution is
generated deterministically.
"""
self.prng = random if (seed is None) else random.Random(seed)
self.sampleList = []
self.dist = self.genDistribution(genSingleton)
self.dumpDistribution()
def genDistribution( self, genSingleton ):
"""
Generate a discrete probability distribution.
The parameter `genSingleton' is a function which is used to generate
singletons for the probability distribution.
"""
dist = {}
# Amount of distinct bins, i.e., packet lengths or inter arrival times.
bins = self.prng.randint(const.MIN_BINS, const.MAX_BINS)
# Cumulative probability of all bins.
cumulProb = 0
for _ in xrange(bins):
prob = self.prng.uniform(0, (1 - cumulProb))
cumulProb += prob
singleton = genSingleton()
dist[singleton] = prob
self.sampleList.append((cumulProb, singleton,))
dist[genSingleton()] = (1 - cumulProb)
return dist
def dumpDistribution( self ):
"""
Dump the probability distribution using the logging object.
Only probabilities > 0.01 are dumped.
"""
log.debug("Dumping probability distribution.")
for singleton in self.dist.iterkeys():
# We are not interested in tiny probabilities.
if self.dist[singleton] > 0.01:
log.debug("P(%s) = %.3f" %
(str(singleton), self.dist[singleton]))
def randomSample( self ):
"""
Draw and return a random sample from the probability distribution.
"""
assert len(self.sampleList) > 0
rand = random.random()
for cumulProb, singleton in self.sampleList:
if rand <= cumulProb:
return singleton
return self.sampleList[-1][1]
# Alias class name in order to provide a more intuitive API.
new = RandProbDist |
#include "core/paint/PaintPhase.h"
#include "platform/graphics/paint/DisplayItem.h"
#include "wtf/Assertions.h"
namespace blink {
// DisplayItem types must be kept in sync with PaintPhase.
static_assert((unsigned)DisplayItem::PaintPhaseMax == (unsigned)PaintPhaseMax, "DisplayItem Type should stay in sync");
} // namespace blink |
<?php
namespace PHPUnit\TextUI;
use PHPUnit\Framework\Error\Deprecated;
use PHPUnit\Framework\Error\Notice;
use PHPUnit\Framework\Error\Warning;
use PHPUnit\Framework\Exception;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestResult;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Runner\BaseTestRunner;
use PHPUnit\Runner\Filter\<API key>;
use PHPUnit\Runner\Filter\Factory;
use PHPUnit\Runner\Filter\<API key>;
use PHPUnit\Runner\Filter\NameFilterIterator;
use PHPUnit\Runner\<API key>;
use PHPUnit\Runner\TestSuiteLoader;
use PHPUnit\Runner\Version;
use PHPUnit\Util\Configuration;
use PHPUnit\Util\Log\JUnit;
use PHPUnit\Util\Log\TeamCity;
use PHPUnit\Util\Printer;
use PHPUnit\Util\TestDox\HtmlResultPrinter;
use PHPUnit\Util\TestDox\TextResultPrinter;
use PHPUnit\Util\TestDox\XmlResultPrinter;
use ReflectionClass;
use SebastianBergmann;
use SebastianBergmann\CodeCoverage\CodeCoverage;
use SebastianBergmann\CodeCoverage\Exception as <API key>;
use SebastianBergmann\CodeCoverage\Filter as CodeCoverageFilter;
use SebastianBergmann\CodeCoverage\Report\Clover as CloverReport;
use SebastianBergmann\CodeCoverage\Report\Crap4j as Crap4jReport;
use SebastianBergmann\CodeCoverage\Report\Html\Facade as HtmlReport;
use SebastianBergmann\CodeCoverage\Report\PHP as PhpReport;
use SebastianBergmann\CodeCoverage\Report\Text as TextReport;
use SebastianBergmann\CodeCoverage\Report\Xml\Facade as XmlReport;
use SebastianBergmann\Environment\Runtime;
/**
* A TestRunner for the Command Line Interface (CLI)
* PHP SAPI Module.
*/
class TestRunner extends BaseTestRunner
{
const SUCCESS_EXIT = 0;
const FAILURE_EXIT = 1;
const EXCEPTION_EXIT = 2;
/**
* @var CodeCoverageFilter
*/
protected $codeCoverageFilter;
/**
* @var TestSuiteLoader
*/
protected $loader;
/**
* @var ResultPrinter
*/
protected $printer;
/**
* @var bool
*/
protected static $<API key> = false;
/**
* @var Runtime
*/
private $runtime;
/**
* @var bool
*/
private $messagePrinted = false;
/**
* @param TestSuiteLoader $loader
* @param CodeCoverageFilter $filter
*/
public function __construct(TestSuiteLoader $loader = null, CodeCoverageFilter $filter = null)
{
if ($filter === null) {
$filter = new CodeCoverageFilter;
}
$this->codeCoverageFilter = $filter;
$this->loader = $loader;
$this->runtime = new Runtime;
}
/**
* @param Test|ReflectionClass $test
* @param array $arguments
* @param bool $exit
*
* @return TestResult
*
* @throws Exception
*/
public static function run($test, array $arguments = [], $exit = true)
{
if ($test instanceof ReflectionClass) {
$test = new TestSuite($test);
}
if ($test instanceof Test) {
$aTestRunner = new self;
return $aTestRunner->doRun(
$test,
$arguments,
$exit
);
}
throw new Exception('No test case or test suite found.');
}
/**
* @return TestResult
*/
protected function createTestResult()
{
return new TestResult;
}
/**
* @param TestSuite $suite
* @param array $arguments
*/
private function processSuiteFilters(TestSuite $suite, array $arguments)
{
if (!$arguments['filter'] &&
empty($arguments['groups']) &&
empty($arguments['excludeGroups'])) {
return;
}
$filterFactory = new Factory;
if (!empty($arguments['excludeGroups'])) {
$filterFactory->addFilter(
new ReflectionClass(<API key>::class),
$arguments['excludeGroups']
);
}
if (!empty($arguments['groups'])) {
$filterFactory->addFilter(
new ReflectionClass(<API key>::class),
$arguments['groups']
);
}
if ($arguments['filter']) {
$filterFactory->addFilter(
new ReflectionClass(NameFilterIterator::class),
$arguments['filter']
);
}
$suite->injectFilter($filterFactory);
}
/**
* @param Test $suite
* @param array $arguments
* @param bool $exit
*
* @return TestResult
*/
public function doRun(Test $suite, array $arguments = [], $exit = true)
{
if (isset($arguments['configuration'])) {
$GLOBALS['<API key>'] = $arguments['configuration'];
}
$this->handleConfiguration($arguments);
$this->processSuiteFilters($suite, $arguments);
if (isset($arguments['bootstrap'])) {
$GLOBALS['__PHPUNIT_BOOTSTRAP'] = $arguments['bootstrap'];
}
if ($arguments['backupGlobals'] === true) {
$suite->setBackupGlobals(true);
}
if ($arguments['<API key>'] === true) {
$suite-><API key>(true);
}
if ($arguments['<API key>'] === true) {
$suite-><API key>(true);
}
if (\is_int($arguments['repeat']) && $arguments['repeat'] > 0) {
$_suite = new TestSuite;
foreach (\range(1, $arguments['repeat']) as $step) {
$_suite->addTest($suite);
}
$suite = $_suite;
unset($_suite);
}
$result = $this->createTestResult();
if (!$arguments['<API key>']) {
$result-><API key>(false);
}
if (!$arguments['<API key>']) {
Deprecated::$enabled = false;
}
if (!$arguments['<API key>']) {
Notice::$enabled = false;
}
if (!$arguments['<API key>']) {
Warning::$enabled = false;
}
if ($arguments['stopOnError']) {
$result->stopOnError(true);
}
if ($arguments['stopOnFailure']) {
$result->stopOnFailure(true);
}
if ($arguments['stopOnWarning']) {
$result->stopOnWarning(true);
}
if ($arguments['stopOnIncomplete']) {
$result->stopOnIncomplete(true);
}
if ($arguments['stopOnRisky']) {
$result->stopOnRisky(true);
}
if ($arguments['stopOnSkipped']) {
$result->stopOnSkipped(true);
}
if ($arguments['<API key>']) {
$result-><API key>(true);
}
if ($this->printer === null) {
if (isset($arguments['printer']) &&
$arguments['printer'] instanceof Printer) {
$this->printer = $arguments['printer'];
} else {
$printerClass = ResultPrinter::class;
if (isset($arguments['printer']) && \is_string($arguments['printer']) && \class_exists($arguments['printer'], false)) {
$class = new ReflectionClass($arguments['printer']);
if ($class->isSubclassOf(ResultPrinter::class)) {
$printerClass = $arguments['printer'];
}
}
$this->printer = new $printerClass(
(isset($arguments['stderr']) && $arguments['stderr'] === true) ? 'php://stderr' : null,
$arguments['verbose'],
$arguments['colors'],
$arguments['debug'],
$arguments['columns'],
$arguments['reverseList']
);
}
}
$this->printer->write(
Version::getVersionString() . "\n"
);
self::$<API key> = true;
if ($arguments['verbose']) {
$runtime = $this->runtime->getNameWithVersion();
if ($this->runtime->hasXdebug()) {
$runtime .= \sprintf(
' with Xdebug %s',
\phpversion('xdebug')
);
}
$this->writeMessage('Runtime', $runtime);
if (isset($arguments['configuration'])) {
$this->writeMessage(
'Configuration',
$arguments['configuration']->getFilename()
);
}
foreach ($arguments['loadedExtensions'] as $extension) {
$this->writeMessage(
'Extension',
$extension
);
}
foreach ($arguments['notLoadedExtensions'] as $extension) {
$this->writeMessage(
'Extension',
$extension
);
}
}
if ($this->runtime->discardsComments()) {
$this->writeMessage('Warning', 'opcache.save_comments=0 set; annotations will not work');
}
foreach ($arguments['listeners'] as $listener) {
$result->addListener($listener);
}
$result->addListener($this->printer);
$codeCoverageReports = 0;
if (!isset($arguments['noLogging'])) {
if (isset($arguments['testdoxHTMLFile'])) {
$result->addListener(
new HtmlResultPrinter(
$arguments['testdoxHTMLFile'],
$arguments['testdoxGroups'],
$arguments['<API key>']
)
);
}
if (isset($arguments['testdoxTextFile'])) {
$result->addListener(
new TextResultPrinter(
$arguments['testdoxTextFile'],
$arguments['testdoxGroups'],
$arguments['<API key>']
)
);
}
if (isset($arguments['testdoxXMLFile'])) {
$result->addListener(
new XmlResultPrinter(
$arguments['testdoxXMLFile']
)
);
}
if (isset($arguments['teamcityLogfile'])) {
$result->addListener(
new TeamCity($arguments['teamcityLogfile'])
);
}
if (isset($arguments['junitLogfile'])) {
$result->addListener(
new JUnit(
$arguments['junitLogfile'],
$arguments['reportUselessTests']
)
);
}
if (isset($arguments['coverageClover'])) {
$codeCoverageReports++;
}
if (isset($arguments['coverageCrap4J'])) {
$codeCoverageReports++;
}
if (isset($arguments['coverageHtml'])) {
$codeCoverageReports++;
}
if (isset($arguments['coveragePHP'])) {
$codeCoverageReports++;
}
if (isset($arguments['coverageText'])) {
$codeCoverageReports++;
}
if (isset($arguments['coverageXml'])) {
$codeCoverageReports++;
}
}
if (isset($arguments['noCoverage'])) {
$codeCoverageReports = 0;
}
if ($codeCoverageReports > 0 && !$this->runtime-><API key>()) {
$this->writeMessage('Error', 'No code coverage driver is available');
$codeCoverageReports = 0;
}
if ($codeCoverageReports > 0) {
$codeCoverage = new CodeCoverage(
null,
$this->codeCoverageFilter
);
$codeCoverage-><API key>(
[SebastianBergmann\Comparator\Comparator::class]
);
$codeCoverage-><API key>(
$arguments['strictCoverage']
);
$codeCoverage-><API key>(
$arguments['strictCoverage']
);
if (isset($arguments['<API key>'])) {
$codeCoverage-><API key>(
$arguments['<API key>']
);
}
if (isset($arguments['<API key>'])) {
$codeCoverage-><API key>(
$arguments['<API key>']
);
}
if (isset($arguments['<API key>'])) {
$codeCoverage-><API key>(true);
}
$<API key> = false;
$whitelistFromOption = false;
if (isset($arguments['whitelist'])) {
$this->codeCoverageFilter-><API key>($arguments['whitelist']);
$whitelistFromOption = true;
}
if (isset($arguments['configuration'])) {
$filterConfiguration = $arguments['configuration']-><API key>();
if (!empty($filterConfiguration['whitelist'])) {
$<API key> = true;
}
if (!empty($filterConfiguration['whitelist'])) {
$codeCoverage-><API key>(
$filterConfiguration['whitelist']['<API key>']
);
$codeCoverage-><API key>(
$filterConfiguration['whitelist']['<API key>']
);
foreach ($filterConfiguration['whitelist']['include']['directory'] as $dir) {
$this->codeCoverageFilter-><API key>(
$dir['path'],
$dir['suffix'],
$dir['prefix']
);
}
foreach ($filterConfiguration['whitelist']['include']['file'] as $file) {
$this->codeCoverageFilter->addFileToWhitelist($file);
}
foreach ($filterConfiguration['whitelist']['exclude']['directory'] as $dir) {
$this->codeCoverageFilter-><API key>(
$dir['path'],
$dir['suffix'],
$dir['prefix']
);
}
foreach ($filterConfiguration['whitelist']['exclude']['file'] as $file) {
$this->codeCoverageFilter-><API key>($file);
}
}
}
if (isset($codeCoverage) && !$this->codeCoverageFilter->hasWhitelist()) {
if (!$<API key> && !$whitelistFromOption) {
$this->writeMessage('Error', 'No whitelist is configured, no code coverage will be generated.');
} else {
$this->writeMessage('Error', 'Incorrect whitelist config, no code coverage will be generated.');
}
$codeCoverageReports = 0;
unset($codeCoverage);
}
}
$this->printer->write("\n");
if (isset($codeCoverage)) {
$result->setCodeCoverage($codeCoverage);
if ($codeCoverageReports > 1 && isset($arguments['cacheTokens'])) {
$codeCoverage->setCacheTokens($arguments['cacheTokens']);
}
}
$result-><API key>($arguments['reportUselessTests']);
$result-><API key>($arguments['disallowTestOutput']);
$result-><API key>($arguments['<API key>']);
$result-><API key>($arguments['<API key>']);
$result->enforceTimeLimit($arguments['enforceTimeLimit']);
$result-><API key>($arguments['<API key>']);
$result-><API key>($arguments['<API key>']);
$result-><API key>($arguments['<API key>']);
if ($suite instanceof TestSuite) {
$suite-><API key>($arguments['processIsolation']);
}
$suite->run($result);
unset($suite);
$result->flushListeners();
if ($this->printer instanceof ResultPrinter) {
$this->printer->printResult($result);
}
if (isset($codeCoverage)) {
if (isset($arguments['coverageClover'])) {
$this->printer->write(
"\nGenerating code coverage report in Clover XML format ..."
);
try {
$writer = new CloverReport;
$writer->process($codeCoverage, $arguments['coverageClover']);
$this->printer->write(" done\n");
unset($writer);
} catch (<API key> $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageCrap4J'])) {
$this->printer->write(
"\nGenerating Crap4J report XML file ..."
);
try {
$writer = new Crap4jReport($arguments['crap4jThreshold']);
$writer->process($codeCoverage, $arguments['coverageCrap4J']);
$this->printer->write(" done\n");
unset($writer);
} catch (<API key> $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageHtml'])) {
$this->printer->write(
"\nGenerating code coverage report in HTML format ..."
);
try {
$writer = new HtmlReport(
$arguments['reportLowUpperBound'],
$arguments['<API key>'],
\sprintf(
' and <a href="https://phpunit.de/">PHPUnit %s</a>',
Version::id()
)
);
$writer->process($codeCoverage, $arguments['coverageHtml']);
$this->printer->write(" done\n");
unset($writer);
} catch (<API key> $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coveragePHP'])) {
$this->printer->write(
"\nGenerating code coverage report in PHP format ..."
);
try {
$writer = new PhpReport;
$writer->process($codeCoverage, $arguments['coveragePHP']);
$this->printer->write(" done\n");
unset($writer);
} catch (<API key> $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
if (isset($arguments['coverageText'])) {
if ($arguments['coverageText'] == 'php://stdout') {
$outputStream = $this->printer;
$colors = $arguments['colors'] && $arguments['colors'] != ResultPrinter::COLOR_NEVER;
} else {
$outputStream = new Printer($arguments['coverageText']);
$colors = false;
}
$processor = new TextReport(
$arguments['reportLowUpperBound'],
$arguments['<API key>'],
$arguments['<API key>'],
$arguments['<API key>']
);
$outputStream->write(
$processor->process($codeCoverage, $colors)
);
}
if (isset($arguments['coverageXml'])) {
$this->printer->write(
"\nGenerating code coverage report in PHPUnit XML format ..."
);
try {
$writer = new XmlReport(Version::id());
$writer->process($codeCoverage, $arguments['coverageXml']);
$this->printer->write(" done\n");
unset($writer);
} catch (<API key> $e) {
$this->printer->write(
" failed\n" . $e->getMessage() . "\n"
);
}
}
}
if ($exit) {
if ($result->wasSuccessful()) {
if ($arguments['failOnRisky'] && !$result->allHarmless()) {
exit(self::FAILURE_EXIT);
}
if ($arguments['failOnWarning'] && $result->warningCount() > 0) {
exit(self::FAILURE_EXIT);
}
exit(self::SUCCESS_EXIT);
}
if ($result->errorCount() > 0) {
exit(self::EXCEPTION_EXIT);
}
if ($result->failureCount() > 0) {
exit(self::FAILURE_EXIT);
}
}
return $result;
}
/**
* @param ResultPrinter $resultPrinter
*/
public function setPrinter(ResultPrinter $resultPrinter)
{
$this->printer = $resultPrinter;
}
/**
* Override to define how to handle a failed loading of
* a test suite.
*
* @param string $message
*/
protected function runFailed($message)
{
$this->write($message . PHP_EOL);
exit(self::FAILURE_EXIT);
}
/**
* @param string $buffer
*/
protected function write($buffer)
{
if (PHP_SAPI != 'cli' && PHP_SAPI != 'phpdbg') {
$buffer = \htmlspecialchars($buffer);
}
if ($this->printer !== null) {
$this->printer->write($buffer);
} else {
print $buffer;
}
}
/**
* Returns the loader to be used.
*
* @return TestSuiteLoader
*/
public function getLoader()
{
if ($this->loader === null) {
$this->loader = new <API key>;
}
return $this->loader;
}
/**
* @param array $arguments
*/
protected function handleConfiguration(array &$arguments)
{
if (isset($arguments['configuration']) &&
!$arguments['configuration'] instanceof Configuration) {
$arguments['configuration'] = Configuration::getInstance(
$arguments['configuration']
);
}
$arguments['debug'] = $arguments['debug'] ?? false;
$arguments['filter'] = $arguments['filter'] ?? false;
$arguments['listeners'] = $arguments['listeners'] ?? [];
if (isset($arguments['configuration'])) {
$arguments['configuration']-><API key>();
$<API key> = $arguments['configuration']-><API key>();
if (isset($<API key>['backupGlobals']) && !isset($arguments['backupGlobals'])) {
$arguments['backupGlobals'] = $<API key>['backupGlobals'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['bootstrap']) && !isset($arguments['bootstrap'])) {
$arguments['bootstrap'] = $<API key>['bootstrap'];
}
if (isset($<API key>['cacheTokens']) && !isset($arguments['cacheTokens'])) {
$arguments['cacheTokens'] = $<API key>['cacheTokens'];
}
if (isset($<API key>['colors']) && !isset($arguments['colors'])) {
$arguments['colors'] = $<API key>['colors'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['processIsolation']) && !isset($arguments['processIsolation'])) {
$arguments['processIsolation'] = $<API key>['processIsolation'];
}
if (isset($<API key>['stopOnError']) && !isset($arguments['stopOnError'])) {
$arguments['stopOnError'] = $<API key>['stopOnError'];
}
if (isset($<API key>['stopOnFailure']) && !isset($arguments['stopOnFailure'])) {
$arguments['stopOnFailure'] = $<API key>['stopOnFailure'];
}
if (isset($<API key>['stopOnWarning']) && !isset($arguments['stopOnWarning'])) {
$arguments['stopOnWarning'] = $<API key>['stopOnWarning'];
}
if (isset($<API key>['stopOnIncomplete']) && !isset($arguments['stopOnIncomplete'])) {
$arguments['stopOnIncomplete'] = $<API key>['stopOnIncomplete'];
}
if (isset($<API key>['stopOnRisky']) && !isset($arguments['stopOnRisky'])) {
$arguments['stopOnRisky'] = $<API key>['stopOnRisky'];
}
if (isset($<API key>['stopOnSkipped']) && !isset($arguments['stopOnSkipped'])) {
$arguments['stopOnSkipped'] = $<API key>['stopOnSkipped'];
}
if (isset($<API key>['failOnWarning']) && !isset($arguments['failOnWarning'])) {
$arguments['failOnWarning'] = $<API key>['failOnWarning'];
}
if (isset($<API key>['failOnRisky']) && !isset($arguments['failOnRisky'])) {
$arguments['failOnRisky'] = $<API key>['failOnRisky'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['reportUselessTests']) && !isset($arguments['reportUselessTests'])) {
$arguments['reportUselessTests'] = $<API key>['reportUselessTests'];
}
if (isset($<API key>['strictCoverage']) && !isset($arguments['strictCoverage'])) {
$arguments['strictCoverage'] = $<API key>['strictCoverage'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['disallowTestOutput']) && !isset($arguments['disallowTestOutput'])) {
$arguments['disallowTestOutput'] = $<API key>['disallowTestOutput'];
}
if (isset($<API key>['enforceTimeLimit']) && !isset($arguments['enforceTimeLimit'])) {
$arguments['enforceTimeLimit'] = $<API key>['enforceTimeLimit'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['verbose']) && !isset($arguments['verbose'])) {
$arguments['verbose'] = $<API key>['verbose'];
}
if (isset($<API key>['reverseDefectList']) && !isset($arguments['reverseList'])) {
$arguments['reverseList'] = $<API key>['reverseDefectList'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
if (isset($<API key>['<API key>']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
}
$groupCliArgs = [];
if (!empty($arguments['groups'])) {
$groupCliArgs = $arguments['groups'];
}
$groupConfiguration = $arguments['configuration']-><API key>();
if (!empty($groupConfiguration['include']) && !isset($arguments['groups'])) {
$arguments['groups'] = $groupConfiguration['include'];
}
if (!empty($groupConfiguration['exclude']) && !isset($arguments['excludeGroups'])) {
$arguments['excludeGroups'] = \array_diff($groupConfiguration['exclude'], $groupCliArgs);
}
foreach ($arguments['configuration']-><API key>() as $listener) {
if (!\class_exists($listener['class'], false) &&
$listener['file'] !== '') {
require_once $listener['file'];
}
if (!\class_exists($listener['class'])) {
throw new Exception(
\sprintf(
'Class "%s" does not exist',
$listener['class']
)
);
}
$listenerClass = new ReflectionClass($listener['class']);
if (!$listenerClass->implementsInterface(TestListener::class)) {
throw new Exception(
\sprintf(
'Class "%s" does not implement the PHPUnit\Framework\TestListener interface',
$listener['class']
)
);
}
if (\count($listener['arguments']) == 0) {
$listener = new $listener['class'];
} else {
$listener = $listenerClass->newInstanceArgs(
$listener['arguments']
);
}
$arguments['listeners'][] = $listener;
}
$<API key> = $arguments['configuration']-><API key>();
if (isset($<API key>['coverage-clover']) && !isset($arguments['coverageClover'])) {
$arguments['coverageClover'] = $<API key>['coverage-clover'];
}
if (isset($<API key>['coverage-crap4j']) && !isset($arguments['coverageCrap4J'])) {
$arguments['coverageCrap4J'] = $<API key>['coverage-crap4j'];
if (isset($<API key>['crap4jThreshold']) && !isset($arguments['crap4jThreshold'])) {
$arguments['crap4jThreshold'] = $<API key>['crap4jThreshold'];
}
}
if (isset($<API key>['coverage-html']) && !isset($arguments['coverageHtml'])) {
if (isset($<API key>['lowUpperBound']) && !isset($arguments['reportLowUpperBound'])) {
$arguments['reportLowUpperBound'] = $<API key>['lowUpperBound'];
}
if (isset($<API key>['highLowerBound']) && !isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['highLowerBound'];
}
$arguments['coverageHtml'] = $<API key>['coverage-html'];
}
if (isset($<API key>['coverage-php']) && !isset($arguments['coveragePHP'])) {
$arguments['coveragePHP'] = $<API key>['coverage-php'];
}
if (isset($<API key>['coverage-text']) && !isset($arguments['coverageText'])) {
$arguments['coverageText'] = $<API key>['coverage-text'];
if (isset($<API key>['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
} else {
$arguments['<API key>'] = false;
}
if (isset($<API key>['<API key>'])) {
$arguments['<API key>'] = $<API key>['<API key>'];
} else {
$arguments['<API key>'] = false;
}
}
if (isset($<API key>['coverage-xml']) && !isset($arguments['coverageXml'])) {
$arguments['coverageXml'] = $<API key>['coverage-xml'];
}
if (isset($<API key>['plain'])) {
$arguments['listeners'][] = new ResultPrinter(
$<API key>['plain'],
true
);
}
if (isset($<API key>['teamcity']) && !isset($arguments['teamcityLogfile'])) {
$arguments['teamcityLogfile'] = $<API key>['teamcity'];
}
if (isset($<API key>['junit']) && !isset($arguments['junitLogfile'])) {
$arguments['junitLogfile'] = $<API key>['junit'];
}
if (isset($<API key>['testdox-html']) && !isset($arguments['testdoxHTMLFile'])) {
$arguments['testdoxHTMLFile'] = $<API key>['testdox-html'];
}
if (isset($<API key>['testdox-text']) && !isset($arguments['testdoxTextFile'])) {
$arguments['testdoxTextFile'] = $<API key>['testdox-text'];
}
if (isset($<API key>['testdox-xml']) && !isset($arguments['testdoxXMLFile'])) {
$arguments['testdoxXMLFile'] = $<API key>['testdox-xml'];
}
$<API key> = $arguments['configuration']-><API key>();
if (isset($<API key>['include']) &&
!isset($arguments['testdoxGroups'])) {
$arguments['testdoxGroups'] = $<API key>['include'];
}
if (isset($<API key>['exclude']) &&
!isset($arguments['<API key>'])) {
$arguments['<API key>'] = $<API key>['exclude'];
}
}
$arguments['<API key>'] = $arguments['<API key>'] ?? true;
$arguments['backupGlobals'] = $arguments['backupGlobals'] ?? null;
$arguments['<API key>'] = $arguments['<API key>'] ?? null;
$arguments['<API key>'] = $arguments['<API key>'] ?? null;
$arguments['<API key>'] = $arguments['<API key>'] ?? false;
$arguments['cacheTokens'] = $arguments['cacheTokens'] ?? false;
$arguments['colors'] = $arguments['colors'] ?? ResultPrinter::COLOR_DEFAULT;
$arguments['columns'] = $arguments['columns'] ?? 80;
$arguments['<API key>'] = $arguments['<API key>'] ?? true;
$arguments['<API key>'] = $arguments['<API key>'] ?? true;
$arguments['<API key>'] = $arguments['<API key>'] ?? true;
$arguments['<API key>'] = $arguments['<API key>'] ?? true;
$arguments['crap4jThreshold'] = $arguments['crap4jThreshold'] ?? 30;
$arguments['disallowTestOutput'] = $arguments['disallowTestOutput'] ?? false;
$arguments['<API key>'] = $arguments['<API key>'] ?? false;
$arguments['enforceTimeLimit'] = $arguments['enforceTimeLimit'] ?? false;
$arguments['excludeGroups'] = $arguments['excludeGroups'] ?? [];
$arguments['failOnRisky'] = $arguments['failOnRisky'] ?? false;
$arguments['failOnWarning'] = $arguments['failOnWarning'] ?? false;
$arguments['groups'] = $arguments['groups'] ?? [];
$arguments['processIsolation'] = $arguments['processIsolation'] ?? false;
$arguments['<API key>'] = $arguments['<API key>'] ?? false;
$arguments['<API key>'] = $arguments['<API key>'] ?? false;
$arguments['repeat'] = $arguments['repeat'] ?? false;
$arguments['<API key>'] = $arguments['<API key>'] ?? 90;
$arguments['reportLowUpperBound'] = $arguments['reportLowUpperBound'] ?? 50;
$arguments['reportUselessTests'] = $arguments['reportUselessTests'] ?? true;
$arguments['reverseList'] = $arguments['reverseList'] ?? false;
$arguments['stopOnError'] = $arguments['stopOnError'] ?? false;
$arguments['stopOnFailure'] = $arguments['stopOnFailure'] ?? false;
$arguments['stopOnIncomplete'] = $arguments['stopOnIncomplete'] ?? false;
$arguments['stopOnRisky'] = $arguments['stopOnRisky'] ?? false;
$arguments['stopOnSkipped'] = $arguments['stopOnSkipped'] ?? false;
$arguments['stopOnWarning'] = $arguments['stopOnWarning'] ?? false;
$arguments['strictCoverage'] = $arguments['strictCoverage'] ?? false;
$arguments['<API key>'] = $arguments['<API key>'] ?? [];
$arguments['testdoxGroups'] = $arguments['testdoxGroups'] ?? [];
$arguments['<API key>'] = $arguments['<API key>'] ?? 60;
$arguments['<API key>'] = $arguments['<API key>'] ?? 10;
$arguments['<API key>'] = $arguments['<API key>'] ?? 1;
$arguments['verbose'] = $arguments['verbose'] ?? false;
}
/**
* @param string $type
* @param string $message
*/
private function writeMessage($type, $message)
{
if (!$this->messagePrinted) {
$this->write("\n");
}
$this->write(
\sprintf(
"%-15s%s\n",
$type . ':',
$message
)
);
$this->messagePrinted = true;
}
} |
from settings import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
} |
#include "components/webcrypto/algorithms/util.h"
#include <openssl/aead.h>
#include <openssl/bn.h>
#include <openssl/digest.h>
#include "base/logging.h"
#include "components/webcrypto/crypto_data.h"
#include "components/webcrypto/status.h"
#include "crypto/openssl_util.h"
#include "crypto/<API key>.h"
namespace webcrypto {
const EVP_MD* GetDigest(const blink::WebCryptoAlgorithm& hash_algorithm) {
return GetDigest(hash_algorithm.id());
}
const EVP_MD* GetDigest(blink::<API key> id) {
switch (id) {
case blink::<API key>:
return EVP_sha1();
case blink::<API key>:
return EVP_sha256();
case blink::<API key>:
return EVP_sha384();
case blink::<API key>:
return EVP_sha512();
default:
return NULL;
}
}
void TruncateToBitLength(size_t length_bits, std::vector<uint8_t>* bytes) {
size_t length_bytes = NumBitsToBytes(length_bits);
if (bytes->size() != length_bytes) {
CHECK_LT(length_bytes, bytes->size());
bytes->resize(length_bytes);
}
size_t remainder_bits = length_bits % 8;
// Zero any "unused bits" in the final byte.
if (remainder_bits)
(*bytes)[bytes->size() - 1] &= ~((0xFF) >> remainder_bits);
}
Status <API key>(blink::<API key> all_possible_usages,
blink::<API key> actual_usages,
EmptyUsagePolicy empty_usage_policy) {
if (actual_usages == 0 &&
empty_usage_policy == EmptyUsagePolicy::REJECT_EMPTY) {
return Status::<API key>();
}
if (!ContainsKeyUsages(all_possible_usages, actual_usages))
return Status::<API key>();
return Status::Success();
}
bool ContainsKeyUsages(blink::<API key> a,
blink::<API key> b) {
return (a & b) == b;
}
BIGNUM* CreateBIGNUM(const std::string& n) {
return BN_bin2bn(reinterpret_cast<const uint8_t*>(n.data()), n.size(), NULL);
}
Status AeadEncryptDecrypt(EncryptOrDecrypt mode,
const std::vector<uint8_t>& raw_key,
const CryptoData& data,
unsigned int tag_length_bytes,
const CryptoData& iv,
const CryptoData& additional_data,
const EVP_AEAD* aead_alg,
std::vector<uint8_t>* buffer) {
crypto::<API key> err_tracer(FROM_HERE);
EVP_AEAD_CTX ctx;
if (!aead_alg)
return Status::ErrorUnexpected();
if (!EVP_AEAD_CTX_init(&ctx, aead_alg, raw_key.data(), raw_key.size(),
tag_length_bytes, NULL)) {
return Status::OperationError();
}
crypto::ScopedOpenSSL<EVP_AEAD_CTX, <API key>> ctx_cleanup(&ctx);
size_t len;
int ok;
if (mode == DECRYPT) {
if (data.byte_length() < tag_length_bytes)
return Status::ErrorDataTooSmall();
buffer->resize(data.byte_length() - tag_length_bytes);
ok = EVP_AEAD_CTX_open(&ctx, buffer->data(), &len, buffer->size(),
iv.bytes(), iv.byte_length(), data.bytes(),
data.byte_length(), additional_data.bytes(),
additional_data.byte_length());
} else {
// No need to check for unsigned integer overflow here (seal fails if
// the output buffer is too small).
buffer->resize(data.byte_length() + <API key>(aead_alg));
ok = EVP_AEAD_CTX_seal(&ctx, buffer->data(), &len, buffer->size(),
iv.bytes(), iv.byte_length(), data.bytes(),
data.byte_length(), additional_data.bytes(),
additional_data.byte_length());
}
if (!ok)
return Status::OperationError();
buffer->resize(len);
return Status::Success();
}
} // namespace webcrypto |
package org.xwalk.embedded.api.sample.basic;
import org.xwalk.embedded.api.sample.R;
import org.xwalk.core.XWalkActivity;
import org.xwalk.core.XWalkPreferences;
import org.xwalk.core.XWalkView;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
public class <API key> extends XWalkActivity{
private XWalkView mXWalkView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
XWalkPreferences.setValue(XWalkPreferences.<API key>, true);
setContentView(R.layout.xwview_layout);
mXWalkView = (XWalkView) findViewById(R.id.xwalkview);
}
@Override
protected void onXWalkReady() {
StringBuffer mess = new StringBuffer();
mess.append("Test Purpose: \n\n")
.append("Check XWalkView's transparent feature.\n\n")
.append("Expected Result:\n\n")
.append("Test passes if you can see transparent webpage BAIDU");
new AlertDialog.Builder(this)
.setTitle("Info" )
.setMessage(mess.toString())
.setPositiveButton("confirm" , null )
.show();
mXWalkView.setBackgroundColor(Color.TRANSPARENT);
mXWalkView.load("http:
}
} |
<!
This file is auto-generated from <API key>.py
DO NOT EDIT!
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebGL Shader Operator Conformance Tests</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css"/>
<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.<API key>');
</script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<canvas id="canvas" width="256" height="256"> </canvas>
<script>
var wtu = WebGLTestUtils;
var gl = wtu.create3DContext('canvas', null, 2);
functional.gles3.<API key>.run(gl, [16, 17]);
</script>
</body>
</html> |
<?php
namespace Drupal\Tests\field\Kernel\Boolean;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Entity\Display\<API key>;
use Drupal\Core\Entity\<API key>;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests the boolean formatter.
*
* @group field
*/
class <API key> extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['field', 'text', 'entity_test', 'user', 'system'];
/**
* @var string
*/
protected $entityType;
/**
* @var string
*/
protected $bundle;
/**
* @var string
*/
protected $fieldName;
/**
* @var \Drupal\Core\Entity\Display\<API key>
*/
protected $display;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(['field']);
$this->installEntitySchema('entity_test');
$this->entityType = 'entity_test';
$this->bundle = $this->entityType;
$this->fieldName = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => $this->entityType,
'type' => 'boolean',
]);
$field_storage->save();
$instance = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $this->bundle,
'label' => $this->randomMachineName(),
]);
$instance->save();
$this->display = entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($this->fieldName, [
'type' => 'boolean',
'settings' => [],
]);
$this->display->save();
}
/**
* Renders fields of a given entity with a given display.
*
* @param \Drupal\Core\Entity\<API key> $entity
* The entity object with attached fields to render.
* @param \Drupal\Core\Entity\Display\<API key> $display
* The display to render the fields in.
*
* @return string
* The rendered entity fields.
*/
protected function renderEntityFields(<API key> $entity, <API key> $display) {
$content = $display->build($entity);
$content = $this->render($content);
return $content;
}
/**
* Tests boolean formatter output.
*/
public function <API key>() {
$data = [];
$data[] = [0, [], 'Off'];
$data[] = [1, [], 'On'];
$format = ['format' => 'enabled-disabled'];
$data[] = [0, $format, 'Disabled'];
$data[] = [1, $format, 'Enabled'];
$format = ['format' => 'unicode-yes-no'];
$data[] = [1, $format, ''];
$data[] = [0, $format, ''];
$format = [
'format' => 'custom',
'format_custom_false' => 'FALSE',
'format_custom_true' => 'TRUE'
];
$data[] = [0, $format, 'FALSE'];
$data[] = [1, $format, 'TRUE'];
foreach ($data as $test_data) {
list($value, $settings, $expected) = $test_data;
$component = $this->display->getComponent($this->fieldName);
$component['settings'] = $settings;
$this->display->setComponent($this->fieldName, $component);
$entity = EntityTest::create([]);
$entity->{$this->fieldName}->value = $value;
// Verify that all HTML is escaped and newlines are retained.
$this->renderEntityFields($entity, $this->display);
$this->assertRaw($expected);
}
}
} |
Creates checkbox with label.
php
FormItem::checkbox('active', 'Active')
 |
// <API key>: Apache-2.0
#pragma once
#include "subgrid.h"
#include "<API key>.h"
#include "<API key>.h"
namespace embree
{
namespace isa
{
template<int M>
__forceinline void interpolateUV(PlueckerHitM<M,UVIdentity<M>> &hit,const GridMesh::Grid &g, const SubGrid& subgrid, const vint<M> &stepX, const vint<M> &stepY)
{
/* correct U,V interpolation across the entire grid */
const vint<M> sx((int)subgrid.x());
const vint<M> sy((int)subgrid.y());
const vint<M> sxM(sx + stepX);
const vint<M> syM(sy + stepY);
const float inv_resX = rcp((float)((int)g.resX-1));
const float inv_resY = rcp((float)((int)g.resY-1));
hit.U = (hit.U + vfloat<M>(sxM) * hit.UVW) * inv_resX;
hit.V = (hit.V + vfloat<M>(syM) * hit.UVW) * inv_resY;
}
template<int M, bool filter>
struct <API key>;
template<int M, bool filter>
struct <API key>
{
__forceinline <API key>() {}
__forceinline <API key>(const Ray& ray, const void* ptr) {}
__forceinline void intersect(RayHit& ray, IntersectContext* context,
const Vec3vf<M>& v0, const Vec3vf<M>& v1, const Vec3vf<M>& v2, const Vec3vf<M>& v3,
const GridMesh::Grid &g, const SubGrid& subgrid) const
{
UVIdentity<M> mapUV;
PlueckerHitM<M,UVIdentity<M>> hit(mapUV);
<API key><M> intersector(ray,nullptr);
Intersect1EpilogMU<M,filter> epilog(ray,context,subgrid.geomID(),subgrid.primID());
/* intersect first triangle */
if (intersector.intersect(ray,v0,v1,v3,mapUV,hit))
{
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
epilog(hit.valid,hit);
}
/* intersect second triangle */
if (intersector.intersect(ray,v2,v3,v1,mapUV,hit))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
epilog(hit.valid,hit);
}
}
__forceinline bool occluded(Ray& ray, IntersectContext* context,
const Vec3vf<M>& v0, const Vec3vf<M>& v1, const Vec3vf<M>& v2, const Vec3vf<M>& v3,
const GridMesh::Grid &g, const SubGrid& subgrid) const
{
UVIdentity<M> mapUV;
PlueckerHitM<M,UVIdentity<M>> hit(mapUV);
<API key><M> intersector(ray,nullptr);
Occluded1EpilogMU<M,filter> epilog(ray,context,subgrid.geomID(),subgrid.primID());
/* intersect first triangle */
if (intersector.intersect(ray,v0,v1,v3,mapUV,hit))
{
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
if (epilog(hit.valid,hit))
return true;
}
/* intersect second triangle */
if (intersector.intersect(ray,v2,v3,v1,mapUV,hit))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
if (epilog(hit.valid,hit))
return true;
}
return false;
}
};
#if defined (__AVX__)
/*! Intersects 4 quads with 1 ray using AVX */
template<bool filter>
struct <API key><4,filter>
{
__forceinline <API key>() {}
__forceinline <API key>(const Ray& ray, const void* ptr) {}
template<typename Epilog>
__forceinline bool intersect(Ray& ray, const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3, const GridMesh::Grid &g, const SubGrid& subgrid, const Epilog& epilog) const
{
const Vec3vf8 vtx0(vfloat8(v0.x,v2.x),vfloat8(v0.y,v2.y),vfloat8(v0.z,v2.z));
#if !defined(<API key>)
const Vec3vf8 vtx1(vfloat8(v1.x),vfloat8(v1.y),vfloat8(v1.z));
const Vec3vf8 vtx2(vfloat8(v3.x),vfloat8(v3.y),vfloat8(v3.z));
#else
const Vec3vf8 vtx1(vfloat8(v1.x,v3.x),vfloat8(v1.y,v3.y),vfloat8(v1.z,v3.z));
const Vec3vf8 vtx2(vfloat8(v3.x,v1.x),vfloat8(v3.y,v1.y),vfloat8(v3.z,v1.z));
#endif
UVIdentity<8> mapUV;
PlueckerHitM<8,UVIdentity<8>> hit(mapUV);
<API key><8> intersector(ray,nullptr);
const vbool8 flags(0,0,0,0,1,1,1,1);
if (unlikely(intersector.intersect(ray,vtx0,vtx1,vtx2,mapUV,hit)))
{
/* correct U,V interpolation across the entire grid */
const vfloat8 U = select(flags,hit.UVW - hit.V,hit.U);
const vfloat8 V = select(flags,hit.UVW - hit.U,hit.V);
hit.U = U;
hit.V = V;
hit.vNg *= select(flags,vfloat8(-1.0f),vfloat8(1.0f));
interpolateUV<8>(hit,g,subgrid,vint<8>(0,1,1,0,0,1,1,0),vint<8>(0,0,1,1,0,0,1,1));
if (unlikely(epilog(hit.valid,hit)))
return true;
}
return false;
}
__forceinline bool intersect(RayHit& ray, IntersectContext* context,
const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3,
const GridMesh::Grid &g, const SubGrid& subgrid) const
{
return intersect(ray,v0,v1,v2,v3,g,subgrid,Intersect1EpilogMU<8,filter>(ray,context,subgrid.geomID(),subgrid.primID()));
}
__forceinline bool occluded(Ray& ray, IntersectContext* context,
const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3,
const GridMesh::Grid &g, const SubGrid& subgrid) const
{
return intersect(ray,v0,v1,v2,v3,g,subgrid,Occluded1EpilogMU<8,filter>(ray,context,subgrid.geomID(),subgrid.primID()));
}
};
#endif
/* -- ray packet intersectors -- */
template<int K>
__forceinline void interpolateUV(const vbool<K>& valid, PlueckerHitK<K,UVIdentity<K>> &hit,const GridMesh::Grid &g, const SubGrid& subgrid, const unsigned int i)
{
/* correct U,V interpolation across the entire grid */
const unsigned int sx = subgrid.x() + (unsigned int)(i % 2);
const unsigned int sy = subgrid.y() + (unsigned int)(i >>1);
const float inv_resX = rcp((float)(int)(g.resX-1));
const float inv_resY = rcp((float)(int)(g.resY-1));
hit.U = select(valid,(hit.U + vfloat<K>((float)sx) * hit.UVW) * inv_resX,hit.U);
hit.V = select(valid,(hit.V + vfloat<K>((float)sy) * hit.UVW) * inv_resY,hit.V);
}
template<int M, int K, bool filter>
struct <API key>
{
__forceinline <API key>(const vbool<K>& valid, const RayK<K>& ray) {}
template<typename Epilog>
__forceinline bool intersectK(const vbool<K>& valid,
RayK<K>& ray,
const Vec3vf<K>& v0,
const Vec3vf<K>& v1,
const Vec3vf<K>& v2,
const Vec3vf<K>& v3,
const GridMesh::Grid &g,
const SubGrid &subgrid,
const unsigned int i,
const Epilog& epilog) const
{
UVIdentity<K> mapUV;
PlueckerHitK<K,UVIdentity<K>> hit(mapUV);
<API key><M,K> intersector;
const vbool<K> valid0 = intersector.intersectK(valid,ray,v0,v1,v3,mapUV,hit);
if (any(valid0))
{
interpolateUV(valid0,hit,g,subgrid,i);
epilog(valid0,hit);
}
const vbool<K> valid1 = intersector.intersectK(valid,ray,v2,v3,v1,mapUV,hit);
if (any(valid1))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV(valid1,hit,g,subgrid,i);
epilog(valid1,hit);
}
return any(valid0|valid1);
}
template<typename Epilog>
__forceinline bool occludedK(const vbool<K>& valid,
RayK<K>& ray,
const Vec3vf<K>& v0,
const Vec3vf<K>& v1,
const Vec3vf<K>& v2,
const Vec3vf<K>& v3,
const GridMesh::Grid &g,
const SubGrid &subgrid,
const unsigned int i,
const Epilog& epilog) const
{
UVIdentity<K> mapUV;
PlueckerHitK<K,UVIdentity<K>> hit(mapUV);
<API key><M,K> intersector;
vbool<K> valid_final = valid;
const vbool<K> valid0 = intersector.intersectK(valid,ray,v0,v1,v3,mapUV,hit);
if (any(valid0))
{
interpolateUV(valid0,hit,g,subgrid,i);
epilog(valid0,hit);
valid_final &= !valid0;
}
if (none(valid_final)) return true;
const vbool<K> valid1 = intersector.intersectK(valid,ray,v2,v3,v1,mapUV,hit);
if (any(valid1))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV(valid1,hit,g,subgrid,i);
epilog(valid1,hit);
valid_final &= !valid1;
}
return none(valid_final);
}
};
template<int M, int K, bool filter>
struct <API key> : public <API key><M,K,filter>
{
__forceinline <API key>(const vbool<K>& valid, const RayK<K>& ray)
: <API key><M,K,filter>(valid,ray) {}
__forceinline void intersect1(RayHitK<K>& ray, size_t k, IntersectContext* context,
const Vec3vf<M>& v0, const Vec3vf<M>& v1, const Vec3vf<M>& v2, const Vec3vf<M>& v3, const GridMesh::Grid &g, const SubGrid &subgrid) const
{
UVIdentity<M> mapUV;
PlueckerHitM<M,UVIdentity<M>> hit(mapUV);
Intersect1KEpilogMU<M,K,filter> epilog(ray,k,context,subgrid.geomID(),subgrid.primID());
<API key><M,K> intersector;
/* intersect first triangle */
if (intersector.intersect(ray,k,v0,v1,v3,mapUV,hit))
{
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
epilog(hit.valid,hit);
}
/* intersect second triangle */
if (intersector.intersect(ray,k,v2,v3,v1,mapUV,hit))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
epilog(hit.valid,hit);
}
}
__forceinline bool occluded1(RayK<K>& ray, size_t k, IntersectContext* context,
const Vec3vf<M>& v0, const Vec3vf<M>& v1, const Vec3vf<M>& v2, const Vec3vf<M>& v3, const GridMesh::Grid &g, const SubGrid &subgrid) const
{
UVIdentity<M> mapUV;
PlueckerHitM<M,UVIdentity<M>> hit(mapUV);
Occluded1KEpilogMU<M,K,filter> epilog(ray,k,context,subgrid.geomID(),subgrid.primID());
<API key><M,K> intersector;
/* intersect first triangle */
if (intersector.intersect(ray,k,v0,v1,v3,mapUV,hit))
{
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
if (epilog(hit.valid,hit)) return true;
}
/* intersect second triangle */
if (intersector.intersect(ray,k,v2,v3,v1,mapUV,hit))
{
hit.U = hit.UVW - hit.U;
hit.V = hit.UVW - hit.V;
interpolateUV<M>(hit,g,subgrid,vint<M>(0,1,1,0),vint<M>(0,0,1,1));
if (epilog(hit.valid,hit)) return true;
}
return false;
}
};
#if defined (__AVX__)
/*! Intersects 4 quads with 1 ray using AVX */
template<int K, bool filter>
struct <API key><4,K,filter> : public <API key><4,K,filter>
{
__forceinline <API key>(const vbool<K>& valid, const RayK<K>& ray)
: <API key><4,K,filter>(valid,ray) {}
template<typename Epilog>
__forceinline bool intersect1(RayK<K>& ray, size_t k,const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3,
const GridMesh::Grid &g, const SubGrid &subgrid, const Epilog& epilog) const
{
const Vec3vf8 vtx0(vfloat8(v0.x,v2.x),vfloat8(v0.y,v2.y),vfloat8(v0.z,v2.z));
#if !defined(<API key>)
const Vec3vf8 vtx1(vfloat8(v1.x),vfloat8(v1.y),vfloat8(v1.z));
const Vec3vf8 vtx2(vfloat8(v3.x),vfloat8(v3.y),vfloat8(v3.z));
#else
const Vec3vf8 vtx1(vfloat8(v1.x,v3.x),vfloat8(v1.y,v3.y),vfloat8(v1.z,v3.z));
const Vec3vf8 vtx2(vfloat8(v3.x,v1.x),vfloat8(v3.y,v1.y),vfloat8(v3.z,v1.z));
#endif
UVIdentity<8> mapUV;
PlueckerHitM<8,UVIdentity<8>> hit(mapUV);
<API key><8,K> intersector;
const vbool8 flags(0,0,0,0,1,1,1,1);
if (unlikely(intersector.intersect(ray,k,vtx0,vtx1,vtx2,mapUV,hit)))
{
/* correct U,V interpolation across the entire grid */
const vfloat8 U = select(flags,hit.UVW - hit.V,hit.U);
const vfloat8 V = select(flags,hit.UVW - hit.U,hit.V);
hit.U = U;
hit.V = V;
hit.vNg *= select(flags,vfloat8(-1.0f),vfloat8(1.0f));
interpolateUV<8>(hit,g,subgrid,vint<8>(0,1,1,0,0,1,1,0),vint<8>(0,0,1,1,0,0,1,1));
if (unlikely(epilog(hit.valid,hit)))
return true;
}
return false;
}
__forceinline bool intersect1(RayHitK<K>& ray, size_t k, IntersectContext* context,
const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3, const GridMesh::Grid &g, const SubGrid &subgrid) const
{
return intersect1(ray,k,v0,v1,v2,v3,g,subgrid,Intersect1KEpilogMU<8,K,filter>(ray,k,context,subgrid.geomID(),subgrid.primID()));
}
__forceinline bool occluded1(RayK<K>& ray, size_t k, IntersectContext* context,
const Vec3vf4& v0, const Vec3vf4& v1, const Vec3vf4& v2, const Vec3vf4& v3, const GridMesh::Grid &g, const SubGrid &subgrid) const
{
return intersect1(ray,k,v0,v1,v2,v3,g,subgrid,Occluded1KEpilogMU<8,K,filter>(ray,k,context,subgrid.geomID(),subgrid.primID()));
}
};
#endif
}
} |
#include "arm_math.h"
/**
* @ingroup groupStats
*/
/**
* @defgroup Min Minimum
*
* Computes the minimum value of an array of data.
* The function returns both the minimum value and its position within the array.
* There are separate functions for floating-point, Q31, Q15, and Q7 data types.
*/
/**
* @addtogroup Min
* @{
*/
/**
* @brief Minimum value of a floating-point vector.
* @param[in] *pSrc points to the input vector
* @param[in] blockSize length of the input vector
* @param[out] *pResult minimum value returned here
* @param[out] *pIndex index of minimum value returned here
* @return none.
*
*/
void arm_min_f32(
float32_t * pSrc,
uint32_t blockSize,
float32_t * pResult,
uint32_t * pIndex)
{
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
float32_t minVal1, minVal2, out; /* Temporary variables to store the output value. */
uint32_t blkCnt, outIndex, count; /* loop counter */
/* Initialise the count value. */
count = 0u;
/* Initialise the index value to zero. */
outIndex = 0u;
/* Load first input value that act as reference value for comparision */
out = *pSrc++;
/* Loop unrolling */
blkCnt = (blockSize - 1u) >> 2u;
while(blkCnt > 0)
{
/* Initialize minVal to the next consecutive values one by one */
minVal1 = *pSrc++;
minVal2 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and its index */
out = minVal1;
outIndex = count + 1u;
}
minVal1 = *pSrc++;
/* compare for the minimum value */
if(out > minVal2)
{
/* Update the minimum value and its index */
out = minVal2;
outIndex = count + 2u;
}
minVal2 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and its index */
out = minVal1;
outIndex = count + 3u;
}
/* compare for the minimum value */
if(out > minVal2)
{
/* Update the minimum value and its index */
out = minVal2;
outIndex = count + 4u;
}
count += 4u;
blkCnt
}
/* if (blockSize - 1u ) is not multiple of 4 */
blkCnt = (blockSize - 1u) % 4u;
#else
/* Run the below code for Cortex-M0 */
float32_t minVal1, out; /* Temporary variables to store the output value. */
uint32_t blkCnt, outIndex; /* loop counter */
/* Initialise the index value to zero. */
outIndex = 0u;
/* Load first input value that act as reference value for comparision */
out = *pSrc++;
blkCnt = (blockSize - 1u);
#endif // #ifndef ARM_MATH_CM0_FAMILY
while(blkCnt > 0)
{
/* Initialize minVal to the next consecutive values one by one */
minVal1 = *pSrc++;
/* compare for the minimum value */
if(out > minVal1)
{
/* Update the minimum value and it's index */
out = minVal1;
outIndex = blockSize - blkCnt;
}
blkCnt
}
/* Store the minimum value and it's index into destination pointers */
*pResult = out;
*pIndex = outIndex;
}
/**
* @} end of Min group
*/ |
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
namespace AllReady.Migrations
{
public partial class <API key> : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "CampaignId",
table: "CampaignImpact",
nullable: false,
defaultValue: 0);
migrationBuilder.Sql(
@"UPDATE i SET i.[CampaignId] = c.[CampaignImpactId]
FROM [CampaignImpact] i
INNER JOIN [Campaign] c ON i.Id = c.[CampaignImpactId]");
migrationBuilder.DropForeignKey(
name: "<API key>",
table: "Campaign");
migrationBuilder.DropIndex(
name: "<API key>",
table: "Campaign");
migrationBuilder.DropColumn(
name: "CampaignImpactId",
table: "Campaign");
migrationBuilder.CreateIndex(
name: "<API key>",
table: "CampaignImpact",
column: "CampaignId");
migrationBuilder.AddForeignKey(
name: "<API key>",
table: "CampaignImpact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "<API key>",
table: "CampaignImpact");
migrationBuilder.AddColumn<int>(
name: "CampaignImpactId",
table: "Campaign",
nullable: true);
migrationBuilder.Sql(
@"UPDATE c SET c.[CampaignImpactId] = i.[Id]
FROM [Campaign] c
INNER JOIN [CampaignImpact] i ON i.CampaignId = c.[Id]");
migrationBuilder.DropIndex(
name: "<API key>",
table: "CampaignImpact");
migrationBuilder.DropColumn(
name: "CampaignId",
table: "CampaignImpact");
migrationBuilder.CreateIndex(
name: "<API key>",
table: "Campaign",
column: "CampaignImpactId");
migrationBuilder.AddForeignKey(
name: "<API key>",
table: "Campaign",
column: "CampaignImpactId",
principalTable: "CampaignImpact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
} |
/**
* @fileoverview Tests for yoda rule.
* @author Raphael Pigulla
*/
"use strict";
// Requirements
const rule = require("../../../lib/rules/yoda"),
RuleTester = require("../../../lib/testers/rule-tester");
// Tests
const ruleTester = new RuleTester();
ruleTester.run("yoda", rule, {
valid: [
// "never" mode
{ code: "if (value === \"red\") {}", options: ["never"] },
{ code: "if (value === value) {}", options: ["never"] },
{ code: "if (value != 5) {}", options: ["never"] },
{ code: "if (5 & foo) {}", options: ["never"] },
{ code: "if (5 === 4) {}", options: ["never"] },
// "always" mode
{ code: "if (\"blue\" === value) {}", options: ["always"] },
{ code: "if (value === value) {}", options: ["always"] },
{ code: "if (4 != value) {}", options: ["always"] },
{ code: "if (foo & 4) {}", options: ["always"] },
{ code: "if (5 === 4) {}", options: ["always"] },
// Range exception
{
code: "if (0 < x && x <= 1) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (x < 0 || 1 <= x) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (0 <= x && x < 1) {}",
options: ["always", { exceptRange: true }]
}, {
code: "if (x <= 'bar' || 'foo' < x) {}",
options: ["always", { exceptRange: true }]
}, {
code: "if ('blue' < x.y && x.y < 'green') {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (0 <= x['y'] && x['y'] <= 100) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (a < 0 && (0 < b && b < 1)) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if ((0 < a && a < 1) && b < 0) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (a < 4 || (b[c[0]].d['e'] < 0 || 1 <= b[c[0]].d['e'])) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (-1 < x && x < 0) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (0 <= this.prop && this.prop <= 1) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (0 <= index && index < list.length) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (ZERO <= index && index < 100) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (value <= MIN || 10 < value) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (value <= 0 || MAX < value) {}",
options: ["never", { exceptRange: true }]
}, {
code: "if (0 <= a.b && a[\"b\"] <= 100) {}",
options: ["never", { exceptRange: true }]
},
// onlyEquality
{ code: "if (0 < x && x <= 1) {}", options: ["never", { onlyEquality: true }] },
{ code: "if (x !== 'foo' && 'foo' !== x) {}", options: ["never", { onlyEquality: true }] },
{ code: "if (x < 2 && x !== -3) {}", options: ["always", { onlyEquality: true }] }
],
invalid: [
{
code: "if (\"red\" == value) {}",
output: "if (value == \"red\") {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of ==.",
type: "BinaryExpression"
}
]
},
{
code: "if (true === value) {}",
output: "if (value === true) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "if (5 != value) {}",
output: "if (value != 5) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of !=.",
type: "BinaryExpression"
}
]
},
{
code: "if (null !== value) {}",
output: "if (value !== null) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of !==.",
type: "BinaryExpression"
}
]
},
{
code: "if (\"red\" <= value) {}",
output: "if (value >= \"red\") {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (true >= value) {}",
output: "if (value <= true) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of >=.",
type: "BinaryExpression"
}
]
},
{
code: "var foo = (5 < value) ? true : false",
output: "var foo = (value > 5) ? true : false",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of <.",
type: "BinaryExpression"
}
]
},
{
code: "function foo() { return (null > value); }",
output: "function foo() { return (value < null); }",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of >.",
type: "BinaryExpression"
}
]
},
{
code: "if (-1 < str.indexOf(substr)) {}",
output: "if (str.indexOf(substr) > -1) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of <.",
type: "BinaryExpression"
}
]
},
{
code: "if (value == \"red\") {}",
output: "if (\"red\" == value) {}",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ==.",
type: "BinaryExpression"
}
]
},
{
code: "if (value === true) {}",
output: "if (true === value) {}",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "if (a < 0 && 0 <= b && b < 1) {}",
output: "if (a < 0 && b >= 0 && b < 1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= a && a < 1 && b < 1) {}",
output: "if (a >= 0 && a < 1 && b < 1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (1 < a && a < 0) {}",
output: "if (a > 1 && a < 0) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <.",
type: "BinaryExpression"
}
]
},
{
code: "0 < a && a < 1",
output: "a > 0 && a < 1",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <.",
type: "BinaryExpression"
}
]
},
{
code: "var a = b < 0 || 1 <= b;",
output: "var a = b < 0 || b >= 1;",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= x && x < -1) {}",
output: "if (x >= 0 && x < -1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "var a = (b < 0 && 0 <= b);",
output: "var a = (0 > b && 0 <= b);",
options: ["always", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the left side of <.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= a[b] && a['b'] < 1) {}",
output: "if (a[b] >= 0 && a['b'] < 1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= a[b] && a.b < 1) {}",
output: "if (a[b] >= 0 && a.b < 1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= a[b()] && a[b()] < 1) {}",
output: "if (a[b()] >= 0 && a[b()] < 1) {}",
options: ["never", { exceptRange: true }],
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if (3 == a) {}",
output: "if (a == 3) {}",
options: ["never", { onlyEquality: true }],
errors: [
{
message: "Expected literal to be on the right side of ==.",
type: "BinaryExpression"
}
]
},
{
code: "foo(3 === a);",
output: "foo(a === 3);",
options: ["never", { onlyEquality: true }],
errors: [
{
message: "Expected literal to be on the right side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "foo(a === 3);",
output: "foo(3 === a);",
options: ["always", { onlyEquality: true }],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "if (0 <= x && x < 1) {}",
output: "if (x >= 0 && x < 1) {}",
errors: [
{
message: "Expected literal to be on the right side of <=.",
type: "BinaryExpression"
}
]
},
{
code: "if ( 0 < foo ) {}",
output: "if ( foo > 0 ) {}",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of <.",
type: "BinaryExpression"
}
]
},
{
code: "if ( foo > 0 ) {}",
output: "if ( 0 < foo ) {}",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of >.",
type: "BinaryExpression"
}
]
},
{
code: "if (foo()===1) {}",
output: "if (1===foo()) {}",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "if (foo() === 1) {}",
output: "if (1 === foo()) {}",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "while (0 === (a));",
output: "while ((a) === 0);",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "while (0 === (a = b));",
output: "while ((a = b) === 0);",
options: ["never"],
errors: [
{
message: "Expected literal to be on the right side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "while ((a) === 0);",
output: "while (0 === (a));",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "while ((a = b) === 0);",
output: "while (0 === (a = b));",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
},
{
code: "if (((((((((((foo)))))))))) === ((((((5)))))));",
output: "if (((((((5)))))) === ((((((((((foo)))))))))));",
options: ["always"],
errors: [
{
message: "Expected literal to be on the left side of ===.",
type: "BinaryExpression"
}
]
}
]
}); |
#ifndef CONF_NVM_H_INCLUDED
#define CONF_NVM_H_INCLUDED
#endif //CONF_NVM_H_INCLUDED |
package com.phonegap;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.webkit.WebView;
public class GeoListener {
public static int PERMISSION_DENIED = 1;
public static int <API key> = 2;
public static int TIMEOUT = 3;
String id; // Listener ID
String successCallback;
String failCallback;
GpsListener mGps; // GPS listener
NetworkListener mNetwork; // Network listener
LocationManager mLocMan; // Location manager
private GeoBroker broker; // GeoBroker object
int interval;
/**
* Constructor.
*
* @param id Listener id
* @param ctx
* @param time Sampling period in msec
* @param appView
*/
GeoListener(GeoBroker broker, String id, int time) {
this.id = id;
this.interval = time;
this.broker = broker;
this.mGps = null;
this.mNetwork = null;
this.mLocMan = (LocationManager) broker.ctx.getSystemService(Context.LOCATION_SERVICE);
// If GPS provider, then create and start GPS listener
if (this.mLocMan.getProvider(LocationManager.GPS_PROVIDER) != null) {
this.mGps = new GpsListener(broker.ctx, time, this);
}
// If network provider, then create and start network listener
if (this.mLocMan.getProvider(LocationManager.NETWORK_PROVIDER) != null) {
this.mNetwork = new NetworkListener(broker.ctx, time, this);
}
}
/**
* Destroy listener.
*/
public void destroy() {
this.stop();
}
/**
* Location found. Send location back to JavaScript.
*
* @param loc
*/
void success(Location loc) {
String params = loc.getLatitude() + "," + loc.getLongitude() + ", " + loc.getAltitude() +
"," + loc.getAccuracy() + "," + loc.getBearing() +
"," + loc.getSpeed() + "," + loc.getTime();
if (id == "global") {
this.stop();
}
this.broker.sendJavascript("navigator._geo.success('" + id + "'," + params + ");");
}
/**
* Location failed. Send error back to JavaScript.
*
* @param code The error code
* @param msg The error message
*/
void fail(int code, String msg) {
this.broker.sendJavascript("navigator._geo.fail('" + this.id + "', '" + code + "', '" + msg + "');");
this.stop();
}
/**
* Start retrieving location.
*
* @param interval
*/
void start(int interval) {
if (this.mGps != null) {
this.mGps.start(interval);
}
if (this.mNetwork != null) {
this.mNetwork.start(interval);
}
if (this.mNetwork == null && this.mGps == null) {
this.fail(<API key>, "No location providers available.");
}
}
/**
* Stop listening for location.
*/
void stop() {
if (this.mGps != null) {
this.mGps.stop();
}
if (this.mNetwork != null) {
this.mNetwork.stop();
}
}
} |
class BuildingAddress
include Mongoid::Document
field :city, type: String
embedded_in :building
<API key> :city
end |
declare module 'css-to-react-native' {
declare module.exports: ([string, string])[] => { [key:string]: any }
} |
namespace Singleton
{
using System;
public class LogEvent
{
public LogEvent(string message)
{
this.Message = message;
this.EventDate = DateTime.Now;
}
public string Message { get; private set; }
public DateTime EventDate { get; private set; }
}
} |
#nullable disable
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interop
{
<summary>
Holds onto a managed object as well as the CCW for that object if there is one.
</summary>
<typeparam name="THandle">The COM interface type to keep a reference to</typeparam>
<typeparam name="TObject">The managed object type to keep a reference to</typeparam>
internal struct ComHandle<THandle, TObject>
where THandle : class
where TObject : class, THandle
{
private readonly THandle _handle;
private readonly TObject _managedObject;
<summary>
Create an instance from a "ComObject" or from a managed object.
</summary>
public ComHandle(THandle <API key>)
{
if (<API key> == null)
{
_handle = null;
_managedObject = null;
}
else if (Marshal.IsComObject(<API key>))
{
_handle = <API key>;
_managedObject = ComAggregate.GetManagedObject<TObject>(<API key>);
}
else
{
_handle = (THandle)ComAggregate.TryGetWrapper(<API key>);
_managedObject = (TObject)<API key>;
}
}
public ComHandle(THandle handle, TObject managedObject)
{
if (handle == null && managedObject == null)
{
_handle = null;
_managedObject = null;
}
else
{
// NOTE: This might get triggered if you do testing with the "NoWrap"
// ComAggregatePolicy, since both handle will not be a ComObject in that
// case.
if (handle != null && !Marshal.IsComObject(handle))
{
throw new ArgumentException("must be null or a Com object", nameof(handle));
}
_handle = handle;
_managedObject = managedObject;
}
}
<summary>
Return the IComWrapperFixed object (as T) or the managed object (as T) if the managed object is not wrapped.
</summary>
public THandle Handle
{
get
{
Debug.Assert(_handle == null || Marshal.IsComObject(_handle), "Invariant broken!");
if (_handle == null)
{
return _managedObject;
}
else
{
return _handle;
}
}
}
<summary>
Return the managed object
</summary>
public TObject Object
{
get
{
return _managedObject;
}
}
public ComHandle<TNewHandle, TNewObject> Cast<TNewHandle, TNewObject>()
where TNewHandle : class
where TNewObject : class, TNewHandle
{
if (!(Handle is TNewHandle newHandle))
{
throw new <API key>("Invalid cast.");
}
if (!(Object is TNewObject newObject))
{
throw new <API key>("Invalid cast.");
}
return new ComHandle<TNewHandle, TNewObject>(newHandle, newObject);
}
}
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Single Page Apps for GitHub Pages</title>
<script type="text/javascript">
// Single Page Apps for GitHub Pages
// This script takes the current url and converts the path and query
// string into just a query string, and then redirects the browser
// to the new url with only a query string and hash fragment,
// e.g. http://www.foo.tld/one/two?a=b&c=d#qwe, becomes
// http://www.foo.tld/?p=/one/two&q=a=b~and~c=d#qwe
// Note: this 404.html file must be at least 512 bytes for it to work
// with Internet Explorer (it is currently > 512 bytes)
// If you're creating a Project Pages site and NOT using a custom domain,
// then set segmentCount to 1 (enterprise users may need to set it to > 1).
// This way the code will only replace the route part of the path, and not
// the real directory in which the app resides, for example:
// https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
// https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe
// Otherwise, leave segmentCount as 0.
var segmentCount = 0;
var l = window.location;
l.replace(
l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' +
l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') +
(l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash
);
</script>
</head>
<body>
</body>
</html> |
module.exports = require( './wrapperValue' ); |
/* <API key>: GPL-2.0 */
#ifndef __NITROX_ISR_H
#define __NITROX_ISR_H
#include "nitrox_dev.h"
int <API key>(struct nitrox_device *ndev);
void <API key>(struct nitrox_device *ndev);
#endif /* __NITROX_ISR_H */ |
<?php
namespace VuFind\Recommend;
class FacetCloud extends ExpandFacets
{
/**
* Get the facet limit.
*
* @return int
*/
public function getFacetLimit()
{
$params = $this->searchObject->getParams();
$settings = is_callable([$params, 'getFacetSettings'])
? $params->getFacetSettings() : [];
// Figure out the facet limit -- if available, we can use this to display
// "..." when more facets are available than are currently being displayed,
// although this comes at the cost of not being able to display the last
// entry in the list -- otherwise we might show "..." when we've exactly
// reached (but not exceeded) the facet limit. If we can't get a facet
// limit, we will set an arbitrary high number so that all available values
// will display and "..." will never display.
return isset($settings['limit']) ? $settings['limit'] - 1 : 100000;
}
} |
#ifndef <API key>
#define <API key>
struct buffer;
#include <sys/ptrace.h>
#ifdef __UCLIBC__
#if !(defined(__UCLIBC_HAS_MMU__) || defined(__ARCH_HAS_MMU__))
/* PTRACE_TEXT_ADDR and friends. */
#include <asm/ptrace.h>
#define HAS_NOMMU
#endif
#endif
#if !defined(PTRACE_TYPE_ARG3)
#define PTRACE_TYPE_ARG3 void *
#endif
#if !defined(PTRACE_TYPE_ARG4)
#define PTRACE_TYPE_ARG4 void *
#endif
#ifndef PTRACE_GETSIGINFO
# define PTRACE_GETSIGINFO 0x4202
# define PTRACE_SETSIGINFO 0x4203
#endif /* PTRACE_GETSIGINF */
/* If the system headers did not provide the constants, hard-code the normal
values. */
#ifndef PTRACE_EVENT_FORK
#define PTRACE_SETOPTIONS 0x4200
#define PTRACE_GETEVENTMSG 0x4201
/* options set using PTRACE_SETOPTIONS */
#define <API key> 0x00000001
#define PTRACE_O_TRACEFORK 0x00000002
#define PTRACE_O_TRACEVFORK 0x00000004
#define PTRACE_O_TRACECLONE 0x00000008
#define PTRACE_O_TRACEEXEC 0x00000010
#define <API key> 0x00000020
#define PTRACE_O_TRACEEXIT 0x00000040
/* Wait extended result codes for the above trace options. */
#define PTRACE_EVENT_FORK 1
#define PTRACE_EVENT_VFORK 2
#define PTRACE_EVENT_CLONE 3
#define PTRACE_EVENT_EXEC 4
#define <API key> 5
#define PTRACE_EVENT_EXIT 6
#endif /* PTRACE_EVENT_FORK */
#if (defined __bfin__ || defined __frv__ || defined __sh__) \
&& !defined PTRACE_GETFDPIC
#define PTRACE_GETFDPIC 31
#define <API key> 0
#define <API key> 1
#endif
/* We can't always assume that this flag is available, but all systems
with the ptrace event handlers also have __WALL, so it's safe to use
in some contexts. */
#ifndef __WALL
#define __WALL 0x40000000 /* Wait for any child. */
#endif
extern void <API key> (pid_t pid, struct buffer *buffer);
extern void <API key> (void);
extern void <API key> (pid_t pid);
extern int <API key> (void);
extern int <API key> (void);
extern int <API key> (void);
extern int <API key> (void);
#endif /* <API key> */ |
/* $Id: ioqueue_common_abs.c 4890 2014-08-19 00:54:34Z bennylp $ */
/*
* ioqueue_common_abs.c
*
* This contains common functionalities to emulate proactor pattern with
* various event dispatching mechanisms (e.g. select, epoll).
*
* This file will be included by the appropriate ioqueue implementation.
* This file is NOT supposed to be compiled as stand-alone source.
*/
#define PENDING_RETRY 2
static void ioqueue_init( pj_ioqueue_t *ioqueue )
{
ioqueue->lock = NULL;
ioqueue->auto_delete_lock = 0;
ioqueue->default_concurrency = <API key>;
}
static pj_status_t ioqueue_destroy(pj_ioqueue_t *ioqueue)
{
if (ioqueue->auto_delete_lock && ioqueue->lock ) {
pj_lock_release(ioqueue->lock);
return pj_lock_destroy(ioqueue->lock);
}
return PJ_SUCCESS;
}
/*
* pj_ioqueue_set_lock()
*/
PJ_DEF(pj_status_t) pj_ioqueue_set_lock( pj_ioqueue_t *ioqueue,
pj_lock_t *lock,
pj_bool_t auto_delete )
{
PJ_ASSERT_RETURN(ioqueue && lock, PJ_EINVAL);
if (ioqueue->auto_delete_lock && ioqueue->lock) {
pj_lock_destroy(ioqueue->lock);
}
ioqueue->lock = lock;
ioqueue->auto_delete_lock = auto_delete;
return PJ_SUCCESS;
}
static pj_status_t ioqueue_init_key( pj_pool_t *pool,
pj_ioqueue_t *ioqueue,
pj_ioqueue_key_t *key,
pj_sock_t sock,
pj_grp_lock_t *grp_lock,
void *user_data,
const pj_ioqueue_callback *cb)
{
pj_status_t rc;
int optlen;
PJ_UNUSED_ARG(pool);
key->ioqueue = ioqueue;
key->fd = sock;
key->user_data = user_data;
pj_list_init(&key->read_list);
pj_list_init(&key->write_list);
#if PJ_HAS_TCP
pj_list_init(&key->accept_list);
key->connecting = 0;
#endif
/* Save callback. */
pj_memcpy(&key->cb, cb, sizeof(pj_ioqueue_callback));
#if <API key>
/* Set initial reference count to 1 */
pj_assert(key->ref_count == 0);
++key->ref_count;
key->closing = 0;
#endif
rc = <API key>(key, ioqueue->default_concurrency);
if (rc != PJ_SUCCESS)
return rc;
/* Get socket type. When socket type is datagram, some optimization
* will be performed during send to allow parallel send operations.
*/
optlen = sizeof(key->fd_type);
rc = pj_sock_getsockopt(sock, pj_SOL_SOCKET(), pj_SO_TYPE(),
&key->fd_type, &optlen);
if (rc != PJ_SUCCESS)
key->fd_type = pj_SOCK_STREAM();
/* Create mutex for the key. */
#if !<API key>
rc = <API key>(poll, NULL, &key->lock);
#endif
if (rc != PJ_SUCCESS)
return rc;
/* Group lock */
key->grp_lock = grp_lock;
if (key->grp_lock) {
<API key>(key->grp_lock, "ioqueue", 0);
}
return PJ_SUCCESS;
}
/*
* <API key>()
*
* Obtain value associated with a key.
*/
PJ_DEF(void*) <API key>( pj_ioqueue_key_t *key )
{
PJ_ASSERT_RETURN(key != NULL, NULL);
return key->user_data;
}
/*
* <API key>()
*/
PJ_DEF(pj_status_t) <API key>( pj_ioqueue_key_t *key,
void *user_data,
void **old_data)
{
PJ_ASSERT_RETURN(key, PJ_EINVAL);
if (old_data)
*old_data = key->user_data;
key->user_data = user_data;
return PJ_SUCCESS;
}
PJ_INLINE(int) <API key>(pj_ioqueue_key_t *key)
{
return !pj_list_empty(&key->write_list);
}
PJ_INLINE(int) <API key>(pj_ioqueue_key_t *key)
{
return !pj_list_empty(&key->read_list);
}
PJ_INLINE(int) <API key>(pj_ioqueue_key_t *key)
{
#if PJ_HAS_TCP
return !pj_list_empty(&key->accept_list);
#else
PJ_UNUSED_ARG(key);
return 0;
#endif
}
PJ_INLINE(int) <API key>(pj_ioqueue_key_t *key)
{
return key->connecting;
}
#if <API key>
# define IS_CLOSING(key) (key->closing)
#else
# define IS_CLOSING(key) (0)
#endif
/*
* <API key>()
*
* Report occurence of an event in the key to be processed by the
* framework.
*/
void <API key>(pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *h)
{
/* Lock the key. */
pj_ioqueue_lock_key(h);
if (IS_CLOSING(h)) {
<API key>(h);
return;
}
#if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0
if (h->connecting) {
/* Completion of connect() operation */
pj_status_t status;
pj_bool_t has_lock;
/* Clear operation. */
h->connecting = 0;
<API key>(ioqueue, h, WRITEABLE_EVENT);
<API key>(ioqueue, h, EXCEPTION_EVENT);
#if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0)
/* from connect(2):
* On Linux, use getsockopt to read the SO_ERROR option at
* level SOL_SOCKET to determine whether connect() completed
* successfully (if SO_ERROR is zero).
*/
{
int value;
int vallen = sizeof(value);
int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR,
&value, &vallen);
if (gs_rc != 0) {
/* Argh!! What to do now???
* Just indicate that the socket is connected. The
* application will get error as soon as it tries to use
* the socket to send/receive.
*/
status = PJ_SUCCESS;
} else {
status = PJ_STATUS_FROM_OS(value);
}
}
#elif (defined(PJ_WIN32) && PJ_WIN32!=0) || (defined(PJ_WIN64) && PJ_WIN64!=0)
status = PJ_SUCCESS; /* success */
#else
{
struct sockaddr_in addr;
int addrlen = sizeof(addr);
status = pj_sock_getpeername(h->fd, (struct sockaddr*)&addr,
&addrlen);
}
#endif
/* Unlock; from this point we don't need to hold key's mutex
* (unless concurrency is disabled, which in this case we should
* hold the mutex while calling the callback) */
if (h->allow_concurrent) {
/* concurrency may be changed while we're in the callback, so
* save it to a flag.
*/
has_lock = PJ_FALSE;
<API key>(h);
} else {
has_lock = PJ_TRUE;
}
/* Call callback. */
if (h->cb.on_connect_complete && !IS_CLOSING(h))
(*h->cb.on_connect_complete)(h, status);
/* Unlock if we still hold the lock */
if (has_lock) {
<API key>(h);
}
/* Done. */
} else
#endif /* PJ_HAS_TCP */
if (<API key>(h)) {
/* Socket is writable. */
struct write_operation *write_op;
pj_ssize_t sent;
pj_status_t send_rc = PJ_SUCCESS;
/* Get the first in the queue. */
write_op = h->write_list.next;
/* For datagrams, we can remove the write_op from the list
* so that send() can work in parallel.
*/
if (h->fd_type == pj_SOCK_DGRAM()) {
pj_list_erase(write_op);
if (pj_list_empty(&h->write_list))
<API key>(ioqueue, h, WRITEABLE_EVENT);
}
/* Send the data.
* Unfortunately we must do this while holding key's mutex, thus
* preventing parallel write on a single key.. :-((
*/
sent = write_op->size - write_op->written;
if (write_op->op == PJ_IOQUEUE_OP_SEND) {
send_rc = pj_sock_send(h->fd, write_op->buf+write_op->written,
&sent, write_op->flags);
/* Can't do this. We only clear "op" after we're finished sending
* the whole buffer.
*/
//write_op->op = 0;
} else if (write_op->op == <API key>) {
int retry = 2;
while (--retry >= 0) {
send_rc = pj_sock_sendto(h->fd,
write_op->buf+write_op->written,
&sent, write_op->flags,
&write_op->rmt_addr,
write_op->rmt_addrlen);
#if defined(<API key>) && \
<API key>!=0
/* Special treatment for dead UDP sockets here, see ticket #1107 */
if (send_rc==PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(h) &&
h->fd_type==pj_SOCK_DGRAM())
{
PJ_PERROR(4,(THIS_FILE, send_rc,
"Send error for socket %d, retrying",
h->fd));
replace_udp_sock(h);
continue;
}
#endif
break;
}
/* Can't do this. We only clear "op" after we're finished sending
* the whole buffer.
*/
//write_op->op = 0;
} else {
pj_assert(!"Invalid operation type!");
write_op->op = PJ_IOQUEUE_OP_NONE;
send_rc = PJ_EBUG;
}
if (send_rc == PJ_SUCCESS) {
write_op->written += sent;
} else {
pj_assert(send_rc > 0);
write_op->written = -send_rc;
}
/* Are we finished with this buffer? */
if (send_rc!=PJ_SUCCESS ||
write_op->written == (pj_ssize_t)write_op->size ||
h->fd_type == pj_SOCK_DGRAM())
{
pj_bool_t has_lock;
write_op->op = PJ_IOQUEUE_OP_NONE;
if (h->fd_type != pj_SOCK_DGRAM()) {
/* Write completion of the whole stream. */
pj_list_erase(write_op);
/* Clear operation if there's no more data to send. */
if (pj_list_empty(&h->write_list))
<API key>(ioqueue, h, WRITEABLE_EVENT);
}
/* Unlock; from this point we don't need to hold key's mutex
* (unless concurrency is disabled, which in this case we should
* hold the mutex while calling the callback) */
if (h->allow_concurrent) {
/* concurrency may be changed while we're in the callback, so
* save it to a flag.
*/
has_lock = PJ_FALSE;
<API key>(h);
PJ_RACE_ME(5);
} else {
has_lock = PJ_TRUE;
}
/* Call callback. */
if (h->cb.on_write_complete && !IS_CLOSING(h)) {
(*h->cb.on_write_complete)(h,
(pj_ioqueue_op_key_t*)write_op,
write_op->written);
}
if (has_lock) {
<API key>(h);
}
} else {
<API key>(h);
}
/* Done. */
} else {
/*
* This is normal; execution may fall here when multiple threads
* are signalled for the same event, but only one thread eventually
* able to process the event.
*/
<API key>(h);
}
}
void <API key>( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *h )
{
pj_status_t rc;
/* Lock the key. */
pj_ioqueue_lock_key(h);
if (IS_CLOSING(h)) {
<API key>(h);
return;
}
# if PJ_HAS_TCP
if (!pj_list_empty(&h->accept_list)) {
struct accept_operation *accept_op;
pj_bool_t has_lock;
/* Get one accept operation from the list. */
accept_op = h->accept_list.next;
pj_list_erase(accept_op);
accept_op->op = PJ_IOQUEUE_OP_NONE;
/* Clear bit in fdset if there is no more pending accept */
if (pj_list_empty(&h->accept_list))
<API key>(ioqueue, h, READABLE_EVENT);
rc=pj_sock_accept(h->fd, accept_op->accept_fd,
accept_op->rmt_addr, accept_op->addrlen);
if (rc==PJ_SUCCESS && accept_op->local_addr) {
rc = pj_sock_getsockname(*accept_op->accept_fd,
accept_op->local_addr,
accept_op->addrlen);
}
/* Unlock; from this point we don't need to hold key's mutex
* (unless concurrency is disabled, which in this case we should
* hold the mutex while calling the callback) */
if (h->allow_concurrent) {
/* concurrency may be changed while we're in the callback, so
* save it to a flag.
*/
has_lock = PJ_FALSE;
<API key>(h);
PJ_RACE_ME(5);
} else {
has_lock = PJ_TRUE;
}
/* Call callback. */
if (h->cb.on_accept_complete && !IS_CLOSING(h)) {
(*h->cb.on_accept_complete)(h,
(pj_ioqueue_op_key_t*)accept_op,
*accept_op->accept_fd, rc);
}
if (has_lock) {
<API key>(h);
}
}
else
# endif
if (<API key>(h)) {
struct read_operation *read_op;
pj_ssize_t bytes_read;
pj_bool_t has_lock;
/* Get one pending read operation from the list. */
read_op = h->read_list.next;
pj_list_erase(read_op);
/* Clear fdset if there is no pending read. */
if (pj_list_empty(&h->read_list))
<API key>(ioqueue, h, READABLE_EVENT);
bytes_read = read_op->size;
if (read_op->op == <API key>) {
read_op->op = PJ_IOQUEUE_OP_NONE;
rc = pj_sock_recvfrom(h->fd, read_op->buf, &bytes_read,
read_op->flags,
read_op->rmt_addr,
read_op->rmt_addrlen);
} else if (read_op->op == PJ_IOQUEUE_OP_RECV) {
read_op->op = PJ_IOQUEUE_OP_NONE;
rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read,
read_op->flags);
} else {
pj_assert(read_op->op == PJ_IOQUEUE_OP_READ);
read_op->op = PJ_IOQUEUE_OP_NONE;
/*
* User has specified pj_ioqueue_read().
* On Win32, we should do ReadFile(). But because we got
* here because of select() anyway, user must have put a
* socket descriptor on h->fd, which in this case we can
* just call pj_sock_recv() instead of ReadFile().
* On Unix, user may put a file in h->fd, so we'll have
* to call read() here.
* This may not compile on systems which doesn't have
* read(). That's why we only specify PJ_LINUX here so
* that error is easier to catch.
*/
# if defined(PJ_WIN32) && PJ_WIN32 != 0 || \
defined(PJ_WIN64) && PJ_WIN64 != 0 || \
defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE != 0
rc = pj_sock_recv(h->fd, read_op->buf, &bytes_read,
read_op->flags);
//rc = ReadFile((HANDLE)h->fd, read_op->buf, read_op->size,
// &bytes_read, NULL);
# elif (defined(PJ_HAS_UNISTD_H) && PJ_HAS_UNISTD_H != 0)
bytes_read = read(h->fd, read_op->buf, bytes_read);
rc = (bytes_read >= 0) ? PJ_SUCCESS : pj_get_os_error();
# elif defined(PJ_LINUX_KERNEL) && PJ_LINUX_KERNEL != 0
bytes_read = sys_read(h->fd, read_op->buf, bytes_read);
rc = (bytes_read >= 0) ? PJ_SUCCESS : -bytes_read;
# else
# error "Implement read() for this platform!"
# endif
}
if (rc != PJ_SUCCESS) {
# if (defined(PJ_WIN32) && PJ_WIN32 != 0) || \
(defined(PJ_WIN64) && PJ_WIN64 != 0)
/* On Win32, for UDP, WSAECONNRESET on the receive side
* indicates that previous sending has triggered ICMP Port
* Unreachable message.
* But we wouldn't know at this point which one of previous
* key that has triggered the error, since UDP socket can
* be shared!
* So we'll just ignore it!
*/
if (rc == PJ_STATUS_FROM_OS(WSAECONNRESET)) {
//PJ_LOG(4,(THIS_FILE,
// "Ignored ICMP port unreach. on key=%p", h));
}
# endif
/* In any case we would report this to caller. */
bytes_read = -rc;
#if defined(<API key>) && \
<API key>!=0
/* Special treatment for dead UDP sockets here, see ticket #1107 */
if (rc == PJ_STATUS_FROM_OS(ENOTCONN) && !IS_CLOSING(h) &&
h->fd_type==pj_SOCK_DGRAM())
{
replace_udp_sock(h);
}
#endif
}
/* Unlock; from this point we don't need to hold key's mutex
* (unless concurrency is disabled, which in this case we should
* hold the mutex while calling the callback) */
if (h->allow_concurrent) {
/* concurrency may be changed while we're in the callback, so
* save it to a flag.
*/
has_lock = PJ_FALSE;
<API key>(h);
PJ_RACE_ME(5);
} else {
has_lock = PJ_TRUE;
}
/* Call callback. */
if (h->cb.on_read_complete && !IS_CLOSING(h)) {
(*h->cb.on_read_complete)(h,
(pj_ioqueue_op_key_t*)read_op,
bytes_read);
}
if (has_lock) {
<API key>(h);
}
} else {
/*
* This is normal; execution may fall here when multiple threads
* are signalled for the same event, but only one thread eventually
* able to process the event.
*/
<API key>(h);
}
}
void <API key>( pj_ioqueue_t *ioqueue,
pj_ioqueue_key_t *h )
{
pj_bool_t has_lock;
pj_ioqueue_lock_key(h);
if (!h->connecting) {
/* It is possible that more than one thread was woken up, thus
* the remaining thread will see h->connecting as zero because
* it has been processed by other thread.
*/
<API key>(h);
return;
}
if (IS_CLOSING(h)) {
<API key>(h);
return;
}
/* Clear operation. */
h->connecting = 0;
<API key>(ioqueue, h, WRITEABLE_EVENT);
<API key>(ioqueue, h, EXCEPTION_EVENT);
/* Unlock; from this point we don't need to hold key's mutex
* (unless concurrency is disabled, which in this case we should
* hold the mutex while calling the callback) */
if (h->allow_concurrent) {
/* concurrency may be changed while we're in the callback, so
* save it to a flag.
*/
has_lock = PJ_FALSE;
<API key>(h);
PJ_RACE_ME(5);
} else {
has_lock = PJ_TRUE;
}
/* Call callback. */
if (h->cb.on_connect_complete && !IS_CLOSING(h)) {
pj_status_t status = -1;
#if (defined(PJ_HAS_SO_ERROR) && PJ_HAS_SO_ERROR!=0)
int value;
int vallen = sizeof(value);
int gs_rc = pj_sock_getsockopt(h->fd, SOL_SOCKET, SO_ERROR,
&value, &vallen);
if (gs_rc == 0) {
status = PJ_RETURN_OS_ERROR(value);
}
#endif
(*h->cb.on_connect_complete)(h, status);
}
if (has_lock) {
<API key>(h);
}
}
/*
* pj_ioqueue_recv()
*
* Start asynchronous recv() from the socket.
*/
PJ_DEF(pj_status_t) pj_ioqueue_recv( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
void *buffer,
pj_ssize_t *length,
unsigned flags )
{
struct read_operation *read_op;
PJ_ASSERT_RETURN(key && op_key && buffer && length, PJ_EINVAL);
PJ_CHECK_STACK();
/* Check if key is closing (need to do this first before accessing
* other variables, since they might have been destroyed. See ticket
* #469).
*/
if (IS_CLOSING(key))
return PJ_ECANCELLED;
read_op = (struct read_operation*)op_key;
read_op->op = PJ_IOQUEUE_OP_NONE;
/* Try to see if there's data immediately available.
*/
if ((flags & <API key>) == 0) {
pj_status_t status;
pj_ssize_t size;
size = *length;
status = pj_sock_recv(key->fd, buffer, &size, flags);
if (status == PJ_SUCCESS) {
/* Yes! Data is available! */
*length = size;
return PJ_SUCCESS;
} else {
/* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
* the error to caller.
*/
if (status != PJ_STATUS_FROM_OS(<API key>))
return status;
}
}
flags &= ~(<API key>);
/*
* No data is immediately available.
* Must schedule asynchronous operation to the ioqueue.
*/
read_op->op = PJ_IOQUEUE_OP_RECV;
read_op->buf = buffer;
read_op->size = *length;
read_op->flags = flags;
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous check
* in multithreaded app. If we add bad handle to the set it will
* corrupt the ioqueue set. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
<API key>(&key->read_list, read_op);
ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
<API key>(key);
return PJ_EPENDING;
}
/*
* pj_ioqueue_recvfrom()
*
* Start asynchronous recvfrom() from the socket.
*/
PJ_DEF(pj_status_t) pj_ioqueue_recvfrom( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
void *buffer,
pj_ssize_t *length,
unsigned flags,
pj_sockaddr_t *addr,
int *addrlen)
{
struct read_operation *read_op;
PJ_ASSERT_RETURN(key && op_key && buffer && length, PJ_EINVAL);
PJ_CHECK_STACK();
/* Check if key is closing. */
if (IS_CLOSING(key))
return PJ_ECANCELLED;
read_op = (struct read_operation*)op_key;
read_op->op = PJ_IOQUEUE_OP_NONE;
/* Try to see if there's data immediately available.
*/
if ((flags & <API key>) == 0) {
pj_status_t status;
pj_ssize_t size;
size = *length;
status = pj_sock_recvfrom(key->fd, buffer, &size, flags,
addr, addrlen);
if (status == PJ_SUCCESS) {
/* Yes! Data is available! */
*length = size;
return PJ_SUCCESS;
} else {
/* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
* the error to caller.
*/
if (status != PJ_STATUS_FROM_OS(<API key>))
return status;
}
}
flags &= ~(<API key>);
/*
* No data is immediately available.
* Must schedule asynchronous operation to the ioqueue.
*/
read_op->op = <API key>;
read_op->buf = buffer;
read_op->size = *length;
read_op->flags = flags;
read_op->rmt_addr = addr;
read_op->rmt_addrlen = addrlen;
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous check
* in multithreaded app. If we add bad handle to the set it will
* corrupt the ioqueue set. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
<API key>(&key->read_list, read_op);
ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
<API key>(key);
return PJ_EPENDING;
}
/*
* pj_ioqueue_send()
*
* Start asynchronous send() to the descriptor.
*/
PJ_DEF(pj_status_t) pj_ioqueue_send( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
const void *data,
pj_ssize_t *length,
unsigned flags)
{
struct write_operation *write_op;
pj_status_t status;
unsigned retry;
pj_ssize_t sent;
PJ_ASSERT_RETURN(key && op_key && data && length, PJ_EINVAL);
PJ_CHECK_STACK();
/* Check if key is closing. */
if (IS_CLOSING(key))
return PJ_ECANCELLED;
/* We can not use <API key> for socket write. */
flags &= ~(<API key>);
/* Fast track:
* Try to send data immediately, only if there's no pending write!
* Note:
* We are speculating that the list is empty here without properly
* acquiring ioqueue's mutex first. This is intentional, to maximize
* performance via parallelism.
*
* This should be safe, because:
* - by convention, we require caller to make sure that the
* key is not unregistered while other threads are invoking
* an operation on the same key.
* - pj_list_empty() is safe to be invoked by multiple threads,
* even when other threads are modifying the list.
*/
if (pj_list_empty(&key->write_list)) {
/*
* See if data can be sent immediately.
*/
sent = *length;
status = pj_sock_send(key->fd, data, &sent, flags);
if (status == PJ_SUCCESS) {
/* Success! */
*length = sent;
return PJ_SUCCESS;
} else {
/* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
* the error to caller.
*/
if (status != PJ_STATUS_FROM_OS(<API key>)) {
return status;
}
}
}
/*
* Schedule asynchronous send.
*/
write_op = (struct write_operation*)op_key;
/* Spin if write_op has pending operation */
for (retry=0; write_op->op != 0 && retry<PENDING_RETRY; ++retry)
pj_thread_sleep(0);
/* Last chance */
if (write_op->op) {
/* Unable to send packet because there is already pending write in the
* write_op. We could not put the operation into the write_op
* because write_op already contains a pending operation! And
* we could not send the packet directly with send() either,
* because that will break the order of the packet. So we can
* only return error here.
*
* This could happen for example in multithreads program,
* where polling is done by one thread, while other threads are doing
* the sending only. If the polling thread runs on lower priority
* than the sending thread, then it's possible that the pending
* write flag is not cleared in-time because clearing is only done
* during polling.
*
* Aplication should specify multiple write operation keys on
* situation like this.
*/
//pj_assert(!"ioqueue: there is pending operation on this key!");
return PJ_EBUSY;
}
write_op->op = PJ_IOQUEUE_OP_SEND;
write_op->buf = (char*)data;
write_op->size = *length;
write_op->written = 0;
write_op->flags = flags;
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous check
* in multithreaded app. If we add bad handle to the set it will
* corrupt the ioqueue set. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
<API key>(&key->write_list, write_op);
ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT);
<API key>(key);
return PJ_EPENDING;
}
/*
* pj_ioqueue_sendto()
*
* Start asynchronous write() to the descriptor.
*/
PJ_DEF(pj_status_t) pj_ioqueue_sendto( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
const void *data,
pj_ssize_t *length,
pj_uint32_t flags,
const pj_sockaddr_t *addr,
int addrlen)
{
struct write_operation *write_op;
unsigned retry;
pj_bool_t restart_retry = PJ_FALSE;
pj_status_t status;
pj_ssize_t sent;
PJ_ASSERT_RETURN(key && op_key && data && length, PJ_EINVAL);
PJ_CHECK_STACK();
#if defined(<API key>) && \
<API key>!=0
retry_on_restart:
#else
PJ_UNUSED_ARG(restart_retry);
#endif
/* Check if key is closing. */
if (IS_CLOSING(key))
return PJ_ECANCELLED;
/* We can not use <API key> for socket write */
flags &= ~(<API key>);
/* Fast track:
* Try to send data immediately, only if there's no pending write!
* Note:
* We are speculating that the list is empty here without properly
* acquiring ioqueue's mutex first. This is intentional, to maximize
* performance via parallelism.
*
* This should be safe, because:
* - by convention, we require caller to make sure that the
* key is not unregistered while other threads are invoking
* an operation on the same key.
* - pj_list_empty() is safe to be invoked by multiple threads,
* even when other threads are modifying the list.
*/
if (pj_list_empty(&key->write_list)) {
/*
* See if data can be sent immediately.
*/
sent = *length;
status = pj_sock_sendto(key->fd, data, &sent, flags, addr, addrlen);
if (status == PJ_SUCCESS) {
/* Success! */
*length = sent;
return PJ_SUCCESS;
} else {
/* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
* the error to caller.
*/
if (status != PJ_STATUS_FROM_OS(<API key>)) {
#if defined(<API key>) && \
<API key>!=0
/* Special treatment for dead UDP sockets here, see ticket #1107 */
if (status==PJ_STATUS_FROM_OS(EPIPE) && !IS_CLOSING(key) &&
key->fd_type==pj_SOCK_DGRAM() && !restart_retry)
{
PJ_PERROR(4,(THIS_FILE, status,
"Send error for socket %d, retrying",
key->fd));
replace_udp_sock(key);
restart_retry = PJ_TRUE;
goto retry_on_restart;
}
#endif
return status;
}
}
}
/*
* Check that address storage can hold the address parameter.
*/
PJ_ASSERT_RETURN(addrlen <= (int)sizeof(pj_sockaddr_in), PJ_EBUG);
/*
* Schedule asynchronous send.
*/
write_op = (struct write_operation*)op_key;
/* Spin if write_op has pending operation */
for (retry=0; write_op->op != 0 && retry<PENDING_RETRY; ++retry)
pj_thread_sleep(0);
/* Last chance */
if (write_op->op) {
/* Unable to send packet because there is already pending write on the
* write_op. We could not put the operation into the write_op
* because write_op already contains a pending operation! And
* we could not send the packet directly with sendto() either,
* because that will break the order of the packet. So we can
* only return error here.
*
* This could happen for example in multithreads program,
* where polling is done by one thread, while other threads are doing
* the sending only. If the polling thread runs on lower priority
* than the sending thread, then it's possible that the pending
* write flag is not cleared in-time because clearing is only done
* during polling.
*
* Aplication should specify multiple write operation keys on
* situation like this.
*/
//pj_assert(!"ioqueue: there is pending operation on this key!");
return PJ_EBUSY;
}
write_op->op = <API key>;
write_op->buf = (char*)data;
write_op->size = *length;
write_op->written = 0;
write_op->flags = flags;
pj_memcpy(&write_op->rmt_addr, addr, addrlen);
write_op->rmt_addrlen = addrlen;
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous check
* in multithreaded app. If we add bad handle to the set it will
* corrupt the ioqueue set. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
<API key>(&key->write_list, write_op);
ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT);
<API key>(key);
return PJ_EPENDING;
}
#if PJ_HAS_TCP
/*
* Initiate overlapped accept() operation.
*/
PJ_DEF(pj_status_t) pj_ioqueue_accept( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
pj_sock_t *new_sock,
pj_sockaddr_t *local,
pj_sockaddr_t *remote,
int *addrlen)
{
struct accept_operation *accept_op;
pj_status_t status;
/* check parameters. All must be specified! */
PJ_ASSERT_RETURN(key && op_key && new_sock, PJ_EINVAL);
/* Check if key is closing. */
if (IS_CLOSING(key))
return PJ_ECANCELLED;
accept_op = (struct accept_operation*)op_key;
accept_op->op = PJ_IOQUEUE_OP_NONE;
/* Fast track:
* See if there's new connection available immediately.
*/
if (pj_list_empty(&key->accept_list)) {
status = pj_sock_accept(key->fd, new_sock, remote, addrlen);
if (status == PJ_SUCCESS) {
/* Yes! New connection is available! */
if (local && addrlen) {
status = pj_sock_getsockname(*new_sock, local, addrlen);
if (status != PJ_SUCCESS) {
pj_sock_close(*new_sock);
*new_sock = PJ_INVALID_SOCKET;
return status;
}
}
return PJ_SUCCESS;
} else {
/* If error is not EWOULDBLOCK (or EAGAIN on Linux), report
* the error to caller.
*/
if (status != PJ_STATUS_FROM_OS(<API key>)) {
return status;
}
}
}
/*
* No connection is available immediately.
* Schedule accept() operation to be completed when there is incoming
* connection available.
*/
accept_op->op = <API key>;
accept_op->accept_fd = new_sock;
accept_op->rmt_addr = remote;
accept_op->addrlen= addrlen;
accept_op->local_addr = local;
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous check
* in multithreaded app. If we add bad handle to the set it will
* corrupt the ioqueue set. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
<API key>(&key->accept_list, accept_op);
ioqueue_add_to_set(key->ioqueue, key, READABLE_EVENT);
<API key>(key);
return PJ_EPENDING;
}
/*
* Initiate overlapped connect() operation (well, it's non-blocking actually,
* since there's no overlapped version of connect()).
*/
PJ_DEF(pj_status_t) pj_ioqueue_connect( pj_ioqueue_key_t *key,
const pj_sockaddr_t *addr,
int addrlen )
{
pj_status_t status;
/* check parameters. All must be specified! */
PJ_ASSERT_RETURN(key && addr && addrlen, PJ_EINVAL);
/* Check if key is closing. */
if (IS_CLOSING(key))
return PJ_ECANCELLED;
/* Check if socket has not been marked for connecting */
if (key->connecting != 0)
return PJ_EPENDING;
status = pj_sock_connect(key->fd, addr, addrlen);
if (status == PJ_SUCCESS) {
/* Connected! */
return PJ_SUCCESS;
} else {
if (status == PJ_STATUS_FROM_OS(<API key>)) {
/* Pending! */
pj_ioqueue_lock_key(key);
/* Check again. Handle may have been closed after the previous
* check in multithreaded app. See #913
*/
if (IS_CLOSING(key)) {
<API key>(key);
return PJ_ECANCELLED;
}
key->connecting = PJ_TRUE;
ioqueue_add_to_set(key->ioqueue, key, WRITEABLE_EVENT);
ioqueue_add_to_set(key->ioqueue, key, EXCEPTION_EVENT);
<API key>(key);
return PJ_EPENDING;
} else {
/* Error! */
return status;
}
}
}
#endif /* PJ_HAS_TCP */
PJ_DEF(void) <API key>( pj_ioqueue_op_key_t *op_key,
pj_size_t size )
{
pj_bzero(op_key, size);
}
/*
* <API key>()
*/
PJ_DEF(pj_bool_t) <API key>( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key )
{
struct generic_operation *op_rec;
PJ_UNUSED_ARG(key);
op_rec = (struct generic_operation*)op_key;
return op_rec->op != 0;
}
/*
* <API key>()
*/
PJ_DEF(pj_status_t) <API key>( pj_ioqueue_key_t *key,
pj_ioqueue_op_key_t *op_key,
pj_ssize_t bytes_status )
{
struct generic_operation *op_rec;
/*
* Find the operation key in all pending operation list to
* really make sure that it's still there; then call the callback.
*/
pj_ioqueue_lock_key(key);
/* Find the operation in the pending read list. */
op_rec = (struct generic_operation*)key->read_list.next;
while (op_rec != (void*)&key->read_list) {
if (op_rec == (void*)op_key) {
pj_list_erase(op_rec);
op_rec->op = PJ_IOQUEUE_OP_NONE;
<API key>(key);
(*key->cb.on_read_complete)(key, op_key, bytes_status);
return PJ_SUCCESS;
}
op_rec = op_rec->next;
}
/* Find the operation in the pending write list. */
op_rec = (struct generic_operation*)key->write_list.next;
while (op_rec != (void*)&key->write_list) {
if (op_rec == (void*)op_key) {
pj_list_erase(op_rec);
op_rec->op = PJ_IOQUEUE_OP_NONE;
<API key>(key);
(*key->cb.on_write_complete)(key, op_key, bytes_status);
return PJ_SUCCESS;
}
op_rec = op_rec->next;
}
/* Find the operation in the pending accept list. */
op_rec = (struct generic_operation*)key->accept_list.next;
while (op_rec != (void*)&key->accept_list) {
if (op_rec == (void*)op_key) {
pj_list_erase(op_rec);
op_rec->op = PJ_IOQUEUE_OP_NONE;
<API key>(key);
(*key->cb.on_accept_complete)(key, op_key,
PJ_INVALID_SOCKET,
(pj_status_t)bytes_status);
return PJ_SUCCESS;
}
op_rec = op_rec->next;
}
<API key>(key);
return PJ_EINVALIDOP;
}
PJ_DEF(pj_status_t) <API key>( pj_ioqueue_t *ioqueue,
pj_bool_t allow)
{
PJ_ASSERT_RETURN(ioqueue != NULL, PJ_EINVAL);
ioqueue->default_concurrency = allow;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) <API key>(pj_ioqueue_key_t *key,
pj_bool_t allow)
{
PJ_ASSERT_RETURN(key, PJ_EINVAL);
/* <API key> must be enabled if concurrency is
* disabled.
*/
PJ_ASSERT_RETURN(allow || <API key>, PJ_EINVAL);
key->allow_concurrent = allow;
return PJ_SUCCESS;
}
PJ_DEF(pj_status_t) pj_ioqueue_lock_key(pj_ioqueue_key_t *key)
{
if (key->grp_lock)
return pj_grp_lock_acquire(key->grp_lock);
else
return pj_lock_acquire(key->lock);
}
PJ_DEF(pj_status_t) <API key>(pj_ioqueue_key_t *key)
{
if (key->grp_lock)
return pj_grp_lock_release(key->grp_lock);
else
return pj_lock_release(key->lock);
} |
#ifndef <API key>
#define <API key>
#include "ci/ciInstance.hpp"
#include "ci/ciUtilities.hpp"
#include "classfile/javaClasses.hpp"
// ciMethodType
// The class represents a java.lang.invoke.MethodType object.
class ciMethodType : public ciInstance {
private:
ciType* class_to_citype(oop klass_oop) const {
if (java_lang_Class::is_primitive(klass_oop)) {
BasicType bt = java_lang_Class::primitive_type(klass_oop);
return ciType::make(bt);
} else {
klassOop k = java_lang_Class::as_klassOop(klass_oop);
return CURRENT_ENV->get_object(k)->as_klass();
}
}
public:
ciMethodType(instanceHandle h_i) : ciInstance(h_i) {}
// What kind of ciObject is this?
bool is_method_type() const { return true; }
ciType* rtype() const {
GUARDED_VM_ENTRY(
oop rtype = <API key>::rtype(get_oop());
return class_to_citype(rtype);
)
}
int ptype_count() const {
GUARDED_VM_ENTRY(return <API key>::ptype_count(get_oop());)
}
int ptype_slot_count() const {
GUARDED_VM_ENTRY(return <API key>::ptype_slot_count(get_oop());)
}
ciType* ptype_at(int index) const {
GUARDED_VM_ENTRY(
oop ptype = <API key>::ptype(get_oop(), index);
return class_to_citype(ptype);
)
}
};
#endif // <API key> |
<?php
namespace Drupal\Core\Command;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Database\<API key>;
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\Extension\InfoParserDynamic;
use Drupal\Core\Site\Settings;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Installs a Drupal site for local testing/development.
*
* @internal
* This command makes no guarantee of an API for Drupal extensions.
*/
class InstallCommand extends Command {
/**
* The class loader.
*
* @var object
*/
protected $classLoader;
/**
* Constructs a new InstallCommand command.
*
* @param object $class_loader
* The class loader.
*/
public function __construct($class_loader) {
parent::__construct('install');
$this->classLoader = $class_loader;
}
/**
* {@inheritdoc}
*/
protected function configure() {
$this->setName('install')
->setDescription('Installs a Drupal demo site. This is not meant for production and might be too simple for custom development. It is a quick and easy way to get Drupal running.')
->addArgument('install-profile', InputArgument::OPTIONAL, 'Install profile to install the site in.')
->addOption('langcode', NULL, InputOption::VALUE_OPTIONAL, 'The language to install the site in.', 'en')
->addOption('site-name', NULL, InputOption::VALUE_OPTIONAL, 'Set the site name.', 'Drupal')
->addUsage('demo_umami --langcode fr')
->addUsage('standard --site-name QuickInstall');
parent::configure();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output) {
$io = new SymfonyStyle($input, $output);
if (!extension_loaded('pdo_sqlite')) {
$io->getErrorStyle()->error('You must have the pdo_sqlite PHP extension installed. See core/INSTALL.sqlite.txt for instructions.');
return 1;
}
// Change the directory to the Drupal root.
chdir(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
// Check whether there is already an installation.
if ($this->isDrupalInstalled()) {
// Do not fail if the site is already installed so this command can be
// chained with ServerCommand.
$output->writeln('<info>Drupal is already installed.</info> If you want to reinstall, remove sites/default/files and sites/default/settings.php.');
return 0;
}
$install_profile = $input->getArgument('install-profile');
if ($install_profile && !$this->validateProfile($install_profile, $io)) {
return 1;
}
if (!$install_profile) {
$install_profile = $this->selectProfile($io);
}
return $this->install($this->classLoader, $io, $install_profile, $input->getOption('langcode'), $this->getSitePath(), $input->getOption('site-name'));
}
/**
* Returns whether there is already an existing Drupal installation.
*
* @return bool
*/
protected function isDrupalInstalled() {
try {
$kernel = new DrupalKernel('prod', $this->classLoader, FALSE);
$kernel::bootEnvironment();
$kernel->setSitePath($this->getSitePath());
Settings::initialize($kernel->getAppRoot(), $kernel->getSitePath(), $this->classLoader);
$kernel->boot();
}
catch (<API key> $e) {
return FALSE;
}
return !empty(Database::getConnectionInfo());
}
/**
* Installs Drupal with specified installation profile.
*
* @param object $class_loader
* The class loader.
* @param \Symfony\Component\Console\Style\SymfonyStyle $io
* The Symfony output decorator.
* @param string $profile
* The installation profile to use.
* @param string $langcode
* The language to install the site in.
* @param string $site_path
* The path to install the site to, like 'sites/default'.
* @param string $site_name
* The site name.
*
* @throws \Exception
* Thrown when failing to create the $site_path directory or settings.php.
*/
protected function install($class_loader, SymfonyStyle $io, $profile, $langcode, $site_path, $site_name) {
$password = Crypt::randomBytesBase64(12);
$parameters = [
'interactive' => FALSE,
'site_path' => $site_path,
'parameters' => [
'profile' => $profile,
'langcode' => $langcode,
],
'forms' => [
'<API key>' => [
'driver' => 'sqlite',
'sqlite' => [
'database' => $site_path . '/files/.sqlite',
],
],
'<API key>' => [
'site_name' => $site_name,
'site_mail' => 'drupal@localhost',
'account' => [
'name' => 'admin',
'mail' => 'admin@localhost',
'pass' => [
'pass1' => $password,
'pass2' => $password,
],
],
'<API key>' => TRUE,
// <API key>() requires NULL instead of FALSE values
// for programmatic form submissions to disable a checkbox.
'<API key>' => NULL,
],
],
];
// Create the directory and settings.php if not there so that the installer
// works.
if (!is_dir($site_path)) {
if ($io->isVerbose()) {
$io->writeln("Creating directory: $site_path");
}
if (!mkdir($site_path, 0775)) {
throw new \RuntimeException("Failed to create directory $site_path");
}
}
if (!file_exists("{$site_path}/settings.php")) {
if ($io->isVerbose()) {
$io->writeln("Creating file: {$site_path}/settings.php");
}
if (!copy('sites/default/default.settings.php', "{$site_path}/settings.php")) {
throw new \RuntimeException("Copying sites/default/default.settings.php to {$site_path}/settings.php failed.");
}
}
require_once 'core/includes/install.core.inc';
$progress_bar = $io->createProgressBar();
install_drupal($class_loader, $parameters, function ($install_state) use ($progress_bar) {
static $started = FALSE;
if (!$started) {
$started = TRUE;
// We've already done 1.
$progress_bar->setFormat("%current%/%max% [%bar%]\n%message%\n");
$progress_bar->setMessage(t('Installing @drupal', ['@drupal' => <API key>()]));
$tasks = install_tasks($install_state);
$progress_bar->start(count($tasks) + 1);
}
$tasks_to_perform = <API key>($install_state);
$task = current($tasks_to_perform);
if (isset($task['display_name'])) {
$progress_bar->setMessage($task['display_name']);
}
$progress_bar->advance();
});
$success_message = t('Congratulations, you installed @drupal!', [
'@drupal' => <API key>(),
'@name' => 'admin',
'@pass' => $password,
], ['langcode' => $langcode]);
$progress_bar->setMessage('<info>' . $success_message . '</info>');
$progress_bar->display();
$progress_bar->finish();
$io->writeln('<info>Username:</info> admin');
$io->writeln("<info>Password:</info> $password");
}
/**
* Gets the site path.
*
* Defaults to 'sites/default'. For testing purposes this can be overridden
* using the <API key> environment variable.
*
* @return string
* The site path to use.
*/
protected function getSitePath() {
return getenv('<API key>') ?: 'sites/default';
}
/**
* Selects the install profile to use.
*
* @param \Symfony\Component\Console\Style\SymfonyStyle $io
* Symfony style output decorator.
*
* @return string
* The selected install profile.
*
* @see <API key>()
* @see \Drupal\Core\Installer\Form\SelectProfileForm
*/
protected function selectProfile(SymfonyStyle $io) {
$profiles = $this->getProfiles();
// If there is a distribution there will be only one profile.
if (count($profiles) == 1) {
return key($profiles);
}
// Display alphabetically by human-readable name, but always put the core
// profiles first (if they are present in the filesystem).
natcasesort($profiles);
if (isset($profiles['minimal'])) {
// If the expert ("Minimal") core profile is present, put it in front of
// any non-core profiles rather than including it with them
// alphabetically, since the other profiles might be intended to group
// together in a particular way.
$profiles = ['minimal' => $profiles['minimal']] + $profiles;
}
if (isset($profiles['standard'])) {
// If the default ("Standard") core profile is present, put it at the very
// top of the list. This profile will have its radio button pre-selected,
// so we want it to always appear at the top.
$profiles = ['standard' => $profiles['standard']] + $profiles;
}
reset($profiles);
return $io->choice('Select an installation profile', $profiles, current($profiles));
}
/**
* Validates a user provided install profile.
*
* @param string $install_profile
* Install profile to validate.
* @param \Symfony\Component\Console\Style\SymfonyStyle $io
* Symfony style output decorator.
*
* @return bool
* TRUE if the profile is valid, FALSE if not.
*/
protected function validateProfile($install_profile, SymfonyStyle $io) {
// Allow people to install hidden and non-distribution profiles if they
// supply the argument.
$profiles = $this->getProfiles(TRUE, FALSE);
if (!isset($profiles[$install_profile])) {
$error_msg = sprintf("'%s' is not a valid install profile.", $install_profile);
$alternatives = [];
foreach (array_keys($profiles) as $profile_name) {
$lev = levenshtein($install_profile, $profile_name);
if ($lev <= strlen($profile_name) / 4 || FALSE !== strpos($profile_name, $install_profile)) {
$alternatives[] = $profile_name;
}
}
if (!empty($alternatives)) {
$error_msg .= sprintf(" Did you mean '%s'?", implode("' or '", $alternatives));
}
$io->getErrorStyle()->error($error_msg);
return FALSE;
}
return TRUE;
}
/**
* Gets a list of profiles.
*
* @param bool $include_hidden
* (optional) Whether to include hidden profiles. Defaults to FALSE.
* @param bool $<API key>
* (optional) Whether to only return the first distribution found.
*
* @return string[]
* An array of profile descriptions keyed by the profile machine name.
*/
protected function getProfiles($include_hidden = FALSE, $<API key> = TRUE) {
// Build a list of all available profiles.
$listing = new ExtensionDiscovery(getcwd(), FALSE);
$listing-><API key>([]);
$profiles = [];
$info_parser = new InfoParserDynamic();
foreach ($listing->scan('profile') as $profile) {
$details = $info_parser->parse($profile->getPathname());
// Don't show hidden profiles.
if (!$include_hidden && !empty($details['hidden'])) {
continue;
}
// Determine the name of the profile; default to the internal name if none
// is specified.
$name = isset($details['name']) ? $details['name'] : $profile->getName();
$description = isset($details['description']) ? $details['description'] : $name;
$profiles[$profile->getName()] = $description;
if ($<API key> && !empty($details['distribution'])) {
return [$profile->getName() => $description];
}
}
return $profiles;
}
} |
#ifndef CLICK_EXTRADECAP_HH
#define CLICK_EXTRADECAP_HH
#include <click/element.hh>
#include <clicknet/ether.h>
CLICK_DECLS
/*
=c
ExtraDecap()
=s Wifi
Pulls the click_wifi_extra header from a packet and stores it in Packet::anno()
=d
Removes the extra header and copies to to Packet->anno(). This contains
informatino such as rssi, noise, bitrate, etc.
=a ExtraEncap
*/
class ExtraDecap : public Element { public:
ExtraDecap() CLICK_COLD;
~ExtraDecap() CLICK_COLD;
const char *class_name() const { return "ExtraDecap"; }
const char *port_count() const { return PORTS_1_1; }
const char *processing() const { return AGNOSTIC; }
int configure(Vector<String> &, ErrorHandler *) CLICK_COLD;
bool <API key>() const { return true; }
Packet *simple_action(Packet *);
void add_handlers() CLICK_COLD;
bool _debug;
private:
};
CLICK_ENDDECLS
#endif |
package com.redhat.rhn.manager.kickstart;
import com.redhat.rhn.common.validator.ValidatorError;
import com.redhat.rhn.domain.kickstart.KickstartData;
import com.redhat.rhn.domain.user.User;
import org.cobbler.Profile;
/**
* <API key> - class to clone a KickstartData object and its children
* @version $Rev$
*/
public class <API key> extends <API key> {
private KickstartData clonedKickstart;
private String newLabel;
/**
* Construct a <API key>
* @param ksidIn id of KickstartData that wants to be cloned
* @param userIn user doing the cloning
* @param newLabelIn to gived to cloned ks.
*/
public <API key>(Long ksidIn, User userIn, String newLabelIn) {
super(ksidIn, userIn);
this.newLabel = newLabelIn;
}
/**
* Execute the clone or copy of the KickstartData associated with this command.
*
* Call getClonedKickstart() to get the new object created.
*
* @return ValidatorError if there was a problem
*/
public ValidatorError store() {
if (clonedKickstart != null) {
throw new <API key>(
"Can't call store twice on this Command");
}
// we keep the name and the label the same.
clonedKickstart = this.ksdata.deepCopy(user, newLabel);
<API key> helperCmd = new <API key>(user);
helperCmd.store(clonedKickstart);
Profile original = ksdata.getCobblerObject(user);
Profile cloned = clonedKickstart.getCobblerObject(user);
cloned.setKsMeta(original.getKsMeta());
cloned.setVirtRam(original.getVirtRam());
cloned.setVirtCpus(original.getVirtCpus());
cloned.setVirtFileSize(original.getVirtFileSize());
cloned.setVirtBridge(original.getVirtBridge());
cloned.setVirtPath(original.getVirtBridge());
cloned.setKernelOptions(original.getKernelOptions());
cloned.<API key>(original.<API key>());
cloned.save();
return null;
}
/**
* @return the clonedKickstart
*/
public KickstartData getClonedKickstart() {
return clonedKickstart;
}
/**
* @return the newLabel
*/
public String getNewLabel() {
return newLabel;
}
} |
package freenet.client.async;
import freenet.client.InsertException;
import freenet.client.Metadata;
/** Callback interface for a <API key>. Usually implemented by SplitFileInserter,
* but can be used for unit tests etc too. Hence SplitFileInserter doesn't need to know much about
* the rest of the client layer.
* @author toad
*/
public interface <API key> {
/** All the segments (and possibly cross-segments) have been encoded. */
void onFinishedEncode();
/** Called after finishing encoding the check blocks and block keys for another segment.
* The callback might need to reschedule as there are more blocks available to insert.
* When this has been called once for each segment we will call onHasKeys(). */
void encodingProgress();
/** Called when all segments have been encoded. So we have all the check blocks and have a CHK
* for every block. The callback must decide whether to complete / start the next insert level,
* or whether to wait for all the blocks to insert. */
void onHasKeys();
/** Called when the whole insert has succeeded, i.e. when all blocks have been inserted. */
void onSucceeded(Metadata metadata);
/** Called if the insert fails. All encodes will have finished by the time this is called. */
void onFailed(InsertException e);
/** Called when a block is inserted successfully */
void onInsertedBlock();
/** Called when a block becomes fetchable (unless because of an encode, in which case we only
* call encodingProgress() ) */
void clearCooldown();
/** Get request priority class for FEC jobs etc */
short getPriorityClass();
} |
/*
* Ring initialization rules:
* 1. Each segment is initialized to zero, except for link TRBs.
* 2. Ring cycle state = 0. This represents Producer Cycle State (PCS) or
* Consumer Cycle State (CCS), depending on ring function.
* 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment.
*
* Ring behavior rules:
* 1. A ring is empty if enqueue == dequeue. This means there will always be at
* least one free TRB in the ring. This is useful if you want to turn that
* into a link TRB and expand the ring.
* 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a
* link TRB, then load the pointer with the address in the link TRB. If the
* link TRB had its toggle bit set, you may need to update the ring cycle
* state (see cycle bit rules). You may have to do this multiple times
* until you reach a non-link TRB.
* 3. A ring is full if enqueue++ (for the definition of increment above)
* equals the dequeue pointer.
*
* Cycle bit rules:
* 1. When a consumer increments a dequeue pointer and encounters a toggle bit
* in a link TRB, it must toggle the ring cycle state.
* 2. When a producer increments an enqueue pointer and encounters a toggle bit
* in a link TRB, it must toggle the ring cycle state.
*
* Producer rules:
* 1. Check if ring is full before you enqueue.
* 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing.
* Update enqueue pointer between each write (which may update the ring
* cycle state).
* 3. Notify consumer. If SW is producer, it rings the doorbell for command
* and endpoint rings. If HC is the producer for the event ring,
* and it generates an interrupt according to interrupt modulation rules.
*
* Consumer rules:
* 1. Check if TRB belongs to you. If the cycle bit == your ring cycle state,
* the TRB is owned by the consumer.
* 2. Update dequeue pointer (which may update the ring cycle state) and
* continue processing TRBs until you reach a TRB which is not owned by you.
* 3. Notify the producer. SW is the consumer for the event ring, and it
* updates event ring dequeue pointer. HC is the consumer for the command and
* endpoint rings; it generates events on the event ring for these.
*/
#include <linux/scatterlist.h>
#include <linux/slab.h>
#include "xhci.h"
#include "mtk-test-lib.h"
#include <linux/dma-mapping.h>
/*
* Returns zero if the TRB isn't in this segment, otherwise it returns the DMA
* address of the TRB.
*/
dma_addr_t <API key>(struct xhci_segment *seg,
union xhci_trb *trb)
{
unsigned long segment_offset;
if (!seg || !trb || trb < seg->trbs)
return 0;
/* offset in TRBs */
segment_offset = trb - seg->trbs;
if (segment_offset > TRBS_PER_SEGMENT)
return 0;
return seg->dma + (segment_offset * sizeof(*trb));
}
/* Does this link TRB point to the first segment in a ring,
* or was the previous TRB the last TRB on the last segment in the ERST?
*/
static inline bool <API key>(struct xhci_hcd *xhci, struct xhci_ring *ring,
struct xhci_segment *seg, union xhci_trb *trb)
{
if (ring == xhci->event_ring)
return (trb == &seg->trbs[TRBS_PER_SEGMENT]) &&
(seg->next == xhci->event_ring->first_seg);
else
return trb->link.control & LINK_TOGGLE;
}
/* Is this TRB a link TRB or was the last TRB the last TRB in this event ring
* segment? I.e. would the updated event TRB pointer step off the end of the
* event seg?
*/
static inline int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
struct xhci_segment *seg, union xhci_trb *trb)
{
if (ring == xhci->event_ring)
return trb == &seg->trbs[TRBS_PER_SEGMENT];
else
return (trb->link.control & TRB_TYPE_BITMASK) == TRB_TYPE(TRB_LINK);
}
static inline int enqueue_is_link_trb(struct xhci_ring *ring)
{
struct xhci_link_trb *link = &ring->enqueue->link;
return ((link->control & TRB_TYPE_BITMASK) == TRB_TYPE(TRB_LINK));
}
/* Updates trb to point to the next TRB in the ring, and updates seg if the next
* TRB is in a new segment. This does not skip over link TRBs, and it does not
* effect the ring dequeue or enqueue pointers.
*/
static void next_trb(struct xhci_hcd *xhci,
struct xhci_ring *ring,
struct xhci_segment **seg,
union xhci_trb **trb)
{
if (last_trb(xhci, ring, *seg, *trb)) {
*seg = (*seg)->next;
*trb = ((*seg)->trbs);
} else {
(*trb)++;
}
}
/*
* See Cycle bit rules. SW is the consumer for the event ring only.
* Don't make a ring full of link TRBs. That would be dumb and this would loop.
*/
void mtktest_inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool consumer)
{
union xhci_trb *next = ++(ring->dequeue);
unsigned long long addr;
ring->deq_updates++;
/* Update the dequeue pointer further if that was a link TRB or we're at
* the end of an event ring segment (which doesn't have link TRBS)
*/
while (last_trb(xhci, ring, ring->deq_seg, next)) {
if (consumer && <API key>(xhci, ring, ring->deq_seg, next)) {
ring->cycle_state = (ring->cycle_state ? 0 : 1);
if (!in_interrupt())
xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
ring,
(unsigned int) ring->cycle_state);
}
ring->deq_seg = ring->deq_seg->next;
ring->dequeue = ring->deq_seg->trbs;
next = ring->dequeue;
}
addr = (unsigned long long) <API key>(ring->deq_seg, ring->dequeue);
if (ring == xhci->event_ring)
xhci_dbg(xhci, "Event ring deq = 0x%llx (DMA)\n", addr);
else if (ring == xhci->cmd_ring)
xhci_dbg(xhci, "Command ring deq = 0x%llx (DMA)\n", addr);
else
xhci_dbg(xhci, "Ring deq = 0x%llx (DMA)\n", addr);
}
/*
* See Cycle bit rules. SW is the consumer for the event ring only.
* Don't make a ring full of link TRBs. That would be dumb and this would loop.
*
* If we've just enqueued a TRB that is in the middle of a TD (meaning the
* chain bit is set), then set the chain bit in all the following link TRBs.
* If we've enqueued the last TRB in a TD, make sure the following link TRBs
* have their chain bit cleared (so that each Link TRB is a separate TD).
*
* Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit
* set, but other sections talk about dealing with the chain bit set. This was
* fixed in the 0.96 specification errata, but we have to assume that all 0.95
* xHCI hardware can't handle the chain bit being cleared on a link TRB.
*
* @more_trbs_coming: Will you enqueue more TRBs before calling
* prepare_transfer()?
*/
static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring,
bool consumer, bool more_trbs_coming)
{
u32 chain;
union xhci_trb *next;
unsigned long long addr;
chain = ring->enqueue->generic.field[3] & TRB_CHAIN;
next = ++(ring->enqueue);
ring->enq_updates++;
/* Update the dequeue pointer further if that was a link TRB or we're at
* the end of an event ring segment (which doesn't have link TRBS)
*/
while (last_trb(xhci, ring, ring->enq_seg, next)) {
if (!consumer) {
if (ring != xhci->event_ring) {
/*
* If the caller doesn't plan on enqueueing more
* TDs before ringing the doorbell, then we
* don't want to give the link TRB to the
* hardware just yet. We'll give the link TRB
* back in prepare_ring() just before we enqueue
* the TD at the top of the ring.
*/
if (!chain && !more_trbs_coming)
break;
/* If we're not dealing with 0.95 hardware,
* carry over the chain bit of the previous TRB
* (which may mean the chain bit is cleared).
*/
if (!xhci_link_trb_quirk(xhci)) {
next->link.control &= ~TRB_CHAIN;
next->link.control |= chain;
}
/* Give this link TRB to the hardware */
wmb();
next->link.control ^= TRB_CYCLE;
}
/* Toggle the cycle bit after the last ring segment. */
if (<API key>(xhci, ring, ring->enq_seg, next)) {
ring->cycle_state = (ring->cycle_state ? 0 : 1);
if (!in_interrupt())
xhci_dbg(xhci, "Toggle cycle state for ring %p = %i\n",
ring,
(unsigned int) ring->cycle_state);
}
}
ring->enq_seg = ring->enq_seg->next;
ring->enqueue = ring->enq_seg->trbs;
next = ring->enqueue;
}
addr = (unsigned long long) <API key>(ring->enq_seg, ring->enqueue);
if (ring == xhci->event_ring)
xhci_dbg(xhci, "Event ring enq = 0x%p, 0x%llx (DMA)\n", ring->enqueue, addr);
else if (ring == xhci->cmd_ring)
xhci_dbg(xhci, "Command ring enq = 0x%p, 0x%llx (DMA)\n", ring->enqueue, addr);
else
xhci_dbg(xhci, "Ring enq = 0x%p 0x%llx (DMA)\n", ring->enqueue, addr);
}
/*
* Check to see if there's room to enqueue num_trbs on the ring. See rules
* above.
* FIXME: this would be simpler and faster if we just kept track of the number
* of free TRBs in a ring.
*/
static int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring,
unsigned int num_trbs)
{
int i;
union xhci_trb *enq = ring->enqueue;
struct xhci_segment *enq_seg = ring->enq_seg;
struct xhci_segment *cur_seg;
unsigned int left_on_ring;
/* If we are currently pointing to a link TRB, advance the
* enqueue pointer before checking for space */
while (last_trb(xhci, ring, enq_seg, enq)) {
enq_seg = enq_seg->next;
enq = enq_seg->trbs;
}
/* Check if ring is empty */
if (enq == ring->dequeue) {
/* Can't use link trbs */
left_on_ring = TRBS_PER_SEGMENT - 1;
for (cur_seg = enq_seg->next; cur_seg != enq_seg;
cur_seg = cur_seg->next)
left_on_ring += TRBS_PER_SEGMENT - 1;
/* Always need one TRB free in the ring. */
left_on_ring -= 1;
if (num_trbs > left_on_ring) {
xhci_warn(xhci, "Not enough room on ring; "
"need %u TRBs, %u TRBs left\n",
num_trbs, left_on_ring);
return 0;
}
return 1;
}
/* Make sure there's an extra empty TRB available */
for (i = 0; i <= num_trbs; ++i) {
if (enq == ring->dequeue)
return 0;
enq++;
while (last_trb(xhci, ring, enq_seg, enq)) {
enq_seg = enq_seg->next;
enq = enq_seg->trbs;
}
}
return 1;
}
void <API key>(struct xhci_hcd *xhci)
{
u64 temp;
dma_addr_t deq;
deq = <API key>(xhci->event_ring->deq_seg,
xhci->event_ring->dequeue);
if (deq == 0 && !in_interrupt())
xhci_warn(xhci, "WARN something wrong with SW event ring "
"dequeue ptr.\n");
/* Update HC event ring dequeue pointer */
temp = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue);
temp &= ERST_PTR_MASK;
/* Don't clear the EHB bit (which is RW1C) because
* there might be more events to service.
*/
temp &= ~ERST_EHB;
xhci_dbg(xhci, "// Write event ring dequeue pointer, preserving EHB bit\n");
xhci_write_64(xhci, ((u64) deq & (u64) ~ERST_PTR_MASK) | temp,
&xhci->ir_set->erst_dequeue);
}
/* Ring the host controller doorbell after placing a command on the ring */
void <API key>(struct xhci_hcd *xhci)
{
u32 temp;
xhci_dbg(xhci, "Ding dong!\n");
temp = xhci_readl(xhci, &xhci->dba->doorbell[0]) & DB_MASK;
xhci_writel(xhci, temp | DB_TARGET_HOST, &xhci->dba->doorbell[0]);
#if 0
/* Flush PCI posted writes */
xhci_readl(xhci, &xhci->dba->doorbell[0]);
#endif
}
static void ring_ep_doorbell(struct xhci_hcd *xhci,
unsigned int slot_id,
unsigned int ep_index,
unsigned int stream_id)
{
struct xhci_virt_ep *ep;
unsigned int ep_state;
u32 field;
__u32 __iomem *db_addr = &xhci->dba->doorbell[slot_id];
ep = &xhci->devs[slot_id]->eps[ep_index];
ep_state = ep->ep_state;
/* Don't ring the doorbell for this endpoint if there are pending
* cancellations because the we don't want to interrupt processing.
* We don't want to restart any stream rings if there's a set dequeue
* pointer command pending because the device can choose to start any
* stream once the endpoint is on the HW schedule.
* FIXME - check all the stream rings for pending cancellations.
*/
if (!(ep_state & EP_HALT_PENDING) && !(ep_state & SET_DEQ_PENDING)
&& !(ep_state & EP_HALTED)) {
field = xhci_readl(xhci, db_addr) & DB_MASK;
field |= EPI_TO_DB(ep_index) | STREAM_ID_TO_DB(stream_id);
xhci_writel(xhci, field, db_addr);
}
}
/* Ring the doorbell for any rings with pending URBs */
static void <API key>(struct xhci_hcd *xhci,
unsigned int slot_id,
unsigned int ep_index)
{
unsigned int stream_id;
struct xhci_virt_ep *ep;
ep = &xhci->devs[slot_id]->eps[ep_index];
/* A ring has pending URBs if its TD list is not empty */
if (!(ep->ep_state & EP_HAS_STREAMS)) {
if (!(list_empty(&ep->ring->td_list)))
ring_ep_doorbell(xhci, slot_id, ep_index, 0);
return;
}
for (stream_id = 1; stream_id < ep->stream_info->num_streams;
stream_id++) {
struct xhci_stream_info *stream_info = ep->stream_info;
if (!list_empty(&stream_info->stream_rings[stream_id]->td_list))
ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
}
}
/*
* Find the segment that trb is in. Start searching in start_seg.
* If we must move past a segment that has a link TRB with a toggle cycle state
* bit set, then we will toggle the value pointed at by cycle_state.
*/
static struct xhci_segment *find_trb_seg(
struct xhci_segment *start_seg,
union xhci_trb *trb, int *cycle_state)
{
struct xhci_segment *cur_seg = start_seg;
struct xhci_generic_trb *generic_trb;
while (cur_seg->trbs > trb ||
&cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) {
generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic;
if ((generic_trb->field[3] & TRB_TYPE_BITMASK) ==
TRB_TYPE(TRB_LINK) &&
(generic_trb->field[3] & LINK_TOGGLE))
*cycle_state = ~(*cycle_state) & 0x1;
cur_seg = cur_seg->next;
if (cur_seg == start_seg)
/* Looped over the entire list. Oops! */
return NULL;
}
return cur_seg;
}
/*
* Move the xHC's endpoint ring dequeue pointer past cur_td.
* Record the new state of the xHC's endpoint ring dequeue segment,
* dequeue pointer, and new consumer cycle state in state.
* Update our internal representation of the ring's dequeue pointer.
*
* We do this in three jumps:
* - First we update our new ring state to be the same as when the xHC stopped.
* - Then we traverse the ring to find the segment that contains
* the last TRB in the TD. We toggle the xHC's new cycle state when we pass
* any link TRBs with the toggle cycle bit set.
* - Finally we move the dequeue state one TRB further, toggling the cycle bit
* if we've moved it past a link TRB with the toggle cycle bit set.
*/
void <API key>(struct xhci_hcd *xhci,
unsigned int slot_id, unsigned int ep_index,
unsigned int stream_id, struct xhci_td *cur_td,
struct xhci_dequeue_state *state)
{
struct xhci_virt_device *dev = xhci->devs[slot_id];
struct xhci_ring *ep_ring;
struct xhci_generic_trb *trb;
struct xhci_ep_ctx *ep_ctx;
dma_addr_t addr;
ep_ring = <API key>(xhci, slot_id,
ep_index, stream_id);
if (!ep_ring) {
xhci_warn(xhci, "WARN can't find new dequeue state "
"for invalid stream ID %u.\n",
stream_id);
return;
}
state->new_cycle_state = 0;
xhci_dbg(xhci, "Finding segment containing stopped TRB.\n");
state->new_deq_seg = find_trb_seg(cur_td->start_seg,
dev->eps[ep_index].stopped_trb,
&state->new_cycle_state);
if (!state->new_deq_seg)
BUG();
/* Dig out the cycle state saved by the xHC during the stop ep cmd */
xhci_dbg(xhci, "Finding endpoint context\n");
ep_ctx = <API key>(xhci, dev->out_ctx, ep_index);
state->new_cycle_state = 0x1 & ep_ctx->deq;
state->new_deq_ptr = cur_td->last_trb;
xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n");
state->new_deq_seg = find_trb_seg(state->new_deq_seg,
state->new_deq_ptr,
&state->new_cycle_state);
if (!state->new_deq_seg)
BUG();
trb = &state->new_deq_ptr->generic;
if ((trb->field[3] & TRB_TYPE_BITMASK) == TRB_TYPE(TRB_LINK) &&
(trb->field[3] & LINK_TOGGLE))
state->new_cycle_state = ~(state->new_cycle_state) & 0x1;
next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr);
/* Don't update the ring cycle state for the producer (us). */
xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n",
state->new_deq_seg);
addr = <API key>(state->new_deq_seg, state->new_deq_ptr);
xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n",
(unsigned long long) addr);
xhci_dbg(xhci, "Setting dequeue pointer in internal ring state.\n");
ep_ring->dequeue = state->new_deq_ptr;
ep_ring->deq_seg = state->new_deq_seg;
}
static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
struct xhci_td *cur_td)
{
struct xhci_segment *cur_seg;
union xhci_trb *cur_trb;
for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb;
true;
next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
if ((cur_trb->generic.field[3] & TRB_TYPE_BITMASK) ==
TRB_TYPE(TRB_LINK)) {
/* Unchain any chained Link TRBs, but
* leave the pointers intact.
*/
cur_trb->generic.field[3] &= ~TRB_CHAIN;
xhci_dbg(xhci, "Cancel (unchain) link TRB\n");
xhci_dbg(xhci, "Address = %p (0x%llx dma); "
"in seg %p (0x%llx dma)\n",
cur_trb,
(unsigned long long)<API key>(cur_seg, cur_trb),
cur_seg,
(unsigned long long)cur_seg->dma);
} else {
cur_trb->generic.field[0] = 0;
cur_trb->generic.field[1] = 0;
cur_trb->generic.field[2] = 0;
/* Preserve only the cycle bit of this TRB */
cur_trb->generic.field[3] &= TRB_CYCLE;
cur_trb->generic.field[3] |= TRB_TYPE(TRB_TR_NOOP);
xhci_dbg(xhci, "Cancel TRB %p (0x%llx dma) "
"in seg %p (0x%llx dma)\n",
cur_trb,
(unsigned long long)<API key>(cur_seg, cur_trb),
cur_seg,
(unsigned long long)cur_seg->dma);
}
if (cur_trb == cur_td->last_trb)
break;
}
}
static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
unsigned int ep_index, unsigned int stream_id,
struct xhci_segment *deq_seg,
union xhci_trb *deq_ptr, u32 cycle_state);
void <API key>(struct xhci_hcd *xhci,
unsigned int slot_id, unsigned int ep_index,
unsigned int stream_id,
struct xhci_dequeue_state *deq_state)
{
struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), "
"new deq ptr = %p (0x%llx dma), new cycle = %u\n",
deq_state->new_deq_seg,
(unsigned long long)deq_state->new_deq_seg->dma,
deq_state->new_deq_ptr,
(unsigned long long)<API key>(deq_state->new_deq_seg, deq_state->new_deq_ptr),
deq_state->new_cycle_state);
queue_set_tr_deq(xhci, slot_id, ep_index, stream_id,
deq_state->new_deq_seg,
deq_state->new_deq_ptr,
(u32) deq_state->new_cycle_state);
/* Stop the TD queueing code from ringing the doorbell until
* this command completes. The HC won't set the dequeue pointer
* if the ring is running, and ringing the doorbell starts the
* ring running.
*/
ep->ep_state |= SET_DEQ_PENDING;
}
static inline void <API key>(struct xhci_hcd *xhci,
struct xhci_virt_ep *ep)
{
ep->ep_state &= ~EP_HALT_PENDING;
/* Can't del_timer_sync in interrupt, so we attempt to cancel. If the
* timer is running on another CPU, we don't decrement stop_cmds_pending
* (since we didn't successfully stop the watchdog timer).
*/
if (del_timer(&ep->stop_cmd_timer))
ep->stop_cmds_pending
}
/* Must be called with xhci->lock held in interrupt context */
static void <API key>(struct xhci_hcd *xhci,
struct xhci_td *cur_td, int status, char *adjective)
{
struct usb_hcd *hcd = xhci_to_hcd(xhci);
cur_td->urb->hcpriv = NULL;
<API key>(hcd, cur_td->urb);
xhci_dbg(xhci, "Giveback %s URB %p\n", adjective, cur_td->urb);
spin_unlock(&xhci->lock);
<API key>(hcd, cur_td->urb, status);
kfree(cur_td);
spin_lock(&xhci->lock);
xhci_dbg(xhci, "%s URB given back\n", adjective);
}
/*
* When we get a command completion for a Stop Endpoint Command, we need to
* unlink any cancelled TDs from the ring. There are two ways to do that:
*
* 1. If the HW was in the middle of processing the TD that needs to be
* cancelled, then we must move the ring's dequeue pointer past the last TRB
* in the TD with a Set Dequeue Pointer Command.
* 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain
* bit cleared) so that the HW will skip over them.
*/
static void <API key>(struct xhci_hcd *xhci,
union xhci_trb *trb)
{
unsigned int slot_id;
unsigned int ep_index;
struct xhci_ring *ep_ring;
struct xhci_virt_ep *ep;
struct list_head *entry;
struct xhci_td *cur_td = NULL;
struct xhci_td *last_unlinked_td;
struct xhci_dequeue_state deq_state;
memset(&deq_state, 0, sizeof(deq_state));
slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
ep = &xhci->devs[slot_id]->eps[ep_index];
if (list_empty(&ep->cancelled_td_list)) {
<API key>(xhci, ep);
<API key>(xhci, slot_id, ep_index);
return;
}
/* Fix up the ep ring first, so HW stops executing cancelled TDs.
* We have the xHCI lock, so nothing can modify this list until we drop
* it. We're also in the event handler, so we can't get re-interrupted
* if another Stop Endpoint command completes
*/
list_for_each(entry, &ep->cancelled_td_list) {
cur_td = list_entry(entry, struct xhci_td, cancelled_td_list);
xhci_dbg(xhci, "Cancelling TD starting at %p, 0x%llx (dma).\n",
cur_td->first_trb,
(unsigned long long)<API key>(cur_td->start_seg, cur_td->first_trb));
ep_ring = <API key>(xhci, cur_td->urb);
if (!ep_ring) {
/* This shouldn't happen unless a driver is mucking
* with the stream ID after submission. This will
* leave the TD on the hardware ring, and the hardware
* will try to execute it, and may access a buffer
* that has already been freed. In the best case, the
* hardware will execute it, and the event handler will
* ignore the completion event for that TD, since it was
* removed from the td_list for that endpoint. In
* short, don't muck with the stream ID after
* submission.
*/
xhci_warn(xhci, "WARN Cancelled URB %p "
"has invalid stream ID %u.\n",
cur_td->urb,
cur_td->urb->stream_id);
goto remove_finished_td;
}
/*
* If we stopped on the TD we need to cancel, then we have to
* move the xHC endpoint ring dequeue pointer past this TD.
*/
if (cur_td == ep->stopped_td)
<API key>(xhci, slot_id, ep_index,
cur_td->urb->stream_id,
cur_td, &deq_state);
else
td_to_noop(xhci, ep_ring, cur_td);
remove_finished_td:
/*
* The event handler won't see a completion for this TD anymore,
* so remove it from the endpoint ring's TD list. Keep it in
* the cancelled TD list for URB completion later.
*/
list_del(&cur_td->td_list);
}
last_unlinked_td = cur_td;
<API key>(xhci, ep);
/* If necessary, queue a Set Transfer Ring Dequeue Pointer command */
if (deq_state.new_deq_ptr && deq_state.new_deq_seg) {
<API key>(xhci,
slot_id, ep_index,
ep->stopped_td->urb->stream_id,
&deq_state);
<API key>(xhci);
} else {
/* Otherwise ring the doorbell(s) to restart queued transfers */
<API key>(xhci, slot_id, ep_index);
}
ep->stopped_td = NULL;
ep->stopped_trb = NULL;
/*
* Drop the lock and complete the URBs in the cancelled TD list.
* New TDs to be cancelled might be added to the end of the list before
* we can complete all the URBs for the TDs we already unlinked.
* So stop when we've completed the URB for the last TD we unlinked.
*/
do {
cur_td = list_entry(ep->cancelled_td_list.next,
struct xhci_td, cancelled_td_list);
list_del(&cur_td->cancelled_td_list);
/* Clean up the cancelled URB */
/* Doesn't matter what we pass for status, since the core will
* just overwrite it (because the URB has been unlinked).
*/
<API key>(xhci, cur_td, 0, "cancelled");
/* Stop processing the cancelled list if the watchdog timer is
* running.
*/
if (xhci->xhc_state & XHCI_STATE_DYING)
return;
} while (cur_td != last_unlinked_td);
/* Return to the event handler with xhci->lock re-acquired */
}
/* Watchdog timer function for when a stop endpoint command fails to complete.
* In this case, we assume the host controller is broken or dying or dead. The
* host may still be completing some other events, so we have to be careful to
* let the event ring handler and the URB dequeueing/enqueueing functions know
* through xhci->state.
*
* The timer may also fire if the host takes a very long time to respond to the
* command, and the stop endpoint command completion handler cannot delete the
* timer before the timer function is called. Another endpoint cancellation may
* sneak in before the timer function can grab the lock, and that may queue
* another stop endpoint command and add the timer back. So we cannot use a
* simple flag to say whether there is a pending stop endpoint command for a
* particular endpoint.
*
* Instead we use a combination of that flag and a counter for the number of
* pending stop endpoint commands. If the timer is the tail end of the last
* stop endpoint command, and the endpoint's command is still pending, we assume
* the host is dying.
*/
void <API key>(unsigned long arg)
{
struct xhci_hcd *xhci;
struct xhci_virt_ep *ep;
struct xhci_virt_ep *temp_ep;
struct xhci_ring *ring;
struct xhci_td *cur_td;
int ret, i, j;
ep = (struct xhci_virt_ep *) arg;
xhci = ep->xhci;
spin_lock(&xhci->lock);
ep->stop_cmds_pending
if (xhci->xhc_state & XHCI_STATE_DYING) {
xhci_dbg(xhci, "Stop EP timer ran, but another timer marked "
"xHCI as DYING, exiting.\n");
spin_unlock(&xhci->lock);
return;
}
if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) {
xhci_dbg(xhci, "Stop EP timer ran, but no command pending, "
"exiting.\n");
spin_unlock(&xhci->lock);
return;
}
xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n");
xhci_warn(xhci, "Assuming host is dying, halting host.\n");
/* Oops, HC is dead or dying or at least not responding to the stop
* endpoint command.
*/
xhci->xhc_state |= XHCI_STATE_DYING;
/* Disable interrupts from the host controller and start halting it */
<API key>(xhci);
spin_unlock(&xhci->lock);
ret = mtktest_xhci_halt(xhci);
spin_lock(&xhci->lock);
if (ret < 0) {
/* This is bad; the host is not responding to commands and it's
* not allowing itself to be halted. At least interrupts are
* disabled, so we can set HC_STATE_HALT and notify the
* USB core. But if we call usb_hc_died(), it will attempt to
* disconnect all device drivers under this host. Those
* disconnect() methods will wait for all URBs to be unlinked,
* so we must complete them.
*/
xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n");
xhci_warn(xhci, "Completing active URBs anyway.\n");
/* We could turn all TDs on the rings to no-ops. This won't
* help if the host has cached part of the ring, and is slow if
* we want to preserve the cycle bit. Skip it and hope the host
* doesn't touch the memory.
*/
}
for (i = 0; i < MAX_HC_SLOTS; i++) {
if (!xhci->devs[i])
continue;
for (j = 0; j < 31; j++) {
temp_ep = &xhci->devs[i]->eps[j];
ring = temp_ep->ring;
if (!ring)
continue;
xhci_dbg(xhci, "Killing URBs for slot ID %u, "
"ep index %u\n", i, j);
while (!list_empty(&ring->td_list)) {
cur_td = list_first_entry(&ring->td_list,
struct xhci_td,
td_list);
list_del(&cur_td->td_list);
if (!list_empty(&cur_td->cancelled_td_list))
list_del(&cur_td->cancelled_td_list);
<API key>(xhci, cur_td,
-ESHUTDOWN, "killed");
}
while (!list_empty(&temp_ep->cancelled_td_list)) {
cur_td = list_first_entry(
&temp_ep->cancelled_td_list,
struct xhci_td,
cancelled_td_list);
list_del(&cur_td->cancelled_td_list);
<API key>(xhci, cur_td,
-ESHUTDOWN, "killed");
}
}
}
spin_unlock(&xhci->lock);
xhci_to_hcd(xhci)->state = HC_STATE_HALT;
xhci_dbg(xhci, "Calling usb_hc_died()\n");
usb_hc_died(xhci_to_hcd(xhci));
xhci_dbg(xhci, "xHCI host controller is dead.\n");
}
/*
* When we get a completion for a Set Transfer Ring Dequeue Pointer command,
* we need to clear the set deq pending flag in the endpoint ring state, so that
* the TD queueing code can ring the doorbell again. We also need to ring the
* endpoint doorbell to restart the ring, but only if there aren't more
* cancellations pending.
*/
static void <API key>(struct xhci_hcd *xhci,
struct xhci_event_cmd *event,
union xhci_trb *trb)
{
unsigned int slot_id;
unsigned int ep_index;
unsigned int stream_id;
struct xhci_ring *ep_ring;
struct xhci_virt_device *dev;
struct xhci_ep_ctx *ep_ctx;
struct xhci_slot_ctx *slot_ctx;
slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
stream_id = TRB_TO_STREAM_ID(trb->generic.field[2]);
dev = xhci->devs[slot_id];
ep_ring = <API key>(dev, ep_index, stream_id);
if (!ep_ring) {
xhci_warn(xhci, "WARN Set TR deq ptr command for "
"freed stream ID %u\n",
stream_id);
/* XXX: Harmless??? */
dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
return;
}
ep_ctx = <API key>(xhci, dev->out_ctx, ep_index);
slot_ctx = <API key>(xhci, dev->out_ctx);
if (GET_COMP_CODE(event->status) != COMP_SUCCESS) {
unsigned int ep_state;
unsigned int slot_state;
switch (GET_COMP_CODE(event->status)) {
case COMP_TRB_ERR:
xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because "
"of stream ID configuration\n");
break;
case COMP_CTX_STATE:
xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due "
"to incorrect slot or ep state.\n");
ep_state = ep_ctx->ep_info;
ep_state &= EP_STATE_MASK;
slot_state = slot_ctx->dev_state;
slot_state = GET_SLOT_STATE(slot_state);
xhci_dbg(xhci, "Slot state = %u, EP state = %u\n",
slot_state, ep_state);
break;
case COMP_EBADSLT:
xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because "
"slot %u was not enabled.\n", slot_id);
break;
default:
xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown "
"completion code of %u.\n",
GET_COMP_CODE(event->status));
break;
}
/* OK what do we do now? The endpoint state is hosed, and we
* should never get to this point if the synchronization between
* queueing, and endpoint state are correct. This might happen
* if the device gets disconnected after we've finished
* cancelling URBs, which might not be an error...
*/
} else {
xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n",
ep_ctx->deq);
if (<API key>(dev->eps[ep_index].queued_deq_seg,
dev->eps[ep_index].queued_deq_ptr) ==
(ep_ctx->deq & ~(EP_CTX_CYCLE_MASK))) {
/* Update the ring's dequeue segment and dequeue pointer
* to reflect the new position.
*/
ep_ring->deq_seg = dev->eps[ep_index].queued_deq_seg;
ep_ring->dequeue = dev->eps[ep_index].queued_deq_ptr;
} else {
xhci_warn(xhci, "Mismatch between completed Set TR Deq "
"Ptr command & xHCI internal state.\n");
xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n",
dev->eps[ep_index].queued_deq_seg,
dev->eps[ep_index].queued_deq_ptr);
}
}
dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
dev->eps[ep_index].queued_deq_seg = NULL;
dev->eps[ep_index].queued_deq_ptr = NULL;
/* Restart any rings with pending URBs */
<API key>(xhci, slot_id, ep_index);
}
static void <API key>(struct xhci_hcd *xhci,
struct xhci_event_cmd *event,
union xhci_trb *trb)
{
int slot_id;
unsigned int ep_index;
slot_id = TRB_TO_SLOT_ID(trb->generic.field[3]);
ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
/* This command will only fail if the endpoint wasn't halted,
* but we don't care.
*/
xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n",
(unsigned int) GET_COMP_CODE(event->status));
/* HW with the reset endpoint quirk needs to have a configure endpoint
* command complete before the endpoint can be used. Queue that here
* because the HW can't handle two commands being queued in a row.
*/
if (xhci->quirks & XHCI_RESET_EP_QUIRK) {
xhci_dbg(xhci, "Queueing configure endpoint command\n");
<API key>(xhci,
xhci->devs[slot_id]->in_ctx->dma, slot_id,
false);
<API key>(xhci);
} else {
/* Clear our internal halted state and restart the ring(s) */
xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED;
<API key>(xhci, slot_id, ep_index);
}
}
/* Check to see if a command in the device's command queue matches this one.
* Signal the completion or free the command, and return 1. Return 0 if the
* completed command isn't at the head of the command list.
*/
static int <API key>(struct xhci_hcd *xhci,
struct xhci_virt_device *virt_dev,
struct xhci_event_cmd *event)
{
struct xhci_command *command;
if (list_empty(&virt_dev->cmd_list))
return 0;
command = list_entry(virt_dev->cmd_list.next,
struct xhci_command, cmd_list);
if (xhci->cmd_ring->dequeue != command->command_trb)
return 0;
command->status =
GET_COMP_CODE(event->status);
list_del(&command->cmd_list);
if (command->completion)
complete(command->completion);
else
<API key>(xhci, command);
return 1;
}
/*
* This TD is defined by the TRBs starting at start_trb in start_seg and ending
* at end_trb, which may be in another segment. If the suspect DMA address is a
* TRB in this TD, this function returns that TRB's segment. Otherwise it
* returns 0.
*/
struct xhci_segment *mtktest_trb_in_td(struct xhci_segment *start_seg,
union xhci_trb *start_trb,
union xhci_trb *end_trb,
dma_addr_t suspect_dma)
{
dma_addr_t start_dma;
dma_addr_t end_seg_dma;
dma_addr_t end_trb_dma;
struct xhci_segment *cur_seg;
start_dma = <API key>(start_seg, start_trb);
cur_seg = start_seg;
printk(KERN_DEBUG "start_dma 0x%p\n", (void *)(unsigned long)start_dma);
printk(KERN_DEBUG "start_seg 0x%p\n", start_seg);
printk(KERN_DEBUG "start_trb 0x%p\n", start_trb);
printk(KERN_DEBUG "end_trb 0x%p\n", end_trb);
printk(KERN_DEBUG "suspect_dma 0x%p\n", (void *)(unsigned long)suspect_dma);
do {
if (start_dma == 0){
printk(KERN_DEBUG "return NULL 1\n");
return NULL;
}
/* We may get an event for a Link TRB in the middle of a TD */
end_seg_dma = <API key>(cur_seg,
&cur_seg->trbs[TRBS_PER_SEGMENT - 1]);
/* If the end TRB isn't in this segment, this is set to 0 */
end_trb_dma = <API key>(cur_seg, end_trb);
printk(KERN_DEBUG "end_trb_dma 0x%p\n", (void *)(unsigned long)end_trb_dma);
if (end_trb_dma > 0) {
/* The end TRB is in this segment, so suspect should be here */
if (start_dma <= end_trb_dma) {
if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma)
return cur_seg;
} else {
/* Case for one segment with
* a TD wrapped around to the top
*/
if ((suspect_dma >= start_dma &&
suspect_dma <= end_seg_dma) ||
(suspect_dma >= cur_seg->dma &&
suspect_dma <= end_trb_dma))
return cur_seg;
}
printk(KERN_DEBUG "return NULL 2\n");
return NULL;
} else {
/* Might still be somewhere in this segment */
if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma)
return cur_seg;
}
cur_seg = cur_seg->next;
start_dma = <API key>(cur_seg, &cur_seg->trbs[0]);
} while (cur_seg != start_seg);
printk(KERN_DEBUG "return NULL 3\n");
return NULL;
}
static void <API key>(struct xhci_hcd *xhci,
unsigned int slot_id, unsigned int ep_index,
unsigned int stream_id,
struct xhci_td *td, union xhci_trb *event_trb)
{
struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index];
ep->ep_state |= EP_HALTED;
ep->stopped_td = td;
ep->stopped_trb = event_trb;
ep->stopped_stream = stream_id;
<API key>(xhci, slot_id, ep_index);
<API key>(xhci, td->urb->dev, ep_index);
ep->stopped_td = NULL;
ep->stopped_trb = NULL;
ep->stopped_stream = 0;
<API key>(xhci);
}
/* Check if an error has halted the endpoint ring. The class driver will
* cleanup the halt for a non-default control endpoint if we indicate a stall.
* However, a babble and other errors also halt the endpoint ring, and the class
* driver won't clear the halt in that case, so we need to issue a Set Transfer
* Ring Dequeue Pointer command manually.
*/
static int <API key>(struct xhci_hcd *xhci,
struct xhci_ep_ctx *ep_ctx,
unsigned int trb_comp_code)
{
xhci_dbg(xhci, "check required to cleanup halt ep\n");
xhci_dbg(xhci, "ep_info 0x%x\n", ep_ctx->ep_info);
/* TRB completion codes that may require a manual halt cleanup */
if (trb_comp_code == COMP_TX_ERR ||
trb_comp_code == COMP_BABBLE ||
trb_comp_code == COMP_SPLIT_ERR)
/* The 0.96 spec says a babbling control endpoint
* is not halted. The 0.96 spec says it is. Some HW
* claims to be 0.95 compliant, but it halts the control
* endpoint anyway. Check if a babble halted the
* endpoint.
*/
if ((ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_HALTED){
xhci_dbg(xhci, "Required to cleanup halt ep, comp code(%d)\n", trb_comp_code);
return 1;
}
return 0;
}
int <API key>(struct xhci_hcd *xhci, unsigned int trb_comp_code)
{
if (trb_comp_code >= 224 && trb_comp_code <= 255) {
/* Vendor defined "informational" completion code,
* treat as not-an-error.
*/
xhci_dbg(xhci, "Vendor defined info completion code %u\n",
trb_comp_code);
xhci_dbg(xhci, "Treating code as success.\n");
return 1;
}
return 0;
}
/*
* Finish the td processing, remove the td from td list;
* Return 1 if the urb can be given back.
*/
static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td,
union xhci_trb *event_trb, struct xhci_transfer_event *event,
struct xhci_virt_ep *ep, int *status, bool skip)
{
struct xhci_virt_device *xdev;
struct xhci_ring *ep_ring;
unsigned int slot_id;
int ep_index;
struct urb *urb = NULL;
struct xhci_ep_ctx *ep_ctx;
int ret = 0;
struct urb_priv *urb_priv;
u32 trb_comp_code;
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
slot_id = TRB_TO_SLOT_ID(event->flags);
xdev = xhci->devs[slot_id];
ep_index = TRB_TO_EP_ID(event->flags) - 1;
ep_ring = <API key>(ep, event->buffer);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
ep_ctx = <API key>(xhci, xdev->out_ctx, ep_index);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
trb_comp_code = GET_COMP_CODE(event->transfer_len);
if (skip)
goto td_cleanup;
if (trb_comp_code == COMP_STOP_INVAL ||
trb_comp_code == COMP_STOP) {
/* The Endpoint Stop Command completion will take care of any
* stopped TDs. A stopped TD may be restarted, so don't update
* the ring dequeue pointer or take this TD off any lists yet.
*/
ep->stopped_td = td;
ep->stopped_trb = event_trb;
xhci_dbg(xhci, "trb_comp_code call COMP_STALL or COMP_STOP_INVAL, %d\n",trb_comp_code);
return 0;
} else {
if (trb_comp_code == COMP_STALL) {
/* The transfer is completed from the driver's
* perspective, but we need to issue a set dequeue
* command for this stalled endpoint to move the dequeue
* pointer past the TD. We can't do that here because
* the halt condition must be cleared first. Let the
* USB class driver clear the stall later.
*/
ep->stopped_td = td;
ep->stopped_trb = event_trb;
ep->stopped_stream = ep_ring->stream_id;
xhci_dbg(xhci, "trb_comp_code call COMP_STALL\n");
} else if (<API key>(xhci,
ep_ctx, trb_comp_code)) {
/* Other types of errors halt the endpoint, but the
* class driver doesn't call usb_reset_endpoint() unless
* the error is -EPIPE. Clear the halted status in the
* xHCI hardware manually.
*/
xhci_dbg(xhci, "Need to cleanup halt ep, do it\n");
<API key>(xhci,
slot_id, ep_index, ep_ring->stream_id,
td, event_trb);
} else {
xhci_dbg(xhci, "inc dequeue of ring: dequeue(0x%p), td(0x%p), last_trb(0x%p)\n", ep_ring->dequeue, td, td->last_trb);
/* Update ring dequeue pointer */
while (ep_ring->dequeue != td->last_trb)
mtktest_inc_deq(xhci, ep_ring, false);
mtktest_inc_deq(xhci, ep_ring, false);
}
td_cleanup:
/* Clean up the endpoint's TD list */
urb = td->urb;
urb_priv = urb->hcpriv;
/* Do one last check of the actual transfer length.
* If the host controller said we transferred more data than
* the buffer length, urb->actual_length will be a very big
* number (since it's unsigned). Play it safe and say we didn't
* transfer anything.
*/
if (urb->actual_length > urb-><API key>) {
xhci_warn(xhci, "URB transfer length is wrong, "
"xHC issue? req. len = %u, "
"act. len = %u\n",
urb-><API key>,
urb->actual_length);
urb->actual_length = 0;
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
*status = -EREMOTEIO;
else
*status = 0;
}
#if 0
spin_lock(&ep_ring->lock);
list_del(&td->td_list);
spin_unlock(&ep_ring->lock);
#endif
xhci_dbg(xhci,"td(0x%p), prev(0x%p), next(0x%p)\n", td, td->td_list.prev, td->td_list.next);
//msleep(1000) ;
list_del(&td->td_list);
xhci_dbg(xhci,"list_del done\n");
/* Was this TD slated to be cancelled but completed anyway? */
if (!list_empty(&td->cancelled_td_list))
list_del(&td->cancelled_td_list);
urb_priv->td_cnt++;
/* Giveback the urb when all the tds are completed */
if (urb_priv->td_cnt == urb_priv->length)
ret = 1;
}
xhci_dbg(xhci,"finish done\n");
return ret;
}
/*
* Process control tds, update urb status and actual_length.
*/
#define FINISH_TD_CALL (0xFFFE)
static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td,
union xhci_trb *event_trb, struct xhci_transfer_event *event,
struct xhci_virt_ep *ep, int *status)
{
struct xhci_virt_device *xdev;
struct xhci_ring *ep_ring;
unsigned int slot_id;
int ep_index;
struct xhci_ep_ctx *ep_ctx;
u32 trb_comp_code;
int ret ;
xhci_dbg(xhci, "process_ctrl_td========>\n");
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
slot_id = TRB_TO_SLOT_ID(event->flags);
xdev = xhci->devs[slot_id];
ep_index = TRB_TO_EP_ID(event->flags) - 1;
ep_ring = <API key>(ep, event->buffer);
xhci_dbg(xhci, "ep_ring is 0x%p\n", ep_ring ) ;
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
ep_ctx = <API key>(xhci, xdev->out_ctx, ep_index);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
trb_comp_code = GET_COMP_CODE(event->transfer_len);
<API key>(xhci, xhci->event_ring->dequeue);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
switch (trb_comp_code) {
case COMP_SUCCESS:
if (event_trb == ep_ring->dequeue) {
xhci_warn(xhci, "WARN: Success on ctrl setup TRB "
"without IOC set??\n");
*status = -ESHUTDOWN;
} else if (event_trb != td->last_trb) {
#if 1
xhci_warn(xhci, "WARN: Success on ctrl data TRB "
"without IOC set??\n");
#endif
*status = -ESHUTDOWN;
} else {
xhci_dbg(xhci, "Successful control transfer!\n");
*status = 0;
}
xhci_dbg(xhci, "end of COMP_SUCCESS\n");
break;
case COMP_SHORT_TX:
xhci_warn(xhci, "WARN: short transfer on control ep\n");
*status = 0;
break;
case COMP_STOP_INVAL:
case COMP_STOP:
ret = finish_td(xhci, td, event_trb, event, ep, status, false);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
//td->urb->status = *status;
//return ret ;
return FINISH_TD_CALL ;
default:
xhci_dbg(xhci, "TRB error code %u, "
"halted endpoint index = %u\n",
trb_comp_code, ep_index);
if (!<API key>(xhci,
ep_ctx, trb_comp_code))
break;
/* else fall through */
case COMP_STALL:
/* Did we transfer part of the data (middle) phase? */
if (event_trb != ep_ring->dequeue &&
event_trb != td->last_trb)
td->urb->actual_length =
td->urb-><API key>
- TRB_LEN(event->transfer_len);
else
td->urb->actual_length = 0;
<API key>(xhci,
slot_id, ep_index, 0, td, event_trb);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
ret = finish_td(xhci, td, event_trb, event, ep, status, true);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
//td->urb->status = *status;
//return ret ;
return FINISH_TD_CALL ;
//return 0;
}
xhci_dbg(xhci, "process_ctrl_td========>2\n");
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
/*
* Did we transfer any data, despite the errors that might have
* happened? I.e. did we get past the setup stage?
*/
if (event_trb != ep_ring->dequeue) {
/* The event was for the status stage */
if (event_trb == td->last_trb) {
if (td->urb->actual_length != 0) {
/* Don't overwrite a previously set error code
*/
if ((*status == -EINPROGRESS || *status == 0) &&
(td->urb->transfer_flags
& URB_SHORT_NOT_OK))
/* Did we already see a short data
* stage? */
*status = -EREMOTEIO;
} else {
td->urb->actual_length =
td->urb-><API key>;
}
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
} else {
/* Maybe the event was for the data stage? */
if (trb_comp_code != COMP_STOP_INVAL) {
/* We didn't stop on a link TRB in the middle */
td->urb->actual_length =
td->urb-><API key> -
TRB_LEN(event->transfer_len);
xhci_dbg(xhci, "Waiting for status "
"stage event\n");
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
return 0;
}
}
}
xhci_dbg(xhci, "process_ctrl_td========>3\n");
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
ret = finish_td(xhci, td, event_trb, event, ep, status, false);
xhci_dbg(xhci, "process_ctrl_td <========\n");
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
//td->urb->status = *status;
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
//return ret;
return FINISH_TD_CALL ;
//return finish_td(xhci, td, event_trb, event, ep, status, false);
}
/*
* Process bulk and interrupt tds, update urb status and actual_length.
*/
static int <API key>(struct xhci_hcd *xhci, struct xhci_td *td,
union xhci_trb *event_trb, struct xhci_transfer_event *event,
struct xhci_virt_ep *ep, int *status)
{
struct xhci_ring *ep_ring;
union xhci_trb *cur_trb;
struct xhci_segment *cur_seg;
u32 trb_comp_code;
int ret ;
ep_ring = <API key>(ep, event->buffer);
trb_comp_code = GET_COMP_CODE(event->transfer_len);
switch (trb_comp_code) {
case COMP_SUCCESS:
/* Double check that the HW transferred everything. */
if (event_trb != td->last_trb) {
xhci_warn(xhci, "WARN Successful completion "
"on short TX\n");
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
*status = -EREMOTEIO;
else
*status = 0;
} else {
if (<API key>(&td->urb->ep->desc))
xhci_dbg(xhci, "Successful bulk "
"transfer!\n");
else
xhci_dbg(xhci, "Successful interrupt "
"transfer!\n");
*status = 0;
}
break;
case COMP_SHORT_TX:
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
*status = -EREMOTEIO;
else
*status = 0;
break;
default:
/* Others already handled above */
break;
}
xhci_dbg(xhci,
"ep %#x - asked for %d bytes, "
"%d bytes untransferred\n",
td->urb->ep->desc.bEndpointAddress,
td->urb-><API key>,
TRB_LEN(event->transfer_len));
/* Fast path - was this the last TRB in the TD for this URB? */
if (event_trb == td->last_trb) {
if (TRB_LEN(event->transfer_len) != 0) {
td->urb->actual_length =
td->urb-><API key> -
TRB_LEN(event->transfer_len);
if (td->urb-><API key> <
td->urb->actual_length) {
xhci_warn(xhci, "HC gave bad length "
"of %d bytes left\n",
TRB_LEN(event->transfer_len));
td->urb->actual_length = 0;
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
*status = -EREMOTEIO;
else
*status = 0;
}
/* Don't overwrite a previously set error code */
if (*status == -EINPROGRESS) {
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
*status = -EREMOTEIO;
else
*status = 0;
}
} else {
td->urb->actual_length =
td->urb-><API key>;
/* Ignore a short packet completion if the
* untransferred length was zero.
*/
if (*status == -EREMOTEIO)
*status = 0;
}
} else {
/* Slow path - walk the list, starting from the dequeue
* pointer, to get the actual length transferred.
*/
td->urb->actual_length = 0;
for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg;
cur_trb != event_trb;
next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
if ((cur_trb->generic.field[3] &
TRB_TYPE_BITMASK) != TRB_TYPE(TRB_TR_NOOP) &&
(cur_trb->generic.field[3] &
TRB_TYPE_BITMASK) != TRB_TYPE(TRB_LINK))
td->urb->actual_length +=
TRB_LEN(cur_trb->generic.field[2]);
}
/* If the ring didn't stop on a Link or No-op TRB, add
* in the actual bytes transferred from the Normal TRB
*/
if (trb_comp_code != COMP_STOP_INVAL)
td->urb->actual_length +=
TRB_LEN(cur_trb->generic.field[2]) -
TRB_LEN(event->transfer_len);
}
ret = finish_td(xhci, td, event_trb, event, ep, status, false);
//td->urb->status = *status;
//return ret ;
return FINISH_TD_CALL ;
}
/*
* Process isochronous tds, update urb packet status and actual_length.
*/
int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td,
union xhci_trb *event_trb, struct xhci_transfer_event *event,
struct xhci_virt_ep *ep, int *status)
{
struct xhci_ring *ep_ring;
struct urb_priv *urb_priv;
int idx;
int len = 0;
int skip_td = 0;
union xhci_trb *cur_trb;
struct xhci_segment *cur_seg;
u32 trb_comp_code;
int ret ;
ep_ring = <API key>(ep, event->buffer);
trb_comp_code = GET_COMP_CODE(event->transfer_len);
urb_priv = td->urb->hcpriv;
idx = urb_priv->td_cnt;
/* handle completion code */
switch (trb_comp_code) {
case COMP_SUCCESS:
td->urb->iso_frame_desc[idx].status = 0;
xhci_dbg(xhci, "Successful isoc transfer, idx(%d)!\n", idx);
break;
case COMP_SHORT_TX:
if (td->urb->transfer_flags & URB_SHORT_NOT_OK)
td->urb->iso_frame_desc[idx].status =
-EREMOTEIO;
else
td->urb->iso_frame_desc[idx].status = 0;
break;
case COMP_BW_OVER:
td->urb->iso_frame_desc[idx].status = -ECOMM;
skip_td = 1;
break;
case COMP_BUFF_OVER:
case COMP_BABBLE:
td->urb->iso_frame_desc[idx].status = -EOVERFLOW;
skip_td = 1;
break;
case COMP_STALL:
td->urb->iso_frame_desc[idx].status = -EPROTO;
skip_td = 1;
break;
case COMP_STOP:
case COMP_STOP_INVAL:
break;
default:
td->urb->iso_frame_desc[idx].status = -1;
break;
}
if (trb_comp_code == COMP_SUCCESS || skip_td == 1) {
td->urb->iso_frame_desc[idx].actual_length =
td->urb->iso_frame_desc[idx].length;
td->urb->actual_length +=
td->urb->iso_frame_desc[idx].length;
} else {
for (cur_trb = ep_ring->dequeue,
cur_seg = ep_ring->deq_seg; cur_trb != event_trb;
next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) {
if ((cur_trb->generic.field[3] &
TRB_TYPE_BITMASK) != TRB_TYPE(TRB_TR_NOOP) &&
(cur_trb->generic.field[3] &
TRB_TYPE_BITMASK) != TRB_TYPE(TRB_LINK))
len +=
TRB_LEN(cur_trb->generic.field[2]);
}
len += TRB_LEN(cur_trb->generic.field[2]) -
TRB_LEN(event->transfer_len);
if (trb_comp_code != COMP_STOP_INVAL) {
td->urb->iso_frame_desc[idx].actual_length = len;
td->urb->actual_length += len;
}
}
if ((idx == urb_priv->length - 1) && *status == -EINPROGRESS){
*status = 0;
}
ret = finish_td(xhci, td, event_trb, event, ep, status, false);
//td->urb->status = *status;
//return ret ;
return FINISH_TD_CALL ;
}
static void <API key>(struct xhci_hcd *xhci,
struct xhci_event_cmd *event)
{
int slot_id;
u64 cmd_dma;
dma_addr_t cmd_dequeue_dma;
union xhci_trb *trb;
struct <API key> *ctrl_ctx;
struct xhci_virt_device *virt_dev;
unsigned int ep_index, ret;
struct xhci_ring *ep_ring;
unsigned int ep_state, port_id;
struct usb_hcd *hcd = xhci_to_hcd(xhci);
struct usb_device *udev, *rhdev;
struct xhci_slot_ctx *slot_ctx;
u64 temp_64;
struct urb *urb;
struct usb_ctrlrequest *dr;
struct <API key> *desc;
int status;
slot_id = TRB_TO_SLOT_ID(event->flags);
cmd_dma = event->cmd_trb;
cmd_dequeue_dma = <API key>(xhci->cmd_ring->deq_seg,
xhci->cmd_ring->dequeue);
trb = xhci->cmd_ring->dequeue;
/* Is the command ring deq ptr out of sync with the deq seg ptr? */
if (cmd_dequeue_dma == 0) {
xhci->error_bitmask |= 1 << 4;
return;
}
/* Does the DMA address match our internal dequeue pointer address? */
if (cmd_dma != (u64) cmd_dequeue_dma) {
xhci->error_bitmask |= 1 << 5;
return;
}
xhci_err(xhci, "CMD(%d), Complete Code(%d), slot_id(%d)\n",
TRB_FIELD_TO_TYPE(xhci->cmd_ring->dequeue->generic.field[3]), GET_COMP_CODE(event->status), slot_id);
switch (xhci->cmd_ring->dequeue->generic.field[3] & TRB_TYPE_BITMASK) {
case TRB_TYPE(TRB_CMD_NOOP):
break;
case TRB_TYPE(TRB_ENABLE_SLOT):
if (GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_err(xhci, "Enable slot\n");
g_slot_id = slot_id;
g_cmd_status = CMD_DONE;
}
else{
g_slot_id = 0;
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_DISABLE_SLOT):
if (GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_err(xhci, "Disable slot\n");
g_slot_id = slot_id;
g_cmd_status = CMD_DONE;
}
break;
case TRB_TYPE(TRB_ADDR_DEV):
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_err(xhci, "Address Device\n");
g_cmd_status = CMD_DONE;
}
else if(GET_COMP_CODE(event->status) == COMP_CMD_ABORT){
xhci_err(xhci, "Address Device Aborted\n");
g_cmd_status = CMD_DONE;
}
else{
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_CONFIG_EP):
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_err(xhci, "config endpoint success\n");
g_cmd_status = CMD_DONE;
}
else{
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_RESET_DEV):
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_err(xhci, "reset dev success\n");
g_cmd_status = CMD_DONE;
}
else{
xhci_dbg(xhci, "reset dev failed, code: %d\n", GET_COMP_CODE(event->status));
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_STOP_RING):
xhci_err(xhci, "TRB_STOP_RING\n");
//xhci_err(xhci, "[DBG] stop ep event refer to 0x%x\n", event->cmd_trb);
if((((int)event->cmd_trb) & 0xff0) != g_cmd_ring_pointer1 && (((int)event->cmd_trb) & 0xff0) != g_cmd_ring_pointer2){
xhci_err(xhci, "[DBG] handle stop ep command pointer not equal to enqueued pointer, enqueue 0x%x , 0x%x, event refer 0x%x\n"
, g_cmd_ring_pointer1, g_cmd_ring_pointer2, (((int)event->cmd_trb) & 0xff0));
while(1);
}
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
xhci_dbg(xhci, "stop ring success\n");
g_cmd_status = CMD_DONE;
}
else{
xhci_dbg(xhci, "stop ring failed, code: %d\n", GET_COMP_CODE(event->status));
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_SET_DEQ):
xhci_err(xhci, "TRB_SET_DEQ\n");
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
virt_dev = xhci->devs[slot_id];
virt_dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING;
g_cmd_status = CMD_DONE;
}
else{
xhci_dbg(xhci, "stop ring failed, code: %d\n", GET_COMP_CODE(event->status));
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_EVAL_CONTEXT):
xhci_err(xhci, "TRB_EVAL_CONTEXT\n");
if(GET_COMP_CODE(event->status) == COMP_SUCCESS){
g_cmd_status = CMD_DONE;
}
else{
xhci_dbg(xhci, "eval context, code: %d\n", GET_COMP_CODE(event->status));
g_cmd_status = CMD_FAIL;
}
break;
case TRB_TYPE(TRB_RESET_EP):
ep_index = TRB_TO_EP_INDEX(trb->generic.field[3]);
xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED;
g_cmd_status = CMD_DONE;
break;
default:
if(GET_COMP_CODE(event->status) == COMP_CMD_STOP){
xhci_err(xhci, "command ring stopped\n");
g_cmd_status = CMD_DONE;
return;
}
#if 0
case TRB_TYPE(TRB_COMPLETION):
if(GET_COMP_CODE(event->status) == COMP_CMD_STOP){
xhci_dbg(xhci, "stop command ring\n");
g_cmd_status = CMD_DONE;
}
else{
xhci_dbg(xhci, "stop command failed, code: %d\n", GET_COMP_CODE(event->status));
g_cmd_status = CMD_FAIL;
}
break;
#endif
/* Skip over unknown commands on the event ring */
xhci->error_bitmask |= 1 << 6;
g_cmd_status = CMD_FAIL;
break;
}
mtktest_inc_deq(xhci, xhci->cmd_ring, false);
}
void <API key>(struct xhci_hcd *xhci, int port_id, int port_temp){
u32 temp;
u32 __iomem *addr;
port_id
addr = &xhci->op_regs->port_status_base + NUM_PORT_REGS*(port_id & 0xff);
//temp = temp = xhci_readl(xhci, addr);
temp = port_temp;
xhci_dbg(xhci, "to clear port change, actual port %d status = 0x%x\n", port_id, temp);
temp = <API key>(temp);
xhci_writel(xhci, temp, addr);
temp = xhci_readl(xhci, addr);
xhci_dbg(xhci, "clear port change, actual port %d status = 0x%x\n", port_id, temp);
}
int rh_get_port_status(struct xhci_hcd *xhci, int port_id){
u32 temp, temp1,status;
u32 __iomem *addr;
port_id
status = 0;
addr = &xhci->op_regs->port_status_base + NUM_PORT_REGS*(port_id & 0xff);
temp = xhci_readl(xhci, addr);
printk(KERN_ERR "[OTG_H][rh_get_port_status] read port status 0x%x\n", temp);
/* wPortChange bits */
if (temp & PORT_CSC)
status |= <API key> << 16;
if (temp & PORT_PEC)
status |= <API key> << 16;
if ((temp & PORT_OCC))
status |= <API key> << 16;
if ((temp & PORT_RC))
status |= <API key> << 16;
if ((temp & PORT_PLC))
status |= <API key> << 16;
/*
* FIXME ignoring suspend, reset, and USB 2.1/3.0 specific
* changes
*/
if (temp & PORT_CONNECT) {
status |= <API key>;
status |= <API key>(temp);
}
if (temp & PORT_PE)
status |= <API key>;
if (temp & PORT_OC)
status |= <API key>;
if (temp & PORT_RESET)
status |= USB_PORT_STAT_RESET;
if (temp & PORT_POWER)
status |= USB_PORT_STAT_POWER;
temp1 = <API key>(temp);
// xhci_writel(xhci, temp, addr);
// temp = xhci_readl(xhci, addr);
xhci_err(xhci, "port_id(%d), state(0x%x), neutral(0x%x), status(0x%x)\n", port_id, temp, temp1, status);
#if 0
put_unaligned(cpu_to_le32(status), (__le32 *) buf);
#endif
return status;
}
extern void <API key>(struct xhci_hcd *xhci);
extern void phy_hsrx_reset(void);
extern void phy_hsrx_set(void);
static void handle_port_status(struct xhci_hcd *xhci,
union xhci_trb *event)
{
u32 port_id, temp, temp1;
int ret, port_status;
struct usb_hcd *hcd = xhci_to_hcd(xhci);
u32 __iomem *addr;
int port_index;
struct xhci_port *port;
#if TEST_OTG
u32 temp2;
#endif
/* Port status change events always have a successful completion code */
if (GET_COMP_CODE(event->generic.field[2]) != COMP_SUCCESS) {
xhci_warn(xhci, "WARN: xHC returned failed port status event\n");
xhci->error_bitmask |= 1 << 8;
}
/* FIXME: core doesn't care about all port link state changes yet */
port_id = GET_PORT_ID(event->generic.field[0]);
port_index = get_port_index(port_id);
xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id);
xhci_dbg(xhci, "port_index: %d\n", port_index);
if(port_index >= RH_PORT_NUM){
xhci_err(xhci, "[ERROR] RH_PORT_NUM not enough\n");
return;
}
port = rh_port[port_index];
port->port_id = port_id;
addr = &xhci->op_regs->port_status_base + NUM_PORT_REGS*((port_id - 1) & 0xff);
temp = xhci_readl(xhci, addr);
printk(KERN_ERR "[OTG_H] port_status change event port_status 0x%x\n", temp);
port_status = rh_get_port_status(xhci, port_id);
printk(KERN_ERR "port_status %x\n", port_status);
// <API key>(xhci, port_id);
if(port_status & (<API key> << 16)){
if(port_status & <API key>){
xhci_err(xhci, "[OTG_H]connect port status event, connected, port_id is %d\n", port_id);
// USBIF
phy_hsrx_set();
g_port_id = port_id;
g_port_connect = true;
port->port_status = CONNECTED;
g_otg_wait_con = false;
mb() ;
printk(KERN_ERR "[OTG_H] handle_port_status, connected, g_port_connect is %d\n", g_port_connect);
if(!(port_status & <API key>)){
if(g_hs_block_reset){// USBIF OTG
#if TEST_OTG
port->port_status = ENABLED;
#endif
}
else{
// USBIF , WARN
mb() ;
addr = &xhci->op_regs->port_status_base + NUM_PORT_REGS*(port_id-1 & 0xff);
temp1 = xhci_readl(xhci, addr);
temp1 = <API key>(temp);
xhci_err(xhci, "Before Reset command, the port status is 0x%x\n", temp1);
if(!g_otg_dev_B)
mdelay(150);
//reset status
temp1 = (temp1 | PORT_RESET);
xhci_dbg(xhci, "Reset command\n");
xhci_err(xhci, "Reset command\n");
xhci_writel(xhci, temp1, addr);
port->port_status = RESET;
}
}
else{
if(port->port_reenabled == 1){
port->port_reenabled = 2;
}
if(g_device_reconnect == 1)
g_device_reconnect = 2;
g_speed = USB_SPEED_SUPER;
addr = &xhci->op_regs->port_status_base + NUM_PORT_REGS*(port_id-1 & 0xff);
temp1 = xhci_readl(xhci, addr);
if(((temp1 & PORT_RESET) == 0) && (temp1 & PORT_PE) && (PORT_PLS(temp1) == 0)){
port->port_status = ENABLED;
port->port_speed = USB_SPEED_SUPER;
xhci_err(xhci, "port set: port_id %d, port_status %d, port_speed %d\n"
, port->port_id, port->port_status, port->port_speed);
g_port_reset = true;
mb() ;
}
else{
xhci_err(xhci, "Super speed port enabled failed!!\n");
xhci_dbg(xhci, "temp & PORT_RESET 0x%x\n", (temp & PORT_RESET));
xhci_dbg(xhci, "temp & PORT_PE 0x%x\n", (temp & PORT_PE));
xhci_dbg(xhci, "temp & PORT_PLS 0x%x\n", (PORT_PLS(temp)));
g_port_reset = false;
mb() ;
}
}
}
else{ //port disconnect
xhci_err(xhci, "[OTG_H]connect port status event, disconnected\n");
// port->port_id = 0;
port->port_speed = 0;
port->port_status = DISCONNECTED;
if(port->port_reenabled == 0){
port->port_reenabled = 1;
}
g_port_connect = false;
g_port_reset = false;
if(g_device_reconnect == 0)
g_device_reconnect = 1;
mb() ;
printk(KERN_ERR "[OTG_H] handle_port_status, disconnect, g_port_connect is %d\n", g_port_connect);
#if TEST_OTG
temp2 = readl(SSUSB_OTG_STS);
//if change role doesn't turn off power, else turn off power
//TODO:
//xhci_err(xhci, "[OTG_H]SSUSB_OTG_STS is 0x%x\n", temp2);
// USBIF, WARN
mb() ;
if (<API key>){ //fast switch back to device ..
//<API key>(xhci);
//xhci_err(xhci, "[OTG_H]suspend device done, SSUSB_OTG_STS is 0x%x\n", readl(SSUSB_OTG_STS));
//writel(readl(SSUSB_U2_CTRL(0)) &(~<API key>) , SSUSB_U2_CTRL(0));
//xhci_err(xhci, "[OTG_H]change DMA to Device done,SSUSB_OTG_STS is 0x%x\n", readl(SSUSB_OTG_STS));
}
#endif
}
g_otg_csc = true; // move to final place to avoid race condition with g_port_connect
mb() ;
}
if((port_status & (<API key> << 16)) && (port_status & (<API key>)) && !(port_status & <API key>)){
xhci_dbg(xhci, "Change Reset\n");
if(!(port_status & USB_PORT_STAT_RESET)){
if(port_status & <API key>){
port->port_speed = USB_SPEED_LOW;
g_speed = USB_SPEED_LOW;
xhci_dbg(xhci, "Change Reset, speed low\n");
}
else if(port_status & <API key>){
port->port_speed = USB_SPEED_HIGH;
g_speed = USB_SPEED_HIGH;
xhci_dbg(xhci, "Change Reset, speed high\n");
}
else{
port->port_speed = USB_SPEED_FULL;
g_speed = USB_SPEED_FULL;
xhci_dbg(xhci, "Change Reset, speed full\n");
}
port->port_status = ENABLED;
xhci_err(xhci, "port_reenabled(%d)\n", port->port_reenabled);
if(port->port_reenabled == 1){
port->port_reenabled = 2;
}
if(g_device_reconnect == 1)
g_device_reconnect = 2;
g_port_reset = true;
mb() ;
}
else{
g_port_reset = false;
mb() ;
}
}
else if((port_status & (<API key> << 16)) && (port_status & (<API key>))
&& (port_status & <API key>)){
port->port_status = ENABLED;
}
else if((port_status & (<API key> << 16)) && (!(port_status & (<API key>)))){
//OTG with PET, change back to device after just reset
printk(KERN_ERR "[OTG_H] <API key> and \n");
if(<API key> && g_otg_dev_B){ // recieve SSUSB_CHG_A_ROLE_A from U3D test driver
if(!g_otg_wait_con){
while(readl(SSUSB_OTG_STS) & <API key>){
msleep(1);
printk(KERN_ERR "[OTG_H] DMA in used\n");
}
writel(SSUSB_CHG_B_ROLE_B, SSUSB_OTG_STS);
printk(KERN_ERR "[OTG_H]alert device done\n");
}
}
g_port_connect = false;
mb() ;
printk(KERN_ERR "[OTG_H] handle_port_status, <API key>, g_port_connect is %d\n", g_port_connect);
}
if(port_status & (<API key> << 16)){
xhci_dbg(xhci, "port link status changed, wake up \n");
//udelay(1000);
}
if(port_status & (<API key> << 16)){
xhci_err(xhci, "port over current changed\n");
g_port_occ = true;
mb() ;
}
if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME){
xhci_dbg(xhci, "Change resume\n");
g_port_resume = 1;
mb() ;
}
if ((temp & PORT_PLC)){
xhci_dbg(xhci, "Change PLS(%d)\n", (temp & PORT_PLS_MASK) >> 5);
g_port_plc = 1;
mb() ;
}
<API key>(xhci, port_id, temp);
/* Update event ring dequeue pointer before dropping the lock */
mtktest_inc_deq(xhci, xhci->event_ring, true);
<API key>(xhci);
}
/*
* If this function returns an error condition, it means it got a Transfer
* event with a corrupted Slot ID, Endpoint ID, or TRB DMA address.
* At this point, the host controller is probably hosed and should be reset.
*/
static int handle_tx_event(struct xhci_hcd *xhci,
struct xhci_transfer_event *event)
{
struct xhci_virt_device *xdev;
struct xhci_virt_ep *ep;
struct xhci_ring *ep_ring;
unsigned int slot_id;
int ep_index;
struct xhci_td *td = NULL;
dma_addr_t event_dma;
struct xhci_segment *event_seg;
union xhci_trb *event_trb;
struct urb *urb = NULL;
int status = -EINPROGRESS;
struct xhci_ep_ctx *ep_ctx;
u32 trb_comp_code;
int i, ret;
char *tmp;
trb_comp_code = GET_COMP_CODE(event->transfer_len);
xhci_dbg(xhci, "Complete code(%d)\n", trb_comp_code);
#if 1
if(trb_comp_code == COMP_UNDERRUN || trb_comp_code == COMP_OVERRUN){
if(trb_comp_code == COMP_UNDERRUN){
//xhci_err(xhci, "underrun event on endpoint\n");
}
else if(trb_comp_code == COMP_OVERRUN){
//xhci_err(xhci, "overrun event on endpoint\n");
}
goto cleanup;
}
#endif
#if 0
if (trb_comp_code == COMP_STOP_INVAL ||
trb_comp_code == COMP_STOP) {
/* The Endpoint Stop Command completion will take care of any
* stopped TDs. A stopped TD may be restarted, so don't update
* the ring dequeue pointer or take this TD off any lists yet.
*/
g_cmd_status = CMD_DONE;
goto cleanup;
}
#endif
#if 1
slot_id = TRB_TO_SLOT_ID(event->flags);
xdev = xhci->devs[slot_id];
if (!xdev) {
xhci_err(xhci, "[ERROR] Transfer event pointed to bad slot\n");
return -ENODEV;
}
/* Endpoint ID is 1 based, our index is zero based */
ep_index = TRB_TO_EP_ID(event->flags) - 1;
xhci_dbg(xhci, "ep index = %d\n", ep_index);
ep = &xdev->eps[ep_index];
ep_ring = <API key>(ep, event->buffer);
ep_ctx = <API key>(xhci, xdev->out_ctx, ep_index);
if (!ep_ring || (ep_ctx->ep_info & EP_STATE_MASK) == EP_STATE_DISABLED) {
xhci_err(xhci, "[ERROR] Transfer event for disabled endpoint "
"or incorrect stream ring\n");
return -ENODEV;
}
event_dma = event->buffer;
/* This TRB should be in the TD at the head of this ring's TD list */
xhci_dbg(xhci, "checking for list empty\n");
if (list_empty(&ep_ring->td_list)) {
if(!<API key>){
xhci_warn(xhci, "WARN Event TRB for slot %d ep %d with no TDs queued?\n",
TRB_TO_SLOT_ID(event->flags), ep_index);
xhci_warn(xhci, "Event TRB(0x%p: 0x%llx 0x%x 0x%x\n"
, event, event->buffer, event->transfer_len, event->flags);
xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
(unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
<API key>(xhci, (union xhci_trb *) event);
}
urb = NULL;
goto cleanup;
}
xhci_dbg(xhci, "getting list entry\n");
td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
/* Is this a TRB in the currently executing TD? */
event_seg = mtktest_trb_in_td(ep_ring->deq_seg, ep_ring->dequeue,
td->last_trb, event_dma);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
if (!event_seg) {
/* HC is busted, give up! */
xhci_err(xhci, "[ERROR] Transfer event TRB DMA ptr not part of current TD\n");
return -ESHUTDOWN;
}
event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)];
xhci_dbg(xhci, "deg_seg_dma(0x%p)trb(0x%p), dequeue(0x%p), td(0x%p), last_trb(0x%p), event_seg_dma(0x%p), event_dma(0x%p)trb(0x%p)\n",
(void *)(unsigned long)ep_ring->deq_seg->dma, ep_ring->deq_seg->trbs, ep_ring->dequeue, td, td->last_trb, (void *)(unsigned long)event_seg->dma, (void *)(unsigned long)event_dma, event_trb);
xhci_dbg(xhci, "Event TRB with TRB type ID %u\n",
(unsigned int) (event->flags & TRB_TYPE_BITMASK)>>10);
xhci_dbg(xhci, "Offset 0x00 (buffer lo) = 0x%x\n",
lower_32_bits(event->buffer));
xhci_dbg(xhci, "Offset 0x04 (buffer hi) = 0x%x\n",
upper_32_bits(event->buffer));
xhci_dbg(xhci, "Offset 0x08 (transfer length) = 0x%x\n",
(unsigned int) event->transfer_len);
xhci_dbg(xhci, "Offset 0x0C (flags) = 0x%x\n",
(unsigned int) event->flags);
/* Look for common error cases */
trb_comp_code = GET_COMP_CODE(event->transfer_len);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
// xhci_dbg(xhci, "td->urb 0x%x\n", td->urb);
switch (trb_comp_code) {
/* Skip codes that require special handling depending on
* transfer type
*/
case COMP_SUCCESS:
#if 0
if(<API key>(&td->urb->ep->desc) && g_con_is_enter){
udelay(g_con_delay_us);
f_port_set_pls(g_port_id, g_con_enter_ux);
udelay(100);
f_port_set_pls((int)g_port_id, 0);
}
#endif
if(!<API key>(&td->urb->ep->desc)){
td->urb->actual_length = td->urb-><API key> - GET_TRANSFER_LENGTH(event->transfer_len);
status = 0;
//td->urb->status = 0;
xhci_dbg(xhci, "urb buffer len(%d), event trb len(%d)\n",
td->urb-><API key>, GET_TRANSFER_LENGTH(event->transfer_len));
}
break;
case COMP_SHORT_TX:
if(!<API key>(&td->urb->ep->desc)){
td->urb->actual_length = td->urb-><API key> - GET_TRANSFER_LENGTH(event->transfer_len);
status = 0;
//td->urb->status = 0;
}
break;
case COMP_STOP:
xhci_dbg(xhci, "Stopped on Transfer TRB\n");
break;
case COMP_STOP_INVAL:
xhci_dbg(xhci, "Stopped on No-op or Link TRB\n");
break;
case COMP_STALL:
xhci_warn(xhci, "WARN: Stalled endpoint\n");
ep->ep_state |= EP_HALTED;
status = -EPIPE;
//td->urb->status = -EPIPE;
break;
case COMP_TRB_ERR:
xhci_warn(xhci, "WARN: TRB error on endpoint\n");
status = -EILSEQ;
//td->urb->status = -EILSEQ;
break;
case COMP_SPLIT_ERR:
case COMP_TX_ERR:
xhci_warn(xhci, "WARN: transfer error on endpoint\n");
status = -EPROTO;
//td->urb->status = -EPROTO;
break;
case COMP_BABBLE:
xhci_warn(xhci, "WARN: babble error on endpoint, ep_idx %d\n", ep_index);
status = -EOVERFLOW;
//td->urb->status = -EOVERFLOW;
break;
case COMP_DB_ERR:
xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n");
status = -ENOSR;
//td->urb->status = -ENOSR;
break;
case COMP_BW_OVER:
xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n");
break;
case COMP_BUFF_OVER:
xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n");
break;
case COMP_UNDERRUN:
/*
* When the Isoch ring is empty, the xHC will generate
* a Ring Overrun Event for IN Isoch endpoint or Ring
* Underrun Event for OUT Isoch endpoint.
*/
xhci_dbg(xhci, "underrun event on endpoint\n");
if (!list_empty(&ep_ring->td_list))
xhci_dbg(xhci, "Underrun Event for slot %d ep %d "
"still with TDs queued?\n",
TRB_TO_SLOT_ID(event->flags), ep_index);
break;
case COMP_OVERRUN:
xhci_dbg(xhci, "overrun event on endpoint\n");
if (!list_empty(&ep_ring->td_list))
xhci_dbg(xhci, "Overrun Event for slot %d ep %d "
"still with TDs queued?\n",
TRB_TO_SLOT_ID(event->flags), ep_index);
break;
case COMP_MISSED_INT:
/*
* When encounter missed service error, one or more isoc tds
* may be missed by xHC.
* Set skip flag of the ep_ring; Complete the missed tds as
* short transfer when process the ep_ring next time.
*/
xhci_dbg(xhci, "Miss service interval error, set skip flag\n");
break;
default:
if (<API key>(xhci, trb_comp_code)) {
//urb->status = 0;
status = 0 ;
break;
}
xhci_warn(xhci, "ERROR Unknown event condition, HC probably busted, comp_code %d\n", trb_comp_code);
urb = NULL;
return -ENODEV;
}
/* Now update the urb's actual_length and give back to
* the core
*/
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
if (<API key>(&td->urb->ep->desc)){
ret = process_ctrl_td(xhci, td, event_trb, event, ep,
&status);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
}else if (<API key>(&td->urb->ep->desc)){
ret = process_isoc_td(xhci, td, event_trb, event, ep,
&status);
}else{
ret = <API key>(xhci, td, event_trb, event,
ep, &status);
}
#if 0
/* Update ring dequeue pointer */
while (ep_ring->dequeue != td->last_trb)
mtktest_inc_deq(xhci, ep_ring, false);
mtktest_inc_deq(xhci, ep_ring, false);
#endif
#if 0
urb = td->urb;
list_del(&td->td_list);
if (<API key>(&urb->ep->desc) ||
(trb_comp_code != COMP_STALL &&
trb_comp_code != COMP_BABBLE)) {
kfree(td);
}
#endif
#if 0
//td cleanup
list_del(&td->td_list);
/* Was this TD slated to be cancelled but completed anyway? */
if (!list_empty(&td->cancelled_td_list))
list_del(&td->cancelled_td_list);
/* Leave the TD around for the reset endpoint function to use
* (but only if it's not a control endpoint, since we already
* queued the Set TR dequeue pointer command for stalled
* control endpoints).
*/
if (<API key>(&urb->ep->desc) ||
(trb_comp_code != COMP_STALL &&
trb_comp_code != COMP_BABBLE)) {
kfree(td);
}
#endif
#if 0
if(dev_list[0] && dev_list[0]->slot_id==slot_id){
xhci_dbg(xhci, "dev 0 slot_id %d trans done\n", slot_id);
g_trans_status1 = TRANS_DONE;
}
else if(dev_list[1] && dev_list[1]->slot_id==slot_id){
xhci_dbg(xhci, "dev 1 slot_id %d trans done\n", slot_id);
g_trans_status2 = TRANS_DONE;
}
else if(dev_list[2] && dev_list[2]->slot_id==slot_id){
xhci_dbg(xhci, "dev 2 slot_id %d trans done\n", slot_id);
g_trans_status3 = TRANS_DONE;
}
else if(dev_list[3] && dev_list[3]->slot_id==slot_id){
xhci_dbg(xhci, "dev 3 slot_id %d trans done\n", slot_id);
g_trans_status4 = TRANS_DONE;
}
#endif
#if 0
if(ep_index == 1 || ep_index == 2 || (dev_list[0] && dev_list[0]->slot_id==slot_id)){
g_trans_status1 = TRANS_DONE;
}
else if(ep_index == 3 || ep_index == 4 || (dev_list[1] && dev_list[1]->slot_id==slot_id)){
g_trans_status2 = TRANS_DONE;
}
else if(ep_index == 5 || ep_index == 6 || (dev_list[2] && dev_list[2]->slot_id==slot_id)){
g_trans_status3 = TRANS_DONE;
}
else if(ep_index == 7 || ep_index == 8 || (dev_list[3] && dev_list[3]->slot_id==slot_id)){
g_trans_status4 = TRANS_DONE;
}
#endif
#endif
cleanup:
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
mtktest_inc_deq(xhci, xhci->event_ring, true);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
<API key>(xhci);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p, td->urb->status is %d\n", td, td->last_trb , td->urb->status) ;
//xhci_dbg(xhci, "set td->urb->status = status %d\n", status) ;
if (ret == FINISH_TD_CALL){
td->urb->status = status; // let the test driver can call the <API key> after whole dequeue is done
}
/* FIXME for multi-TD URBs (who have buffers bigger than 64MB) */
return 0;
}
int <API key>(struct xhci_hcd *xhci){
union xhci_trb *event;
struct xhci_generic_trb *generic_event;
int update_ptrs = 1;
int ret;
event = xhci->event_ring->dequeue;
printk(KERN_ERR "[OTG_H]<API key>: %x\n", event->event_cmd.flags);
#if 1
if(g_event_full){
struct xhci_generic_trb *event_trb = &event->generic;
if(GET_COMP_CODE(event_trb->field[2]) == COMP_ER_FULL){
xhci_dbg(xhci, "Got event ring full\n");
g_got_event_full = true;
}
else{
xhci_dbg(xhci, "increase SW dequeue pointer\n");
mtktest_inc_deq(xhci, xhci->event_ring, true);
return 0;
}
}
#endif
if((event->event_cmd.flags & TRB_TYPE_BITMASK) == TRB_TYPE(TRB_MFINDEX_WRAP)){
g_mfindex_event++;
}
/* Does the HC or OS own the TRB? */
if ((event->event_cmd.flags & TRB_CYCLE) !=
xhci->event_ring->cycle_state) {
xhci->error_bitmask |= 1 << 2;
return 0;
}
xhci_dbg(xhci, "%s - OS owns TRB\n", __func__);
xhci_dbg(xhci, "TRB TYPE(0x%x)\n", TRB_FIELD_TO_TYPE(event->event_cmd.flags));
/* FIXME: Handle more event types. */
switch ((event->event_cmd.flags & TRB_TYPE_BITMASK)) {
case TRB_TYPE(TRB_COMPLETION):
#if 1
xhci_dbg(xhci, "%s - calling <API key>\n", __func__);
<API key>(xhci, &event->event_cmd);
xhci_dbg(xhci, "%s - returned from <API key>\n", __func__);
#endif
break;
case TRB_TYPE(TRB_PORT_STATUS):
#if 1
xhci_dbg(xhci, "%s - calling handle_port_status\n", __func__);
handle_port_status(xhci, event);
xhci_dbg(xhci, "%s - returned from handle_port_status\n", __func__);
update_ptrs = 0;
#endif
break;
case TRB_TYPE(TRB_TRANSFER):
#if 1
xhci_dbg(xhci, "%s - calling handle_tx_event\n", __func__);
ret = handle_tx_event(xhci, &event->trans_event);
xhci_dbg(xhci, "%s - returned from handle_tx_event\n", __func__);
if (ret < 0)
xhci->error_bitmask |= 1 << 9;
else
update_ptrs = 0;
#endif
break;
case TRB_TYPE(TRB_DEV_NOTE):
xhci_dbg(xhci, "Got device notification packet\n");
generic_event = &event->generic;
xhci_dbg(xhci, "fields 0x%x 0x%x 0x%x 0x%x\n"
, generic_event->field[0], generic_event->field[1], generic_event->field[2], generic_event->field[3]);
g_dev_notification = TRB_DEV_NOTE_TYEP(generic_event->field[0]);
xhci_dbg(xhci, "notification type %d\n", g_dev_notification);
g_dev_not_value = <API key>(generic_event->field[0])
| (generic_event->field[1] << 32);
xhci_dbg(xhci, "notification value %ld\n", g_dev_not_value);
break;
default:
break;
#if 0
if ((event->event_cmd.flags & TRB_TYPE_BITMASK) >= TRB_TYPE(48))
handle_vendor_event(xhci, event);
else
xhci->error_bitmask |= 1 << 3;
#endif
}
/* Any of the above functions may drop and re-acquire the lock, so check
* to make sure a watchdog timer didn't mark the host as non-responsive.
*/
if (update_ptrs) {
/* Update SW and HC event ring dequeue pointer */
mtktest_inc_deq(xhci, xhci->event_ring, true);
<API key>(xhci);
}
/* Are there more items on the event ring? */
// USBIF OTG
// <API key>(xhci);
return 1;
}
/*
* Generic function for queueing a TRB on a ring.
* The caller must have checked to make sure there's room on the ring.
*
* @more_trbs_coming: Will you enqueue more TRBs before calling
* prepare_transfer()?
*/
static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring,
bool consumer, bool more_trbs_coming,
u32 field1, u32 field2, u32 field3, u32 field4)
{
struct xhci_generic_trb *trb;
trb = &ring->enqueue->generic;
trb->field[0] = field1;
trb->field[1] = field2;
trb->field[2] = field3;
trb->field[3] = field4;
xhci_dbg(xhci, "Dump TRB: 0x%x 0x%x 0x%x 0x%x\n", trb->field[0], trb->field[1], trb->field[2], trb->field[3]);
inc_enq(xhci, ring, consumer, more_trbs_coming);
}
/*
* Does various checks on the endpoint ring, and makes it ready to queue num_trbs.
* FIXME allocate segments if the ring is full.
*/
static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring,
u32 ep_state, unsigned int num_trbs, gfp_t mem_flags)
{
/* Make sure the endpoint has been added to xHC schedule */
xhci_dbg(xhci, "Endpoint state = 0x%x\n", ep_state);
switch (ep_state) {
case EP_STATE_DISABLED:
/*
* USB core changed config/interfaces without notifying us,
* or hardware is reporting the wrong state.
*/
xhci_warn(xhci, "WARN urb submitted to disabled ep\n");
return -ENOENT;
case EP_STATE_ERROR:
xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n");
/* FIXME event handling code for error needs to clear it */
/* XXX not sure if this should be -ENOENT or not */
return -EINVAL;
case EP_STATE_HALTED:
xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n");
case EP_STATE_STOPPED:
case EP_STATE_RUNNING:
break;
default:
xhci_err(xhci, "[ERROR] unknown endpoint state for ep\n");
/*
* FIXME issue Configure Endpoint command to try to get the HC
* back into a known state.
*/
return -EINVAL;
}
if (!room_on_ring(xhci, ep_ring, num_trbs)) {
/* FIXME allocate more room */
xhci_err(xhci, "[ERROR] no room on ep ring, num_trbs %d\n", num_trbs);
return -ENOMEM;
}
if (enqueue_is_link_trb(ep_ring)) {
struct xhci_ring *ring = ep_ring;
union xhci_trb *next;
xhci_dbg(xhci, "prepare_ring: pointing to link trb\n");
next = ring->enqueue;
while (last_trb(xhci, ring, ring->enq_seg, next)) {
/* If we're not dealing with 0.95 hardware,
* clear the chain bit.
*/
if (!xhci_link_trb_quirk(xhci))
next->link.control &= ~TRB_CHAIN;
else
next->link.control |= TRB_CHAIN;
wmb();
next->link.control ^= (u32) TRB_CYCLE;
/* Toggle the cycle bit after the last ring segment. */
if (<API key>(xhci, ring, ring->enq_seg, next)) {
ring->cycle_state = (ring->cycle_state ? 0 : 1);
if (!in_interrupt()) {
xhci_dbg(xhci, "queue_trb: Toggle cycle "
"state for ring %p = %i\n",
ring, (unsigned int)ring->cycle_state);
}
}
ring->enq_seg = ring->enq_seg->next;
ring->enqueue = ring->enq_seg->trbs;
next = ring->enqueue;
}
}
return 0;
}
static int prepare_transfer(struct xhci_hcd *xhci,
struct xhci_virt_device *xdev,
unsigned int ep_index,
unsigned int stream_id,
unsigned int num_trbs,
struct urb *urb,
unsigned int td_index,
gfp_t mem_flags)
{
int ret;
struct urb_priv *urb_priv;
struct xhci_td *td;
struct xhci_ring *ep_ring;
struct xhci_ep_ctx *ep_ctx = <API key>(xhci, xdev->out_ctx, ep_index);
ep_ring = <API key>(xdev, ep_index, stream_id);
if (!ep_ring) {
xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n",
stream_id);
return -EINVAL;
}
xhci_dbg(xhci, "prepare transfer EP[%d]\n", ep_index);
ret = prepare_ring(xhci, ep_ring,
ep_ctx->ep_info & EP_STATE_MASK,
num_trbs, mem_flags);
if (ret)
return ret;
urb_priv = urb->hcpriv;
td = urb_priv->td[td_index];
INIT_LIST_HEAD(&td->td_list);
INIT_LIST_HEAD(&td->cancelled_td_list);
td->urb = urb;
list_add_tail(&td->td_list, &ep_ring->td_list);
xhci_dbg(xhci, "td(0x%p), prev(0x%p), next(0x%p)\n", td, td->td_list.prev, td->td_list.next);
td->start_seg = ep_ring->enq_seg;
td->first_trb = ep_ring->enqueue;
urb_priv->td[td_index] = td;
return 0;
}
static unsigned int <API key>(struct xhci_hcd *xhci, struct urb *urb)
{
int num_sgs, num_trbs, running_total, temp, i;
struct scatterlist *sg;
sg = NULL;
num_sgs = urb->num_sgs;
temp = urb-><API key>;
xhci_dbg(xhci, "count sg list trbs: \n");
num_trbs = 0;
for_each_sg(urb->sg, sg, num_sgs, i) {
unsigned int previous_total_trbs = num_trbs;
unsigned int len = sg_dma_len(sg);
/* Scatter gather list entries may cross 64KB boundaries */
running_total = TRB_MAX_BUFF_SIZE -
(sg_dma_address(sg) & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
if (running_total != 0)
num_trbs++;
/* How many more 64KB chunks to transfer, how many more TRBs? */
while (running_total < sg_dma_len(sg)) {
num_trbs++;
running_total += TRB_MAX_BUFF_SIZE;
}
xhci_dbg(xhci, " sg #%d: dma = %#llx, len = %#x (%d), num_trbs = %d\n",
i, (unsigned long long)sg_dma_address(sg),
len, len, num_trbs - previous_total_trbs);
len = min_t(int, len, temp);
temp -= len;
if (temp == 0)
break;
}
xhci_dbg(xhci, "\n");
if (!in_interrupt())
dev_dbg(&urb->dev->dev, "ep %#x - urb len = %d, sglist used, num_trbs = %d\n",
urb->ep->desc.bEndpointAddress,
urb-><API key>,
num_trbs);
return num_trbs;
}
static void check_trb_math(struct urb *urb, int num_trbs, int running_total)
{
if (num_trbs != 0)
dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated number of "
"TRBs, %d left\n", __func__,
urb->ep->desc.bEndpointAddress, num_trbs);
if (running_total != urb-><API key>)
dev_dbg(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, "
"queued %#x (%d), asked for %#x (%d)\n",
__func__,
urb->ep->desc.bEndpointAddress,
running_total, running_total,
urb-><API key>,
urb-><API key>);
}
static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id,
unsigned int ep_index, unsigned int stream_id, int start_cycle,
struct xhci_generic_trb *start_trb, struct xhci_td *td)
{
/*
* Pass all the TRBs to the hardware at once and make sure this write
* isn't reordered.
*/
wmb();
if (start_cycle)
start_trb->field[3] |= start_cycle;
else
start_trb->field[3] &= ~0x1;
ring_ep_doorbell(xhci, slot_id, ep_index, stream_id);
}
/*
* xHCI uses normal TRBs for both bulk and interrupt. When the interrupt
* endpoint is to be serviced, the xHC will consume (at most) one TD. A TD
* (comprised of sg list entries) can take several service intervals to
* transmit.
*/
int <API key>(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_ep_ctx *ep_ctx = <API key>(xhci,
xhci->devs[slot_id]->out_ctx, ep_index);
int xhci_interval;
int ep_interval;
xhci_interval = <API key>(ep_ctx->ep_info);
ep_interval = urb->interval;
/* Convert to microframes */
if (urb->dev->speed == USB_SPEED_LOW ||
urb->dev->speed == USB_SPEED_FULL)
ep_interval *= 8;
/* FIXME change this to a warning and a suggestion to use the new API
* to set the polling interval (once the API is added).
*/
if (xhci_interval != ep_interval) {
if (!printk_ratelimit())
dev_dbg(&urb->dev->dev, "Driver uses different interval"
" (%d microframe%s) than xHCI "
"(%d microframe%s)\n",
ep_interval,
ep_interval == 1 ? "" : "s",
xhci_interval,
xhci_interval == 1 ? "" : "s");
urb->interval = xhci_interval;
/* Convert back to frames for LS/FS devices */
if (urb->dev->speed == USB_SPEED_LOW ||
urb->dev->speed == USB_SPEED_FULL)
urb->interval /= 8;
}
return <API key>(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
}
/*
* The TD size is the number of bytes remaining in the TD (including this TRB),
* right shifted by 10.
* It must fit in bits 21:17, so it can't be bigger than 31.
*/
static u32 xhci_td_remainder(unsigned int td_transfer_size, unsigned int td_running_total
, unsigned int maxp, unsigned trb_buffer_length)
{
u32 max = 31;
int remainder, td_packet_count, packet_transferred;
//0 for the last TRB
//FIXME: need to workaround if there is ZLP in this TD
if(td_running_total + trb_buffer_length == td_transfer_size)
return 0;
//FIXME: need to take care of high-bandwidth (MAX_ESIT)
packet_transferred = (td_running_total /*+ trb_buffer_length*/) / maxp;
td_packet_count = DIV_ROUND_UP(td_transfer_size, maxp);
remainder = td_packet_count - packet_transferred;
if(remainder > max)
return max << 17;
else
return remainder << 17;
}
static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_ring *ep_ring;
unsigned int num_trbs;
struct urb_priv *urb_priv;
struct xhci_td *td;
struct scatterlist *sg;
int num_sgs;
int trb_buff_len, this_sg_len, running_total;
bool first_trb;
u64 addr;
int max_packet;
bool more_trbs_coming;
bool zlp;
// int td_packet_count, trb_tx_len_sum, packet_transferred, trb_residue, td_size;
struct xhci_generic_trb *start_trb;
int start_cycle;
ep_ring = <API key>(xhci, urb);
if (!ep_ring)
return -EINVAL;
num_trbs = <API key>(xhci, urb);
num_sgs = urb->num_sgs;
trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id],
ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags);
if (trb_buff_len < 0)
return trb_buff_len;
urb_priv = urb->hcpriv;
td = urb_priv->td[0];
zlp = false;
/* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */
switch(urb->dev->speed){
case USB_SPEED_SUPER:
max_packet = urb->ep->desc.wMaxPacketSize;
break;
case USB_SPEED_HIGH:
case USB_SPEED_FULL:
case USB_SPEED_LOW:
max_packet = urb->ep->desc.wMaxPacketSize & 0x7ff;
break;
}
if((urb->transfer_flags & URB_ZERO_PACKET)
&& ((urb-><API key> % max_packet) == 0)){
zlp = true;
}
#if 0
td_packet_count = urb-><API key>/max_packet + (urb-><API key>%max_packet > 0 ? 1 : 0);
trb_tx_len_sum = 0;
packet_transferred = 0;
#endif
/*
* Don't give the first TRB to the hardware (by toggling the cycle bit)
* until we've finished creating all the other TRBs. The ring's cycle
* state may change as we enqueue the other TRBs, so save it too.
*/
start_trb = &ep_ring->enqueue->generic;
start_cycle = ep_ring->cycle_state;
running_total = 0;
/*
* How much data is in the first TRB?
*
* There are three forces at work for TRB buffer pointers and lengths:
* 1. We don't want to walk off the end of this sg-list entry buffer.
* 2. The transfer length that the driver requested may be smaller than
* the amount of memory allocated for this scatter-gather list.
* 3. TRBs buffers can't cross 64KB boundaries.
*/
sg = urb->sg;
addr = (u64) sg_dma_address(sg);
this_sg_len = sg_dma_len(sg);
trb_buff_len = TRB_MAX_BUFF_SIZE -
(addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
if (trb_buff_len > urb-><API key>)
trb_buff_len = urb-><API key>;
xhci_dbg(xhci, "First length to xfer from 1st sglist entry = %u\n",
trb_buff_len);
first_trb = true;
/* Queue the first TRB, even if it's zero-length */
do {
u32 field = 0;
u32 length_field = 0;
u32 remainder = 0;
/* Don't change the cycle bit of the first TRB until later */
if (first_trb){
first_trb = false;
if (start_cycle == 0)
field |= 0x1;
}
else
field |= ep_ring->cycle_state;
/* Chain all the TRBs together; clear the chain bit in the last
* TRB to indicate it's the last TRB in the chain.
*/
if (num_trbs > 1 || zlp) {
field |= TRB_CHAIN;
} else {
/* FIXME - add check for ZERO_PACKET flag before this */
td->last_trb = ep_ring->enqueue;
field |= TRB_IOC;
}
xhci_dbg(xhci, " sg entry: dma = %#x, len = %#x (%d), "
"64KB boundary at %#x, end dma = %#x\n",
(unsigned int) addr, trb_buff_len, trb_buff_len,
(unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
(unsigned int) addr + trb_buff_len);
if (TRB_MAX_BUFF_SIZE -
(addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)) < trb_buff_len) {
xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n");
xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n",
(unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1),
(unsigned int) addr + trb_buff_len);
}
remainder = xhci_td_remainder(urb-><API key>, running_total, max_packet, trb_buff_len);
length_field = TRB_LEN(trb_buff_len) |
remainder |
TRB_INTR_TARGET(0);
if (num_trbs > 1 || zlp)
more_trbs_coming = true;
else
more_trbs_coming = false;
xhci_dbg(xhci, "queue trb, len[%d], addr[0x%llx]\n", trb_buff_len, addr);
queue_trb(xhci, ep_ring, false, more_trbs_coming,
lower_32_bits(addr),
upper_32_bits(addr),
length_field,
/* We always want to know if the TRB was short,
* or we won't get an event when it completes.
* (Unless we use event data TRBs, which are a
* waste of space and HC resources.)
*/
field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
--num_trbs;
running_total += trb_buff_len;
/* Calculate length for next transfer --
* Are we done queueing all the TRBs for this sg entry?
*/
this_sg_len -= trb_buff_len;
if (this_sg_len == 0) {
--num_sgs;
if (num_sgs == 0)
break;
sg = sg_next(sg);
addr = (u64) sg_dma_address(sg);
this_sg_len = sg_dma_len(sg);
} else {
addr += trb_buff_len;
}
trb_buff_len = TRB_MAX_BUFF_SIZE -
(addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
trb_buff_len = min_t(int, trb_buff_len, this_sg_len);
if (running_total + trb_buff_len > urb-><API key>)
trb_buff_len =
urb-><API key> - running_total;
} while (num_trbs > 0/*running_total < urb-><API key>*/);
if(zlp){
u32 field = 0;
u32 length_field = 0;
length_field = TRB_LEN(0) | TRB_INTR_TARGET(0);
field |= ep_ring->cycle_state;
field |= TRB_IOC;
td->last_trb = ep_ring->enqueue;
xhci_dbg(xhci, "queue trb, len[0x%x], addr[0x%llx]\n", length_field, addr);
queue_trb(xhci, ep_ring, false, false,
lower_32_bits(addr),
upper_32_bits(addr),
length_field,
/* We always want to know if the TRB was short,
* or we won't get an event when it completes.
* (Unless we use event data TRBs, which are a
* waste of space and HC resources.)
*/
field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
}
check_trb_math(urb, num_trbs, running_total);
giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
start_cycle, start_trb, td);
return 0;
}
/* This is very similar to what ehci-q.c qtd_fill() does */
int <API key>(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_ring *ep_ring;
struct urb_priv *urb_priv;
struct xhci_td *td;
int num_trbs;
struct xhci_generic_trb *start_trb;
bool first_trb;
bool more_trbs_coming;
int start_cycle;
u32 field, length_field;
int max_packet;
int running_total, trb_buff_len, ret;
u64 addr;
if (urb->num_sgs)
return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index);
ep_ring = <API key>(xhci, urb);
if (!ep_ring){
xhci_err(xhci, "<API key>, Get transfer ring failed\n");
return -EINVAL;
}
num_trbs = 0;
/* How much data is (potentially) left before the 64KB boundary? */
running_total = TRB_MAX_BUFF_SIZE -
(urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
/* If there's some data on this 64KB chunk, or we have to send a
* zero-length transfer, we need at least one TRB
*/
if (running_total != 0 || urb-><API key> == 0)
num_trbs++;
/* How many more 64KB chunks to transfer, how many more TRBs? */
while (running_total < urb-><API key>) {
num_trbs++;
running_total += TRB_MAX_BUFF_SIZE;
}
#if 1
/* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */
switch(urb->dev->speed){
case USB_SPEED_SUPER:
max_packet = urb->ep->desc.wMaxPacketSize;
break;
case USB_SPEED_HIGH:
case USB_SPEED_FULL:
case USB_SPEED_LOW:
max_packet = urb->ep->desc.wMaxPacketSize & 0x7ff;
break;
}
if((urb->transfer_flags & URB_ZERO_PACKET)
&& ((urb-><API key> % max_packet) == 0)){
num_trbs++;
}
#endif
if (!in_interrupt())
dev_dbg(&urb->dev->dev, "ep %#x - urb len = %#x (%d), addr = %#llx, num_trbs = %d\n",
urb->ep->desc.bEndpointAddress,
urb-><API key>,
urb-><API key>,
(unsigned long long)urb->transfer_dma,
num_trbs);
ret = prepare_transfer(xhci, xhci->devs[slot_id],
ep_index, urb->stream_id,
num_trbs, urb, 0, mem_flags);
if (ret < 0)
return ret;
urb_priv = urb->hcpriv;
td = urb_priv->td[0];
/*
* Don't give the first TRB to the hardware (by toggling the cycle bit)
* until we've finished creating all the other TRBs. The ring's cycle
* state may change as we enqueue the other TRBs, so save it too.
*/
start_trb = &ep_ring->enqueue->generic;
start_cycle = ep_ring->cycle_state;
running_total = 0;
/* How much data is in the first TRB? */
addr = (u64) urb->transfer_dma;
trb_buff_len = TRB_MAX_BUFF_SIZE -
(urb->transfer_dma & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
if (urb-><API key> < trb_buff_len)
trb_buff_len = urb-><API key>;
first_trb = true;
/* Queue the first TRB, even if it's zero-length */
do {
u32 remainder = 0;
field = 0;
/* Don't change the cycle bit of the first TRB until later */
if (first_trb){
first_trb = false;
if (start_cycle == 0)
field |= 0x1;
}
else
field |= ep_ring->cycle_state;
/* Chain all the TRBs together; clear the chain bit in the last
* TRB to indicate it's the last TRB in the chain.
*/
if (num_trbs > 1) {
field |= TRB_CHAIN;
} else {
/* FIXME - add check for ZERO_PACKET flag before this */
td->last_trb = ep_ring->enqueue;
field |= TRB_IOC;
if(g_is_bei){
field |= TRB_BEI;
}
}
remainder = xhci_td_remainder(urb-><API key>, running_total, max_packet, trb_buff_len);
length_field = TRB_LEN(trb_buff_len) |
remainder |
TRB_INTR_TARGET(0);
if (num_trbs > 1)
more_trbs_coming = true;
else
more_trbs_coming = false;
// xhci_dbg(xhci, "queue trb, len[%d], addr[0x%x]\n", trb_buff_len, addr);
if(g_idt_transfer && !usb_endpoint_dir_in(&urb->ep->desc)){
struct xhci_generic_trb *trb;
u32 *idt_data;
idt_data = urb->transfer_buffer;
xhci_err(xhci, "idt_data: 0x%p\n", idt_data);
trb = &ep_ring->enqueue->generic;
trb->field[0] = *idt_data;
idt_data++;
trb->field[1] = *idt_data;
trb->field[2] = length_field;
trb->field[3] = field | TRB_ISP | TRB_TYPE(TRB_NORMAL) | TRB_IDT;
xhci_dbg(xhci, "Dump TRB: 0x%x 0x%x 0x%x 0x%x\n", trb->field[0], trb->field[1], trb->field[2], trb->field[3]);
inc_enq(xhci, ep_ring, false, more_trbs_coming);
}
else{
queue_trb(xhci, ep_ring, false, more_trbs_coming,
lower_32_bits(addr),
upper_32_bits(addr),
length_field,
/* We always want to know if the TRB was short,
* or we won't get an event when it completes.
* (Unless we use event data TRBs, which are a
* waste of space and HC resources.)
*/
field | TRB_ISP | TRB_TYPE(TRB_NORMAL));
}
--num_trbs;
running_total += trb_buff_len;
/* Calculate length for next transfer */
addr += trb_buff_len;
trb_buff_len = urb-><API key> - running_total;
if (trb_buff_len > TRB_MAX_BUFF_SIZE)
trb_buff_len = TRB_MAX_BUFF_SIZE;
} while (num_trbs > 0/*running_total < urb-><API key>*/);
check_trb_math(urb, num_trbs, running_total);
if(g_td_to_noop){
if (start_cycle)
start_trb->field[3] |= start_cycle;
else
start_trb->field[3] &= ~0x1;
td_to_noop(xhci, ep_ring, td);
list_del(&td->td_list);
return 0;
}
giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
start_cycle, start_trb, td);
return 0;
}
static int <API key>(struct xhci_hcd *xhci,
struct urb *urb, int i)
{
int num_trbs = 0;
u64 addr, td_len, running_total;
addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset);
td_len = urb->iso_frame_desc[i].length;
running_total = TRB_MAX_BUFF_SIZE -
(addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
if (running_total != 0)
num_trbs++;
while (running_total < td_len) {
num_trbs++;
running_total += TRB_MAX_BUFF_SIZE;
}
return num_trbs;
}
/* This is for isoc transfer */
static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_ring *ep_ring;
struct urb_priv *urb_priv;
struct xhci_td *td;
int num_tds, trbs_per_td;
struct xhci_generic_trb *start_trb;
bool first_trb;
int start_cycle;
u32 field, length_field;
int running_total, trb_buff_len, td_len, td_remain_len, ret;
u64 start_addr, addr;
int i, j;
bool more_trbs_coming;
int max_packet;
int max_esit_payload;
int frame_id;
ep_ring = xhci->devs[slot_id]->eps[ep_index].ring;
num_tds = urb->number_of_packets;
if (num_tds < 1) {
xhci_dbg(xhci, "Isoc URB with zero packets?\n");
return -EINVAL;
}
if (!in_interrupt())
dev_dbg(&urb->dev->dev, "ep %#x - urb len = %#x (%d),"
" addr = %#llx, num_tds = %d\n",
urb->ep->desc.bEndpointAddress,
urb-><API key>,
urb-><API key>,
(unsigned long long)urb->transfer_dma,
num_tds);
start_addr = (u64) urb->transfer_dma;
start_trb = &ep_ring->enqueue->generic;
start_cycle = ep_ring->cycle_state;
switch(urb->dev->speed){
case USB_SPEED_SUPER:
max_packet = urb->ep->desc.wMaxPacketSize;
break;
case USB_SPEED_HIGH:
case USB_SPEED_FULL:
case USB_SPEED_LOW:
max_packet = urb->ep->desc.wMaxPacketSize & 0x7ff;
break;
}
/* Queue the first TRB, even if it's zero-length */
for (i = 0; i < num_tds; i++) {
first_trb = true;
running_total = 0;
addr = start_addr + urb->iso_frame_desc[i].offset;
td_len = urb->iso_frame_desc[i].length;
td_remain_len = td_len;
trbs_per_td = <API key>(xhci, urb, i);
ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index,
urb->stream_id, trbs_per_td, urb, i, mem_flags);
if (ret < 0)
return ret;
urb_priv = urb->hcpriv;
td = urb_priv->td[i];
for (j = 0; j < trbs_per_td; j++) {
u32 remainder = 0;
field = 0;
if (first_trb) {
/* Queue the isoc TRB */
field |= TRB_TYPE(TRB_ISOC);
/* Assume URB_ISO_ASAP is set */
if(g_iso_frame && i==0){
frame_id = xhci_readl(xhci, &xhci->run_regs->microframe_index) >> 3;
frame_id &= 0x7ff;
frame_id
if(frame_id <0){
frame_id = 0x7ff;
}
field |= ((frame_id) << 20);
xhci_err(xhci, "[DBG]start frame id = %d\n", frame_id);
}
else{
field |= TRB_SIA;
}
if (i == 0) {
if (start_cycle == 0)
field |= 0x1;
} else
field |= ep_ring->cycle_state;
first_trb = false;
} else {
/* Queue other normal TRBs */
field |= TRB_TYPE(TRB_NORMAL);
field |= ep_ring->cycle_state;
}
/* Chain all the TRBs together; clear the chain bit in
* the last TRB to indicate it's the last TRB in the
* chain.
*/
if (j < trbs_per_td - 1) {
field |= TRB_CHAIN;
more_trbs_coming = true;
} else {
td->last_trb = ep_ring->enqueue;
field |= TRB_IOC;
more_trbs_coming = false;
}
/* Calculate TRB length */
trb_buff_len = TRB_MAX_BUFF_SIZE -
(addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1));
if (trb_buff_len > td_remain_len)
trb_buff_len = td_remain_len;
// remainder = xhci_td_remainder(td_len - running_total);
remainder = xhci_td_remainder(td_len, running_total, max_packet, trb_buff_len);
length_field = TRB_LEN(trb_buff_len) |
remainder |
TRB_INTR_TARGET(0);
queue_trb(xhci, ep_ring, false, more_trbs_coming,
lower_32_bits(addr),
upper_32_bits(addr),
length_field,
/* We always want to know if the TRB was short,
* or we won't get an event when it completes.
* (Unless we use event data TRBs, which are a
* waste of space and HC resources.)
*/
field | TRB_ISP);
running_total += trb_buff_len;
addr += trb_buff_len;
td_remain_len -= trb_buff_len;
}
/* Check TD length */
if (running_total != td_len) {
xhci_err(xhci, "ISOC TD length unmatch\n");
return -EINVAL;
}
}
giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id,
start_cycle, start_trb, td);
return 0;
}
/*
* Check transfer ring to guarantee there is enough room for the urb.
* Update ISO URB start_frame and interval.
* Update interval as <API key> does. Just use xhci frame_index to
* update the urb->start_frame by now.
* Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input.
*/
int <API key>(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_virt_device *xdev;
struct xhci_ring *ep_ring;
struct xhci_ep_ctx *ep_ctx;
int start_frame;
int xhci_interval;
int ep_interval;
int num_tds, num_trbs, i;
int ret;
xdev = xhci->devs[slot_id];
ep_ring = xdev->eps[ep_index].ring;
ep_ctx = <API key>(xhci, xdev->out_ctx, ep_index);
num_trbs = 0;
num_tds = urb->number_of_packets;
for (i = 0; i < num_tds; i++)
num_trbs += <API key>(xhci, urb, i);
/* Check the ring to guarantee there is enough room for the whole urb.
* Do not insert any td of the urb to the ring if the check failed.
*/
ret = prepare_ring(xhci, ep_ring, ep_ctx->ep_info & EP_STATE_MASK,
num_trbs, mem_flags);
if (ret)
return ret;
start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index);
start_frame &= 0x3fff;
urb->start_frame = start_frame;
if (urb->dev->speed == USB_SPEED_LOW ||
urb->dev->speed == USB_SPEED_FULL)
urb->start_frame >>= 3;
xhci_interval = <API key>(ep_ctx->ep_info);
ep_interval = urb->interval;
/* Convert to microframes */
if (urb->dev->speed == USB_SPEED_LOW ||
urb->dev->speed == USB_SPEED_FULL)
ep_interval *= 8;
/* FIXME change this to a warning and a suggestion to use the new API
* to set the polling interval (once the API is added).
*/
if (xhci_interval != ep_interval) {
if (printk_ratelimit())
dev_dbg(&urb->dev->dev, "Driver uses different interval"
" (%d microframe%s) than xHCI "
"(%d microframe%s)\n",
ep_interval,
ep_interval == 1 ? "" : "s",
xhci_interval,
xhci_interval == 1 ? "" : "s");
urb->interval = xhci_interval;
/* Convert back to frames for LS/FS devices */
if (urb->dev->speed == USB_SPEED_LOW ||
urb->dev->speed == USB_SPEED_FULL)
urb->interval /= 8;
}
return xhci_queue_isoc_tx(xhci, GFP_ATOMIC, urb, slot_id, ep_index);
}
/* Caller must have locked xhci->lock */
int <API key>(struct xhci_hcd *xhci, gfp_t mem_flags,
struct urb *urb, int slot_id, unsigned int ep_index)
{
struct xhci_ring *ep_ring;
int num_trbs;
int ret;
struct usb_ctrlrequest *setup;
struct xhci_generic_trb *start_trb;
int start_cycle;
u32 field, length_field;
struct urb_priv *urb_priv;
struct xhci_td *td;
int max_packet;
int remainder;
u32 trt;
#if 0
xhci_dbg(xhci, "urb->ep->desc->bLength 0x%x\n", urb->ep->desc.bLength);
xhci_dbg(xhci, "urb->ep->desc->bDescriptorType 0x%x\n", urb->ep->desc.bDescriptorType);
xhci_dbg(xhci, "urb->ep->desc->bEndpointAddress 0x%x\n", urb->ep->desc.bEndpointAddress);
xhci_dbg(xhci, "urb->ep->desc->bmAttributes 0x%x\n", urb->ep->desc.bmAttributes);
xhci_dbg(xhci, "urb->ep->desc->wMaxPacketSize 0x%x\n", urb->ep->desc.wMaxPacketSize);
xhci_dbg(xhci, "urb->ep->desc->bInterval 0x%x\n", urb->ep->desc.bInterval);
xhci_dbg(xhci, "urb->ep->desc->bRefresh 0x%x\n", urb->ep->desc.bRefresh);
xhci_dbg(xhci, "urb->ep->desc->bSynchAddress 0x%x\n", urb->ep->desc.bSynchAddress);
xhci_dbg(xhci, "urb->setup_packet 0x%x\n", urb->setup_packet);
#endif
xhci_dbg(xhci, "<API key>\n");
ep_ring = <API key>(xhci, urb);
if (!ep_ring)
return -EINVAL;
/*
* Need to copy setup packet into setup TRB, so we can't use the setup
* DMA address.
*/
if (!urb->setup_packet)
return -EINVAL;
if (!in_interrupt())
xhci_dbg(xhci, "Queueing ctrl tx for slot id %d, ep %d\n",
slot_id, ep_index);
/* 1 TRB for setup, 1 for status */
num_trbs = 2;
/*
* Don't need to check if we need additional event data and normal TRBs,
* since data in control transfers will never get bigger than 16MB
* XXX: can we get a buffer that crosses 64KB boundaries?
*/
if (urb-><API key> > 0)
num_trbs++;
ret = prepare_transfer(xhci, xhci->devs[slot_id],
ep_index, urb->stream_id,
num_trbs, urb, 0, mem_flags);
if (ret < 0)
return ret;
urb_priv = urb->hcpriv;
td = urb_priv->td[0];
/*
* Don't give the first TRB to the hardware (by toggling the cycle bit)
* until we've finished creating all the other TRBs. The ring's cycle
* state may change as we enqueue the other TRBs, so save it too.
*/
start_trb = &ep_ring->enqueue->generic;
start_cycle = ep_ring->cycle_state;
#if 0
xhci_dbg(xhci, "start_trb 0x%x\n", &ep_ring->enqueue->generic);
xhci_dbg(xhci, "start_cycle 0x%x\n", ep_ring->cycle_state);
#endif
/* Queue setup TRB - see section 6.4.1.2.1 */
/* FIXME better way to translate setup_packet into two u32 fields? */
setup = (struct usb_ctrlrequest *) urb->setup_packet;
#if 0
xhci_dbg(xhci, "setup->bRequestType 0x%x\n", setup->bRequestType);
xhci_dbg(xhci, "setup->bRequest 0x%x\n", setup->bRequest);
xhci_dbg(xhci, "setup->wValue 0x%x\n", setup->wValue);
xhci_dbg(xhci, "setup->wIndex 0x%x\n", setup->wIndex);
xhci_dbg(xhci, "setup->wLength 0x%x\n", setup->wLength);
#endif
if(num_trbs ==2){
trt = TRB_TRT(TRT_NO_DATA);
}else if(setup->bRequestType & USB_DIR_IN){
trt = TRB_TRT(TRT_IN_DATA);
}else{
trt = TRB_TRT(TRT_OUT_DATA);
}
field = 0;
field |= TRB_IDT | TRB_TYPE(TRB_SETUP) | trt;
if (start_cycle == 0)
field |= 0x1;
queue_trb(xhci, ep_ring, false, true,
/* FIXME endianness is probably going to bite my ass here. */
setup->bRequestType | setup->bRequest << 8 | setup->wValue << 16,
setup->wIndex | setup->wLength << 16,
TRB_LEN(8) | TRB_INTR_TARGET(0),
/* Immediate data in pointer */
field);
/* If there's data, queue data TRBs */
field = 0;
// remainder = xhci_td_remainder(urb-><API key>, 0, max_packet, urb-><API key>);
length_field = TRB_LEN(urb-><API key>) |
// remainder |
TRB_INTR_TARGET(0);
if (urb-><API key> > 0) {
if (setup->bRequestType & USB_DIR_IN)
field |= TRB_DIR_IN;
queue_trb(xhci, ep_ring, false, true,
lower_32_bits(urb->transfer_dma),
upper_32_bits(urb->transfer_dma),
length_field,
/* Event on short tx */
field | TRB_ISP | TRB_TYPE(TRB_DATA) | ep_ring->cycle_state);
}
#if 1
max_packet = urb->ep->desc.wMaxPacketSize;
if((urb->transfer_flags & URB_ZERO_PACKET)
&& ((urb-><API key> % max_packet) == 0)){
if (setup->bRequestType & USB_DIR_IN)
field |= TRB_DIR_IN;
queue_trb(xhci, ep_ring, false, true,
lower_32_bits(urb->transfer_dma),
upper_32_bits(urb->transfer_dma),
0,
/* Event on short tx */
field | TRB_ISP | TRB_TYPE(TRB_DATA) | ep_ring->cycle_state);
}
#endif
/* Save the DMA address of the last TRB in the TD */
td->last_trb = ep_ring->enqueue;
xhci_dbg(xhci, "set the td 0x%p 's last_trb 0x%p to 0x%p\n", td, td->last_trb , ep_ring->enqueue) ;
/* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */
/* If the device sent data, the status stage is an OUT transfer */
if (urb-><API key> > 0 && setup->bRequestType & USB_DIR_IN)
field = 0;
else
field = TRB_DIR_IN;
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
queue_trb(xhci, ep_ring, false, false,
0,
0,
TRB_INTR_TARGET(0),
/* Event on completion */
field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
#if 1
giveback_first_trb(xhci, slot_id, ep_index, 0,
start_cycle, start_trb, td);
xhci_dbg(xhci, "td is 0x%p, last_trb is 0x%p\n", td, td->last_trb ) ;
#endif
return 0;
}
/* Generic function for queueing a command TRB on the command ring.
* Check to make sure there's room on the command ring for one command TRB.
* Also check that there's room reserved for commands that must not fail.
* If this is a command that must not fail, meaning <API key> = TRUE,
* then only check for the number of reserved spots.
* Don't decrement xhci-><API key> after we've queued the TRB
* because the command event handler may want to resubmit a failed command.
*/
static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2,
u32 field3, u32 field4, bool <API key>)
{
int reserved_trbs = xhci-><API key>;
int ret;
if (!<API key>)
reserved_trbs++;
ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING,
reserved_trbs, GFP_ATOMIC);
if (ret < 0) {
xhci_err(xhci, "[ERROR] No room for command on command ring\n");
if (<API key>)
xhci_err(xhci, "[ERROR] Reserved TRB counting for "
"unfailable commands failed.\n");
return ret;
}
queue_trb(xhci, xhci->cmd_ring, false, false, field1, field2, field3,
field4 | xhci->cmd_ring->cycle_state);
return 0;
}
/* Queue a no-op command on the command ring */
static int queue_cmd_noop(struct xhci_hcd *xhci)
{
return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_CMD_NOOP), false);
}
/*
* Place a no-op command on the command ring to test the command and
* event ring.
*/
void *<API key>(struct xhci_hcd *xhci)
{
if (queue_cmd_noop(xhci) < 0)
return NULL;
xhci->noops_submitted++;
return <API key>;
}
/*
* Place a no-op command on the command ring to test the command and
* event ring.
*/
void *<API key>(struct xhci_hcd *xhci)
{
if (queue_cmd_noop(xhci) < 0)
return NULL;
<API key>(xhci);
}
/* Queue a slot enable or disable request on the command ring */
int <API key>(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id)
{
return queue_command(xhci, 0, 0, 0,
TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false);
}
/* Queue an address device command TRB */
int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
u32 slot_id, char isBSR)
{
if(isBSR){
return queue_command(xhci, lower_32_bits(in_ctx_ptr),
upper_32_bits(in_ctx_ptr), 0,
TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id) | ADDRESS_TRB_BSR,
false);
}
else{
return queue_command(xhci, lower_32_bits(in_ctx_ptr),
upper_32_bits(in_ctx_ptr), 0,
TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id),
false);
}
}
int <API key>(struct xhci_hcd *xhci,
u32 field1, u32 field2, u32 field3, u32 field4)
{
return queue_command(xhci, field1, field2, field3, field4, false);
}
/* Queue a reset device command TRB */
int <API key>(struct xhci_hcd *xhci, u32 slot_id)
{
return queue_command(xhci, 0, 0, 0,
TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id),
false);
}
/* Queue a configure endpoint command TRB */
int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
u32 slot_id, bool <API key>)
{
return queue_command(xhci, lower_32_bits(in_ctx_ptr),
upper_32_bits(in_ctx_ptr), 0,
TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id),
<API key>);
}
int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
u32 slot_id, bool <API key>){
return queue_command(xhci, lower_32_bits(in_ctx_ptr),
upper_32_bits(in_ctx_ptr), 0,
TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id) | CONFIG_EP_TRB_DC,
<API key>);
}
/* Queue an evaluate context command TRB */
int <API key>(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr,
u32 slot_id)
{
return queue_command(xhci, lower_32_bits(in_ctx_ptr),
upper_32_bits(in_ctx_ptr), 0,
TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id),
false);
}
int <API key>(struct xhci_hcd *xhci, int slot_id,
unsigned int ep_index)
{
u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
u32 type = TRB_TYPE(TRB_STOP_RING);
//xhci_err(xhci, "[DBG] queue stop ep command, address 0x%x\n", xhci->cmd_ring->enqueue);
if(ep_index == 1){
if(TRB_FIELD_TO_TYPE(xhci->cmd_ring->enqueue->generic.field[3]) == TRB_LINK){
g_cmd_ring_pointer1 = (((int)xhci->cmd_ring->enqueue->link.segment_ptr) & 0xff0);
}
else{
g_cmd_ring_pointer1 = ((((int)(unsigned long)xhci->cmd_ring->enqueue) & 0xff0));
}
}
else if(ep_index == 2){
if(TRB_FIELD_TO_TYPE(xhci->cmd_ring->enqueue->generic.field[3]) == TRB_LINK){
g_cmd_ring_pointer2 = (((int)xhci->cmd_ring->enqueue->link.segment_ptr) & 0xff0);
}
else{
g_cmd_ring_pointer2 = ((((int)(unsigned long)xhci->cmd_ring->enqueue) & 0xff0));
}
}
return queue_command(xhci, 0, 0, 0,
trb_slot_id | trb_ep_index | type, false);
}
/* Set Transfer Ring Dequeue Pointer command.
* This should not be used for endpoints that have streams enabled.
*/
static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id,
unsigned int ep_index, unsigned int stream_id,
struct xhci_segment *deq_seg,
union xhci_trb *deq_ptr, u32 cycle_state)
{
dma_addr_t addr;
u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id);
u32 type = TRB_TYPE(TRB_SET_DEQ);
struct xhci_virt_ep *ep;
addr = <API key>(deq_seg, deq_ptr);
if (addr == 0) {
xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n",
deq_seg, deq_ptr);
return 0;
}
ep = &xhci->devs[slot_id]->eps[ep_index];
if ((ep->ep_state & SET_DEQ_PENDING)) {
xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n");
xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n");
return 0;
}
ep->queued_deq_seg = deq_seg;
ep->queued_deq_ptr = deq_ptr;
return queue_command(xhci, lower_32_bits(addr) | cycle_state,
upper_32_bits(addr), trb_stream_id,
trb_slot_id | trb_ep_index | type, false);
}
int <API key>(struct xhci_hcd *xhci, int slot_id,
unsigned int ep_index)
{
u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id);
u32 trb_ep_index = EP_ID_FOR_TRB(ep_index);
u32 type = TRB_TYPE(TRB_RESET_EP);
return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type,
false);
} |
/* ScriptData
SDName: Boss_Razorgore
SD%Complete: 50
SDComment: Needs additional review. Phase 1 NYI (Grethok the Controller)
SDCategory: Blackwing Lair
EndScriptData */
#include "ScriptPCH.h"
//Razorgore Phase 2 Script
enum Say
{
SAY_EGGS_BROKEN1 = -1469022,
SAY_EGGS_BROKEN2 = -1469023,
SAY_EGGS_BROKEN3 = -1469024,
SAY_DEATH = -1469025
};
enum Spells
{
SPELL_CLEAVE = 22540,
SPELL_WARSTOMP = 24375,
<API key> = 22425,
SPELL_CONFLAGRATION = 23023
};
class boss_razorgore : public CreatureScript
{
public:
boss_razorgore() : CreatureScript("boss_razorgore") { }
CreatureAI* GetAI(Creature* creature) const
{
return new boss_razorgoreAI (creature);
}
struct boss_razorgoreAI : public ScriptedAI
{
boss_razorgoreAI(Creature* creature) : ScriptedAI(creature) {}
uint32 Cleave_Timer;
uint32 WarStomp_Timer;
uint32 <API key>;
uint32 Conflagration_Timer;
void Reset()
{
Cleave_Timer = 15000; //These times are probably wrong
WarStomp_Timer = 35000;
<API key> = 7000;
Conflagration_Timer = 12000;
}
void EnterCombat(Unit* /*who*/)
{
DoZoneInCombat();
}
void JustDied(Unit* /*Killer*/)
{
DoScriptText(SAY_DEATH, me);
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//Cleave_Timer
if (Cleave_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CLEAVE);
Cleave_Timer = urand(7000, 10000);
} else Cleave_Timer -= diff;
//WarStomp_Timer
if (WarStomp_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_WARSTOMP);
WarStomp_Timer = urand(15000, 25000);
} else WarStomp_Timer -= diff;
//<API key>
if (<API key> <= diff)
{
DoCast(me->getVictim(), <API key>);
<API key> = urand(12000, 15000);
} else <API key> -= diff;
//Conflagration_Timer
if (Conflagration_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CONFLAGRATION);
//We will remove this threat reduction and add an aura check.
//if (DoGetThreat(me->getVictim()))
//<API key>(me->getVictim(), -50);
Conflagration_Timer = 12000;
} else Conflagration_Timer -= diff;
// Aura Check. If the gamer is affected by confliguration we attack a random gamer.
if (me->getVictim() && me->getVictim()->HasAura(SPELL_CONFLAGRATION))
if (Unit* target = SelectTarget(<API key>, 1, 100, true))
me->TauntApply(target);
<API key>();
}
};
};
void <API key>()
{
new boss_razorgore();
} |
#ifndef _SYS_STAT_H
# error "Never include <bits/stat.h> directly; use <sys/stat.h> instead."
#endif
/* Versions of the `struct stat' data structure. */
#define _STAT_VER_LINUX_OLD 1
#define _STAT_VER_KERNEL 1
#define _STAT_VER_SVR4 2
#define _STAT_VER_LINUX 3
#define _STAT_VER _STAT_VER_LINUX /* The one defined below. */
/* Versions of the `xmknod' interface. */
#define _MKNOD_VER_LINUX 1
#define _MKNOD_VER_SVR4 2
#define _MKNOD_VER _MKNOD_VER_LINUX /* The bits defined below. */
struct stat
{
__dev_t st_dev; /* Device. */
unsigned short int __pad1;
#ifndef __USE_FILE_OFFSET64
__ino_t st_ino; /* File serial number. */
#else
__ino_t __st_ino; /* 32bit file serial number. */
#endif
__mode_t st_mode; /* File mode. */
__nlink_t st_nlink; /* Link count. */
__uid_t st_uid; /* User ID of the file's owner. */
__gid_t st_gid; /* Group ID of the file's group.*/
__dev_t st_rdev; /* Device number, if device. */
unsigned short int __pad2;
#ifndef __USE_FILE_OFFSET64
__off_t st_size; /* Size of file, in bytes. */
#else
__off64_t st_size; /* Size of file, in bytes. */
#endif
__blksize_t st_blksize; /* Optimal block size for I/O. */
#ifndef __USE_FILE_OFFSET64
__blkcnt_t st_blocks; /* Number 512-byte blocks allocated. */
#else
__blkcnt64_t st_blocks; /* Number 512-byte blocks allocated. */
#endif
__time_t st_atime; /* Time of last access. */
unsigned long int __unused1;
__time_t st_mtime; /* Time of last modification. */
unsigned long int __unused2;
__time_t st_ctime; /* Time of last status change. */
unsigned long int __unused3;
#ifndef __USE_FILE_OFFSET64
unsigned long int __unused4;
unsigned long int __unused5;
#else
__ino64_t st_ino; /* File serial number. */
#endif
};
#ifdef __USE_LARGEFILE64
struct stat64
{
__dev_t st_dev; /* Device. */
unsigned int __pad1;
__ino_t __st_ino; /* 32bit file serial number. */
__mode_t st_mode; /* File mode. */
__nlink_t st_nlink; /* Link count. */
__uid_t st_uid; /* User ID of the file's owner. */
__gid_t st_gid; /* Group ID of the file's group.*/
__dev_t st_rdev; /* Device number, if device. */
unsigned int __pad2;
__off64_t st_size; /* Size of file, in bytes. */
__blksize_t st_blksize; /* Optimal block size for I/O. */
__blkcnt64_t st_blocks; /* Number 512-byte blocks allocated. */
__time_t st_atime; /* Time of last access. */
unsigned long int __unused1;
__time_t st_mtime; /* Time of last modification. */
unsigned long int __unused2;
__time_t st_ctime; /* Time of last status change. */
unsigned long int __unused3;
__ino64_t st_ino; /* File serial number. */
};
#endif
/* Tell code we have these members. */
#define _STATBUF_ST_BLKSIZE
#define _STATBUF_ST_RDEV
/* Encoding of the file mode. */
#define __S_IFMT 0170000 /* These bits determine file type. */
/* File types. */
#define __S_IFDIR 0040000 /* Directory. */
#define __S_IFCHR 0020000 /* Character device. */
#define __S_IFBLK 0060000 /* Block device. */
#define __S_IFREG 0100000 /* Regular file. */
#define __S_IFIFO 0010000 /* FIFO. */
#define __S_IFLNK 0120000 /* Symbolic link. */
#define __S_IFSOCK 0140000 /* Socket. */
/* POSIX.1b objects. Note that these macros always evaluate to zero. But
they do it by enforcing the correct use of the macros. */
#define __S_TYPEISMQ(buf) ((buf)->st_mode - (buf)->st_mode)
#define __S_TYPEISSEM(buf) ((buf)->st_mode - (buf)->st_mode)
#define __S_TYPEISSHM(buf) ((buf)->st_mode - (buf)->st_mode)
/* Protection bits. */
#define __S_ISUID 04000 /* Set user ID on execution. */
#define __S_ISGID 02000 /* Set group ID on execution. */
#define __S_ISVTX 01000 /* Save swapped text after use (sticky). */
#define __S_IREAD 0400 /* Read by owner. */
#define __S_IWRITE 0200 /* Write by owner. */
#define __S_IEXEC 0100 /* Execute by owner. */ |
#ifndef POLARSSL_MD5_H
#define POLARSSL_MD5_H
#if !defined(<API key>)
#include "config.h"
#else
#include <API key>
#endif
#include <string.h>
#if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32)
#include <basetsd.h>
typedef UINT32 uint32_t;
#else
#include <inttypes.h>
#endif
#define <API key> -0x0074 /**< Read/write error in file. */
#if !defined(POLARSSL_MD5_ALT)
// Regular implementation
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief MD5 context structure
*/
typedef struct
{
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
unsigned char ipad[64]; /*!< HMAC: inner padding */
unsigned char opad[64]; /*!< HMAC: outer padding */
}
md5_context;
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*/
void md5_init( md5_context *ctx );
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*/
void md5_free( md5_context *ctx );
/**
* \brief MD5 context setup
*
* \param ctx context to be initialized
*/
void md5_starts( md5_context *ctx );
/**
* \brief MD5 process buffer
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void md5_update( md5_context *ctx, const unsigned char *input, size_t ilen );
/**
* \brief MD5 final digest
*
* \param ctx MD5 context
* \param output MD5 checksum result
*/
void md5_finish( md5_context *ctx, unsigned char output[16] );
/* Internal use */
void md5_process( md5_context *ctx, const unsigned char data[64] );
#ifdef __cplusplus
}
#endif
#else /* POLARSSL_MD5_ALT */
#include "md5_alt.h"
#endif /* POLARSSL_MD5_ALT */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Output = MD5( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*/
void md5( const unsigned char *input, size_t ilen, unsigned char output[16] );
/**
* \brief Output = MD5( file contents )
*
* \param path input file name
* \param output MD5 checksum result
*
* \return 0 if successful, or <API key>
*/
int md5_file( const char *path, unsigned char output[16] );
/**
* \brief MD5 HMAC context setup
*
* \param ctx HMAC context to be initialized
* \param key HMAC secret key
* \param keylen length of the HMAC key
*/
void md5_hmac_starts( md5_context *ctx,
const unsigned char *key, size_t keylen );
/**
* \brief MD5 HMAC process buffer
*
* \param ctx HMAC context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void md5_hmac_update( md5_context *ctx,
const unsigned char *input, size_t ilen );
/**
* \brief MD5 HMAC final digest
*
* \param ctx HMAC context
* \param output MD5 HMAC checksum result
*/
void md5_hmac_finish( md5_context *ctx, unsigned char output[16] );
/**
* \brief MD5 HMAC context reset
*
* \param ctx HMAC context to be reset
*/
void md5_hmac_reset( md5_context *ctx );
/**
* \brief Output = HMAC-MD5( hmac key, input buffer )
*
* \param key HMAC secret key
* \param keylen length of the HMAC key
* \param input buffer holding the data
* \param ilen length of the input data
* \param output HMAC-MD5 result
*/
void md5_hmac( const unsigned char *key, size_t keylen,
const unsigned char *input, size_t ilen,
unsigned char output[16] );
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*/
int md5_self_test( int verbose );
#ifdef __cplusplus
}
#endif
#endif /* md5.h */ |
#ifndef DIFFUSIONMAPS_H_
#define DIFFUSIONMAPS_H_
#include <shogun/lib/config.h>
#include <shogun/converter/EmbeddingConverter.h>
#ifdef HAVE_EIGEN3
#include <shogun/features/Features.h>
#include <shogun/kernel/Kernel.h>
namespace shogun
{
class CFeatures;
class CKernel;
class CDiffusionMaps: public CEmbeddingConverter
{
public:
/** constructor */
CDiffusionMaps();
/** destructor */
virtual ~CDiffusionMaps();
/** apply preprocessor to features
* @param features
*/
virtual CFeatures* apply(CFeatures* features);
/** embed distance
* @param distance to use for embedding
* @return embedding simple features
*/
virtual CDenseFeatures<float64_t>* embed_distance(CDistance* distance);
/** setter for t parameter
* @param t t value
*/
void set_t(int32_t t);
/** getter for t parameter
* @return t value
*/
int32_t get_t() const;
/** setter for width parameter
* @param width width value
*/
void set_width(float64_t width);
/** getter for width parameter
* @return width value
*/
float64_t get_width() const;
/** get name */
virtual const char* get_name() const;
protected:
/** default init */
void init();
protected:
/** number of steps */
int32_t m_t;
/** gaussian kernel width */
float64_t m_width;
};
}
#endif /* HAVE_LAPACK */
#endif /* DIFFUSIONMAPS_H_ */ |
/**
* \file mult_files.c
* Internal code to find remainder of files in a split raw set
*/
#include "tsk_img_i.h"
// return non-zero if str ends with suffix, ignoring case
static int
endsWith(const TSK_TCHAR * str, const TSK_TCHAR * suffix)
{
if (TSTRLEN(str) >= TSTRLEN(suffix)) {
return (TSTRICMP(&str[TSTRLEN(str) - TSTRLEN(suffix)],
suffix) == 0);
}
return 0;
}
/** Generate the name of the Nth segment of an image, given the starting name.
* If the name scheme isn't recognized, just returns the starting name for
* segment 1 and NULL for subsequent segments.
*
* @param a_startingName First name in the list (must be full name)
* @param a_segmentNumber The file number to generate a name for (starting at 1)
* @returns newly-allocated file name for this segment number or NULL on error
*/
static TSK_TCHAR *
getSegmentName(const TSK_TCHAR * a_startingName, int a_segmentNumber)
{
size_t nameLen = TSTRLEN(a_startingName);
TSK_TCHAR *newName =
(TSK_TCHAR *) tsk_malloc((nameLen + 32) * sizeof(TSK_TCHAR));
// (extra space to allow for .NNN.dmgpart for .dmg file names and for
// large segment numbers, which could be 10 digits for 32-bit int)
if (newName == NULL)
return NULL;
// segment 1 uses the original file name always
TSTRNCPY(newName, a_startingName, nameLen + 1);
if (a_segmentNumber == 1) {
return newName;
}
// .dmg case: second part is .002.dmgpart (etc.)
if (endsWith(a_startingName, _TSK_T(".dmg"))) {
TSNPRINTF(newName + nameLen - 3, 35, _TSK_T("%03d.dmgpart"),
a_segmentNumber);
return newName;
}
// numeric counter case, 3 digit
if (endsWith(a_startingName, _TSK_T(".001")) ||
endsWith(a_startingName, _TSK_T("_001"))) {
// don't limit to 3 digits (FTK produces files named
// foo.1000 for 1000-part DD images)
TSNPRINTF(newName + nameLen - 3, 35, _TSK_T("%03d"),
a_segmentNumber);
return newName;
}
// 0-based numeric counter case, 3 digit
if (endsWith(a_startingName, _TSK_T(".000")) ||
endsWith(a_startingName, _TSK_T("_000"))) {
TSNPRINTF(newName + nameLen - 3, 35, _TSK_T("%03d"),
a_segmentNumber - 1);
return newName;
}
// numeric counter case, 2 digit
if (endsWith(a_startingName, _TSK_T(".01")) ||
endsWith(a_startingName, _TSK_T("_01"))) {
TSNPRINTF(newName + nameLen - 2, 34, _TSK_T("%02d"),
a_segmentNumber);
return newName;
}
// 0-based numeric counter case, 2 digit
if (endsWith(a_startingName, _TSK_T(".00")) ||
endsWith(a_startingName, _TSK_T("_00"))) {
TSNPRINTF(newName + nameLen - 2, 34, _TSK_T("%02d"),
a_segmentNumber - 1);
return newName;
}
// alphabetic counter, 3 character
if (endsWith(a_startingName, _TSK_T(".aaa")) ||
endsWith(a_startingName, _TSK_T("xaaa")) ||
endsWith(a_startingName, _TSK_T("_aaa"))) {
// preserve case for the alpha characters
a_segmentNumber
newName[nameLen - 1] += (a_segmentNumber % 26);
a_segmentNumber /= 26;
newName[nameLen - 2] += (a_segmentNumber % 26);
a_segmentNumber /= 26;
newName[nameLen - 3] += (a_segmentNumber % 26);
a_segmentNumber /= 26;
if (a_segmentNumber > 0) {
// too many segments for format
free(newName);
return NULL;
}
return newName;
}
// alphabetic counter, 2 character
if (endsWith(a_startingName, _TSK_T(".aa")) ||
endsWith(a_startingName, _TSK_T("xaa")) ||
endsWith(a_startingName, _TSK_T("_aa"))) {
// preserve case for the alpha characters
a_segmentNumber
newName[nameLen - 1] += (a_segmentNumber % 26);
a_segmentNumber /= 26;
newName[nameLen - 2] += (a_segmentNumber % 26);
a_segmentNumber /= 26;
if (a_segmentNumber > 0) {
// too many segments for format
free(newName);
return NULL;
}
return newName;
}
// numeric counter, variable width
if (endsWith(a_startingName, _TSK_T(".bin"))) {
TSNPRINTF(newName + nameLen - 4, 36, _TSK_T("(%d).bin"),
a_segmentNumber);
return newName;
}
// unknown name format
free(newName);
return NULL;
}
/**
* @param a_startingName First name in the list (must be full name)
* @param [out] a_numFound Number of images that are in returned list
* @returns array of names that caller must free (NULL on error or if supplied file does not exist)
*/
TSK_TCHAR **
tsk_img_findFiles(const TSK_TCHAR * a_startingName, int *a_numFound)
{
TSK_TCHAR **retNames = NULL;
TSK_TCHAR *nextName;
TSK_TCHAR **tmpNames;
int fileCount = 0;
struct STAT_STR stat_buf;
*a_numFound = 0;
// iterate through potential segment names
while ((nextName =
getSegmentName(a_startingName, fileCount + 1)) != NULL) {
// does the file exist?
if (TSTAT(nextName, &stat_buf) < 0) {
free(nextName);
break;
}
if (tsk_verbose)
tsk_fprintf(stderr,
"tsk_img_findFiles: %" PRIttocTSK " found\n", nextName);
// add to list
fileCount++;
if (fileCount == 1)
tmpNames = (TSK_TCHAR **) tsk_malloc(sizeof(TSK_TCHAR *));
else
tmpNames =
(TSK_TCHAR **) tsk_realloc(retNames,
fileCount * sizeof(TSK_TCHAR *));
if (tmpNames == NULL) {
if (retNames != NULL)
free(retNames);
return NULL;
}
retNames = tmpNames;
retNames[fileCount - 1] = nextName;
}
if (fileCount <= 0)
return NULL;
if (tsk_verbose)
tsk_fprintf(stderr, "tsk_img_findFiles: %d total segments found\n",
fileCount);
*a_numFound = fileCount;
return retNames;
} |
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#if defined (HAVE_GFC_COMPLEX_10)
/* Allocates a block of memory with internal_malloc if the array needs
repacking. */
GFC_COMPLEX_10 *
internal_pack_c10 (gfc_array_c10 * source)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type stride[GFC_MAX_DIMENSIONS];
index_type stride0;
index_type dim;
index_type ssize;
const GFC_COMPLEX_10 *src;
GFC_COMPLEX_10 * restrict dest;
GFC_COMPLEX_10 *destptr;
int n;
int packed;
/* TODO: Investigate how we can figure out if this is a temporary
since the stride=0 thing has been removed from the frontend. */
dim = GFC_DESCRIPTOR_RANK (source);
ssize = 1;
packed = 1;
for (n = 0; n < dim; n++)
{
count[n] = 0;
stride[n] = <API key>(source,n);
extent[n] = <API key>(source,n);
if (extent[n] <= 0)
{
/* Do nothing. */
packed = 1;
break;
}
if (ssize != stride[n])
packed = 0;
ssize *= extent[n];
}
if (packed)
return source->base_addr;
/* Allocate storage for the destination. */
destptr = xmallocarray (ssize, sizeof (GFC_COMPLEX_10));
dest = destptr;
src = source->base_addr;
stride0 = stride[0];
while (src)
{
/* Copy the data. */
*(dest++) = *src;
/* Advance to the next element. */
src += stride0;
count[0]++;
/* Advance to the next source element. */
n = 0;
while (count[n] == extent[n])
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
src -= stride[n] * extent[n];
n++;
if (n == dim)
{
src = NULL;
break;
}
else
{
count[n]++;
src += stride[n];
}
}
}
return destptr;
}
#endif |
#ifndef <API key>
#define <API key>
#include "gimppaintoptions.h"
#define <API key> (<API key> ())
#define GIMP_PENCIL_OPTIONS(obj) (<API key> ((obj), <API key>, GimpPencilOptions))
#define <API key>(klass) (<API key> ((klass), <API key>, <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>))
#define <API key>(klass) (<API key> ((klass), <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>, <API key>))
typedef struct <API key> <API key>;
struct _GimpPencilOptions
{
GimpPaintOptions parent_instance;
};
struct <API key>
{
<API key> parent_class;
};
GType <API key> (void) G_GNUC_CONST;
#endif /* <API key> */ |
/* Written by Bruno Haible <bruno@clisp.org>, 2007. */
#include <config.h>
#include <stdio.h>
#include "verify.h"
/* Check that the various SEEK_* macros are defined. */
int sk[] = { SEEK_CUR, SEEK_END, SEEK_SET };
/* Check that NULL can be passed through varargs as a pointer type,
per POSIX 2008. */
verify (sizeof NULL == sizeof (void *));
/* Check that the types are all defined. */
fpos_t t1;
off_t t2;
size_t t3;
ssize_t t4;
va_list t5;
int
main (void)
{
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.