file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
radon_transform.py
# -*- coding: utf-8 -*- """ radon.py - Radon and inverse radon transforms Based on code of Justin K. Romberg (http://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html) J. Gillam and Chris Griffin. References: -B.R. Ramesh, N. Srinivasa, K. Rajgopal, "An Algorithm for Computing the Discrete Radon Transform With Some Applications", Proceedings of the Fourth IEEE Region 10 International Conference, TENCON '89, 1989. -A. C. Kak, Malcolm Slaney, "Principles of Computerized Tomographic Imaging", IEEE Press 1988. """ from __future__ import division import numpy as np from scipy.fftpack import fft, ifft, fftfreq from scipy.interpolate import interp1d from ._warps_cy import _warp_fast from ._radon_transform import sart_projection_update from .. import util from warnings import warn __all__ = ["radon", "iradon", "iradon_sart"] def radon(image, theta=None, circle=False): """ Calculates the radon transform of an image given specified projection angles. Parameters ---------- image : array_like, dtype=float Input image. The rotation axis will be located in the pixel with indices ``(image.shape[0] // 2, image.shape[1] // 2)``. theta : array_like, dtype=float, optional (default np.arange(180)) Projection angles (in degrees). circle : boolean, optional Assume image is zero outside the inscribed circle, making the width of each projection (the first dimension of the sinogram) equal to ``min(image.shape)``. Returns ------- radon_image : ndarray Radon transform (sinogram). The tomography rotation axis will lie at the pixel index ``radon_image.shape[0] // 2`` along the 0th dimension of ``radon_image``. """ if image.ndim != 2: raise ValueError('The input image must be 2-D') if theta is None: theta = np.arange(180) if circle: radius = min(image.shape) // 2 c0, c1 = np.ogrid[0:image.shape[0], 0:image.shape[1]] reconstruction_circle = ((c0 - image.shape[0] // 2) ** 2 + (c1 - image.shape[1] // 2) ** 2) reconstruction_circle = reconstruction_circle <= radius ** 2 if not np.all(reconstruction_circle | (image == 0)): warn('Radon transform: image must be zero outside the ' 'reconstruction circle') # Crop image to make it square slices = [] for d in (0, 1): if image.shape[d] > min(image.shape): excess = image.shape[d] - min(image.shape) slices.append(slice(int(np.ceil(excess / 2)), int(np.ceil(excess / 2) + min(image.shape)))) else: slices.append(slice(None)) slices = tuple(slices) padded_image = image[slices] else: diagonal = np.sqrt(2) * max(image.shape) pad = [int(np.ceil(diagonal - s)) for s in image.shape] new_center = [(s + p) // 2 for s, p in zip(image.shape, pad)] old_center = [s // 2 for s in image.shape] pad_before = [nc - oc for oc, nc in zip(old_center, new_center)] pad_width = [(pb, p - pb) for pb, p in zip(pad_before, pad)] padded_image = util.pad(image, pad_width, mode='constant', constant_values=0) # padded_image is always square assert padded_image.shape[0] == padded_image.shape[1] radon_image = np.zeros((padded_image.shape[0], len(theta))) center = padded_image.shape[0] // 2 shift0 = np.array([[1, 0, -center], [0, 1, -center], [0, 0, 1]]) shift1 = np.array([[1, 0, center], [0, 1, center], [0, 0, 1]]) def build_rotation(theta): T = np.deg2rad(theta) R = np.array([[np.cos(T), np.sin(T), 0], [-np.sin(T), np.cos(T), 0], [0, 0, 1]]) return shift1.dot(R).dot(shift0) for i in range(len(theta)): rotated = _warp_fast(padded_image, build_rotation(theta[i])) radon_image[:, i] = rotated.sum(0) return radon_image def _sinogram_circle_to_square(sinogram): diagonal = int(np.ceil(np.sqrt(2) * sinogram.shape[0])) pad = diagonal - sinogram.shape[0] old_center = sinogram.shape[0] // 2 new_center = diagonal // 2 pad_before = new_center - old_center pad_width = ((pad_before, pad - pad_before), (0, 0)) return util.pad(sinogram, pad_width, mode='constant', constant_values=0) def iradon(radon_image, theta=None, output_size=None, filter="ramp", interpolation="linear", circle=False): """ Inverse radon transform. Reconstruct an image from the radon transform, using the filtered back projection algorithm. Parameters ---------- radon_image : array_like, dtype=float Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index ``radon_image.shape[0] // 2`` along the 0th dimension of ``radon_image``. theta : array_like, dtype=float, optional Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)). output_size : int Number of rows and columns in the reconstruction. filter : str, optional (default ramp) Filter used in frequency domain filtering. Ramp filter used by default. Filters available: ramp, shepp-logan, cosine, hamming, hann. Assign None to use no filter. interpolation : str, optional (default 'linear') Interpolation method used in reconstruction. Methods available: 'linear', 'nearest', and 'cubic' ('cubic' is slow). circle : boolean, optional Assume the reconstructed image is zero outside the inscribed circle. Also changes the default output_size to match the behaviour of ``radon`` called with ``circle=True``. Returns ------- reconstructed : ndarray Reconstructed image. The rotation axis will be located in the pixel with indices ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``. Notes ----- It applies the Fourier slice theorem to reconstruct an image by multiplying the frequency domain of the filter with the FFT of the projection data. This algorithm is called filtered back projection. """ if radon_image.ndim != 2: raise ValueError('The input image must be 2-D') if theta is None: m, n = radon_image.shape theta = np.linspace(0, 180, n, endpoint=False) else: theta = np.asarray(theta) if len(theta) != radon_image.shape[1]: raise ValueError("The given ``theta`` does not match the number of " "projections in ``radon_image``.") interpolation_types = ('linear', 'nearest', 'cubic') if not interpolation in interpolation_types: raise ValueError("Unknown interpolation: %s" % interpolation) if not output_size: # If output size not specified, estimate from input radon image if circle: output_size = radon_image.shape[0] else: output_size = int(np.floor(np.sqrt((radon_image.shape[0]) ** 2 / 2.0))) if circle: radon_image = _sinogram_circle_to_square(radon_image) th = (np.pi / 180.0) * theta # resize image to next power of two (but no less than 64) for # Fourier analysis; speeds up Fourier and lessens artifacts projection_size_padded = \ max(64, int(2 ** np.ceil(np.log2(2 * radon_image.shape[0])))) pad_width = ((0, projection_size_padded - radon_image.shape[0]), (0, 0)) img = util.pad(radon_image, pad_width, mode='constant', constant_values=0) # Construct the Fourier filter f = fftfreq(projection_size_padded).reshape(-1, 1) # digital frequency omega = 2 * np.pi * f # angular frequency fourier_filter = 2 * np.abs(f) # ramp filter if filter == "ramp": pass elif filter == "shepp-logan": # Start from first element to avoid divide by zero fourier_filter[1:] = fourier_filter[1:] * np.sin(omega[1:]) / omega[1:] elif filter == "cosine": fourier_filter *= np.cos(omega) elif filter == "hamming": fourier_filter *= (0.54 + 0.46 * np.cos(omega / 2)) elif filter == "hann": fourier_filter *= (1 + np.cos(omega / 2)) / 2 elif filter is None: fourier_filter[:] = 1 else: raise ValueError("Unknown filter: %s" % filter) # Apply filter in Fourier domain projection = fft(img, axis=0) * fourier_filter radon_filtered = np.real(ifft(projection, axis=0)) # Resize filtered image back to original size radon_filtered = radon_filtered[:radon_image.shape[0], :] reconstructed = np.zeros((output_size, output_size)) # Determine the center of the projections (= center of sinogram) mid_index = radon_image.shape[0] // 2 [X, Y] = np.mgrid[0:output_size, 0:output_size] xpr = X - int(output_size) // 2 ypr = Y - int(output_size) // 2 # Reconstruct image by interpolation for i in range(len(theta)): t = ypr * np.cos(th[i]) - xpr * np.sin(th[i]) x = np.arange(radon_filtered.shape[0]) - mid_index if interpolation == 'linear': backprojected = np.interp(t, x, radon_filtered[:, i], left=0, right=0) else: interpolant = interp1d(x, radon_filtered[:, i], kind=interpolation, bounds_error=False, fill_value=0) backprojected = interpolant(t) reconstructed += backprojected if circle: radius = output_size // 2 reconstruction_circle = (xpr ** 2 + ypr ** 2) <= radius ** 2 reconstructed[~reconstruction_circle] = 0. return reconstructed * np.pi / (2 * len(th)) def order_angles_golden_ratio(theta): """ Order angles to reduce the amount of correlated information in subsequent projections. Parameters ---------- theta : 1D array of floats Projection angles in degrees. Duplicate angles are not allowed. Returns ------- indices_generator : generator yielding unsigned integers The returned generator yields indices into ``theta`` such that ``theta[indices]`` gives the approximate golden ratio ordering of the projections. In total, ``len(theta)`` indices are yielded. All non-negative integers < ``len(theta)`` are yielded exactly once. Notes ----- The method used here is that of the golden ratio introduced by T. Kohler. References ---------- .. [1] Kohler, T. "A projection access scheme for iterative reconstruction based on the golden section." Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. .. [2] Winkelmann, Stefanie, et al. "An optimal radial profile order based on the Golden Ratio for time-resolved MRI." Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76. """ interval = 180 def angle_distance(a, b): difference = a - b return min(abs(difference % interval), abs(difference % -interval)) remaining = list(np.argsort(theta)) # indices into theta # yield an arbitrary angle to start things off index = remaining.pop(0) angle = theta[index] yield index # determine subsequent angles using the golden ratio method angle_increment = interval * (1 - (np.sqrt(5) - 1) / 2) while remaining: angle = (angle + angle_increment) % interval insert_point = np.searchsorted(theta[remaining], angle) index_below = insert_point - 1 index_above = 0 if insert_point == len(remaining) else insert_point distance_below = angle_distance(angle, theta[remaining[index_below]]) distance_above = angle_distance(angle, theta[remaining[index_above]]) if distance_below < distance_above: yield remaining.pop(index_below) else: yield remaining.pop(index_above) def iradon_sart(radon_image, theta=None, image=None, projection_shifts=None, clip=None, relaxation=0.15):
""" Inverse radon transform Reconstruct an image from the radon transform, using a single iteration of the Simultaneous Algebraic Reconstruction Technique (SART) algorithm. Parameters ---------- radon_image : 2D array, dtype=float Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index ``radon_image.shape[0] // 2`` along the 0th dimension of ``radon_image``. theta : 1D array, dtype=float, optional Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)). image : 2D array, dtype=float, optional Image containing an initial reconstruction estimate. Shape of this array should be ``(radon_image.shape[0], radon_image.shape[0])``. The default is an array of zeros. projection_shifts : 1D array, dtype=float Shift the projections contained in ``radon_image`` (the sinogram) by this many pixels before reconstructing the image. The i'th value defines the shift of the i'th column of ``radon_image``. clip : length-2 sequence of floats Force all values in the reconstructed tomogram to lie in the range ``[clip[0], clip[1]]`` relaxation : float Relaxation parameter for the update step. A higher value can improve the convergence rate, but one runs the risk of instabilities. Values close to or higher than 1 are not recommended. Returns ------- reconstructed : ndarray Reconstructed image. The rotation axis will be located in the pixel with indices ``(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)``. Notes ----- Algebraic Reconstruction Techniques are based on formulating the tomography reconstruction problem as a set of linear equations. Along each ray, the projected value is the sum of all the values of the cross section along the ray. A typical feature of SART (and a few other variants of algebraic techniques) is that it samples the cross section at equidistant points along the ray, using linear interpolation between the pixel values of the cross section. The resulting set of linear equations are then solved using a slightly modified Kaczmarz method. When using SART, a single iteration is usually sufficient to obtain a good reconstruction. Further iterations will tend to enhance high-frequency information, but will also often increase the noise. References ---------- .. [1] AC Kak, M Slaney, "Principles of Computerized Tomographic Imaging", IEEE Press 1988. .. [2] AH Andersen, AC Kak, "Simultaneous algebraic reconstruction technique (SART): a superior implementation of the ART algorithm", Ultrasonic Imaging 6 pp 81--94 (1984) .. [3] S Kaczmarz, "Angenäherte auflösung von systemen linearer gleichungen", Bulletin International de l’Academie Polonaise des Sciences et des Lettres 35 pp 355--357 (1937) .. [4] Kohler, T. "A projection access scheme for iterative reconstruction based on the golden section." Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. .. [5] Kaczmarz' method, Wikipedia, http://en.wikipedia.org/wiki/Kaczmarz_method """ if radon_image.ndim != 2: raise ValueError('radon_image must be two dimensional') reconstructed_shape = (radon_image.shape[0], radon_image.shape[0]) if theta is None: theta = np.linspace(0, 180, radon_image.shape[1], endpoint=False) elif theta.shape != (radon_image.shape[1],): raise ValueError('Shape of theta (%s) does not match the ' 'number of projections (%d)' % (projection_shifts.shape, radon_image.shape[1])) if image is None: image = np.zeros(reconstructed_shape, dtype=np.float) elif image.shape != reconstructed_shape: raise ValueError('Shape of image (%s) does not match first dimension ' 'of radon_image (%s)' % (image.shape, reconstructed_shape)) if projection_shifts is None: projection_shifts = np.zeros((radon_image.shape[1],), dtype=np.float) elif projection_shifts.shape != (radon_image.shape[1],): raise ValueError('Shape of projection_shifts (%s) does not match the ' 'number of projections (%d)' % (projection_shifts.shape, radon_image.shape[1])) if not clip is None: if len(clip) != 2: raise ValueError('clip must be a length-2 sequence') clip = (float(clip[0]), float(clip[1])) relaxation = float(relaxation) for angle_index in order_angles_golden_ratio(theta): image_update = sart_projection_update(image, theta[angle_index], radon_image[:, angle_index], projection_shifts[angle_index]) image += relaxation * image_update if not clip is None: image = np.clip(image, clip[0], clip[1]) return image
run_rules.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # Usage: # # $ python -m fixit.cli.run_rules --help # $ python -m fixit.cli.run_rules # $ python -m fixit.cli.run_rules --rules AvoidOrInExceptRule # $ python -m fixit.cli.run_rules . --rules AvoidOrInExceptRule NoUnnecessaryListComprehensionRule # $ python -m fixit.cli.run_rules . --rules AvoidOrInExceptRule my.custom.rules.package # $ python -m fixit.cli.run_rules . --rules fixit.rules import argparse import itertools import shutil import sys import time from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, Iterable, Mapping, Optional, Sequence from libcst import ParserSyntaxError, parse_module from libcst.metadata import MetadataWrapper from fixit.cli import find_files, map_paths from fixit.cli.args import ( get_compact_parser, get_multiprocessing_parser, get_paths_parser, get_rules_parser, get_skip_ignore_byte_marker_parser, get_use_ignore_comments_parser, ) from fixit.cli.formatter import LintRuleReportFormatter from fixit.cli.full_repo_metadata import ( get_metadata_caches, rules_require_metadata_cache, ) from fixit.cli.utils import print_red from fixit.common.utils import LintRuleCollectionT from fixit.rule_lint_engine import lint_file if TYPE_CHECKING: from libcst.metadata.base_provider import ProviderT @dataclass(frozen=True) class LintOpts: rules: LintRuleCollectionT use_ignore_byte_markers: bool use_ignore_comments: bool formatter: LintRuleReportFormatter def get_formatted_reports_for_path( path: Path, opts: LintOpts, metadata_cache: Optional[Mapping["ProviderT", object]] = None, ) -> Iterable[str]: with open(path, "rb") as f: source = f.read() try: cst_wrapper = None if metadata_cache is not None: cst_wrapper = MetadataWrapper(parse_module(source), True, metadata_cache) raw_reports = lint_file( path, source, rules=opts.rules, use_ignore_byte_markers=opts.use_ignore_byte_markers, use_ignore_comments=opts.use_ignore_comments, cst_wrapper=cst_wrapper, ) except (SyntaxError, ParserSyntaxError) as e: print_red( f"Encountered the following error while parsing source code in file {path}:" ) print(e) return [] # linter completed successfully return [opts.formatter.format(rr) for rr in raw_reports] def main(raw_args: Sequence[str]) -> int: parser = argparse.ArgumentParser( description=( "Validates your lint rules by running them against the specified, " + "directory or file(s). This is not a substitute for unit tests, " + "but it can provide additional confidence in your lint rules.\n" + "If no lint rules or packages are specified, runs all lint rules " + "found in the packages specified in `fixit.config.yaml`." ), parents=[ get_paths_parser(), get_rules_parser(), get_use_ignore_comments_parser(), get_skip_ignore_byte_marker_parser(), get_compact_parser(), get_multiprocessing_parser(), ], ) parser.add_argument( "--cache-timeout", type=int, help="Timeout (seconds) for metadata cache fetching. Default is 2 seconds.", default=2, ) args = parser.parse_args(raw_args) width = shutil.get_terminal_size(fallback=(80, 24)).columns # expand path if it's a directory file_paths = tuple(find_files(args.paths)) all_rules = args.rules if not args.compact: print(f"Scanning {len(file_paths)} files") print(f"Testing {len(all_rules)} rules") print() start_time = time.time() metadata_caches: Optional[Mapping[str, Mapping["ProviderT", object]]] = None if rules_require_metadata_cache(all_rules): metadata_caches = get_metadata_caches(args.cache_timeout, file_paths) # opts is a more type-safe version of args that we pass around opts = LintOpts(
rules=all_rules, use_ignore_byte_markers=args.use_ignore_byte_markers, use_ignore_comments=args.use_ignore_comments, formatter=LintRuleReportFormatter(width, args.compact), ) formatted_reports_iter = itertools.chain.from_iterable( map_paths( get_formatted_reports_for_path, file_paths, opts, workers=args.workers, metadata_caches=metadata_caches, ) ) formatted_reports = [] for formatted_report in formatted_reports_iter: # Reports are yielded as soon as they're available. Stream the output to the # terminal. print(formatted_report) # save the report from the iterator for later use formatted_reports.append(formatted_report) if not args.compact: print() print( f"Found {len(formatted_reports)} reports in {len(file_paths)} files in " + f"{time.time() - start_time :.2f} seconds." ) # Return with an exit code of 1 if there are any violations found. return int(bool(formatted_reports)) if __name__ == "__main__": sys.exit(main(sys.argv[1:]))
signin.js
(function signInIIFE() { const usernameField = document.getElementsByName('username')[0]; document.getElementsByClassName('sign-in-form')[0].onsubmit = onSignInFormSubmit; function
() { window.sessionStorage.setItem('username', usernameField.value); console.log(window.sessionStorage.getItem('username')); } })();
onSignInFormSubmit
registry_create.go
package registries import ( "errors" "fmt" "net/http" "github.com/asaskevich/govalidator" httperror "github.com/portainer/libhttp/error" "github.com/portainer/libhttp/request" "github.com/portainer/libhttp/response" portainer "github.com/portainer/portainer/api" ) type registryCreatePayload struct { // Name that will be used to identify this registry Name string `example:"my-registry" validate:"required"` // Registry Type. Valid values are: 1 (Quay.io), 2 (Azure container registry), 3 (custom registry), 4 (Gitlab registry) or 5 (ProGet registry) Type portainer.RegistryType `example:"1" validate:"required" enums:"1,2,3,4,5"` // URL or IP address of the Docker registry URL string `example:"registry.mydomain.tld:2375/feed" validate:"required"` // BaseURL required for ProGet registry BaseURL string `example:"registry.mydomain.tld:2375"` // Is authentication against this registry enabled Authentication bool `example:"false" validate:"required"` // Username used to authenticate against this registry. Required when Authentication is true Username string `example:"registry_user"` // Password used to authenticate against this registry. required when Authentication is true Password string `example:"registry_password"` // Gitlab specific details, required when type = 4 Gitlab portainer.GitlabRegistryData // Quay specific details, required when type = 1 Quay portainer.QuayRegistryData } func (payload *registryCreatePayload) Validate(_ *http.Request) error { if govalidator.IsNull(payload.Name) { return errors.New("Invalid registry name") } if govalidator.IsNull(payload.URL) { return errors.New("Invalid registry URL") } if payload.Authentication && (govalidator.IsNull(payload.Username) || govalidator.IsNull(payload.Password)) { return errors.New("Invalid credentials. Username and password must be specified when authentication is enabled") }
switch payload.Type { case portainer.QuayRegistry, portainer.AzureRegistry, portainer.CustomRegistry, portainer.GitlabRegistry, portainer.ProGetRegistry: default: return errors.New("invalid registry type. Valid values are: 1 (Quay.io), 2 (Azure container registry), 3 (custom registry), 4 (Gitlab registry) or 5 (ProGet registry)") } if payload.Type == portainer.ProGetRegistry && payload.BaseURL == "" { return fmt.Errorf("BaseURL is required for registry type %d (ProGet)", portainer.ProGetRegistry) } return nil } // @id RegistryCreate // @summary Create a new registry // @description Create a new registry. // @description **Access policy**: administrator // @tags registries // @security jwt // @accept json // @produce json // @param body body registryCreatePayload true "Registry details" // @success 200 {object} portainer.Registry "Success" // @failure 400 "Invalid request" // @failure 500 "Server error" // @router /registries [post] func (handler *Handler) registryCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { var payload registryCreatePayload err := request.DecodeAndValidateJSONPayload(r, &payload) if err != nil { return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err} } registry := &portainer.Registry{ Type: portainer.RegistryType(payload.Type), Name: payload.Name, URL: payload.URL, BaseURL: payload.BaseURL, Authentication: payload.Authentication, Username: payload.Username, Password: payload.Password, UserAccessPolicies: portainer.UserAccessPolicies{}, TeamAccessPolicies: portainer.TeamAccessPolicies{}, Gitlab: payload.Gitlab, Quay: payload.Quay, } err = handler.DataStore.Registry().CreateRegistry(registry) if err != nil { return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist the registry inside the database", err} } hideFields(registry) return response.JSON(w, registry) }
planar_utils.py
import matplotlib.pyplot as plt import numpy as np import sklearn import sklearn.datasets import sklearn.linear_model def plot_decision_boundary(model, X, y): # Set min and max values and give it some padding x_min, x_max = X[0, :].min() - 1, X[0, :].max() + 1 y_min, y_max = X[1, :].min() - 1, X[1, :].max() + 1 h = 0.01 # Generate a grid of points with distance h between them xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) # Predict the function value for the whole grid Z = model(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) # Plot the contour and training examples plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral) plt.ylabel('x2') plt.xlabel('x1') plt.scatter(X[0, :], X[1, :], c=y[0], cmap=plt.cm.Spectral) def sigmoid(x):
def load_planar_dataset(): np.random.seed(1) m = 400 # number of examples N = int(m/2) # number of points per class D = 2 # dimensionality X = np.zeros((m,D)) # data matrix where each row is a single example Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue) a = 4 # maximum ray of the flower for j in range(2): ix = range(N*j,N*(j+1)) t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] Y[ix] = j X = X.T Y = Y.T return X, Y def load_extra_datasets(): N = 200 noisy_circles = sklearn.datasets.make_circles(n_samples=N, factor=.5, noise=.3) noisy_moons = sklearn.datasets.make_moons(n_samples=N, noise=.2) blobs = sklearn.datasets.make_blobs(n_samples=N, random_state=5, n_features=2, centers=6) gaussian_quantiles = sklearn.datasets.make_gaussian_quantiles(mean=None, cov=0.5, n_samples=N, n_features=2, n_classes=2, shuffle=True, random_state=None) no_structure = np.random.rand(N, 2), np.random.rand(N, 2) return noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure
""" Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size. Return: s -- sigmoid(x) """ s = 1/(1+np.exp(-x)) return s
get_gateways_credential_id_for_workspace_parameters.go
// Code generated by go-swagger; DO NOT EDIT. package v4_workspace_id_connectors // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "time" "golang.org/x/net/context" "github.com/go-openapi/errors" "github.com/go-openapi/runtime" cr "github.com/go-openapi/runtime/client" "github.com/go-openapi/swag" strfmt "github.com/go-openapi/strfmt" ) // NewGetGatewaysCredentialIDForWorkspaceParams creates a new GetGatewaysCredentialIDForWorkspaceParams object // with the default values initialized. func NewGetGatewaysCredentialIDForWorkspaceParams() *GetGatewaysCredentialIDForWorkspaceParams { var () return &GetGatewaysCredentialIDForWorkspaceParams{ timeout: cr.DefaultTimeout, } } // NewGetGatewaysCredentialIDForWorkspaceParamsWithTimeout creates a new GetGatewaysCredentialIDForWorkspaceParams object // with the default values initialized, and the ability to set a timeout on a request func NewGetGatewaysCredentialIDForWorkspaceParamsWithTimeout(timeout time.Duration) *GetGatewaysCredentialIDForWorkspaceParams { var () return &GetGatewaysCredentialIDForWorkspaceParams{ timeout: timeout, } } // NewGetGatewaysCredentialIDForWorkspaceParamsWithContext creates a new GetGatewaysCredentialIDForWorkspaceParams object // with the default values initialized, and the ability to set a context for a request func NewGetGatewaysCredentialIDForWorkspaceParamsWithContext(ctx context.Context) *GetGatewaysCredentialIDForWorkspaceParams { var () return &GetGatewaysCredentialIDForWorkspaceParams{ Context: ctx, } } // NewGetGatewaysCredentialIDForWorkspaceParamsWithHTTPClient creates a new GetGatewaysCredentialIDForWorkspaceParams object // with the default values initialized, and the ability to set a custom HTTPClient for a request func NewGetGatewaysCredentialIDForWorkspaceParamsWithHTTPClient(client *http.Client) *GetGatewaysCredentialIDForWorkspaceParams { var () return &GetGatewaysCredentialIDForWorkspaceParams{ HTTPClient: client, } } /*GetGatewaysCredentialIDForWorkspaceParams contains all the parameters to send to the API endpoint for the get gateways credential Id for workspace operation typically these are written to a http.Request */ type GetGatewaysCredentialIDForWorkspaceParams struct { /*AvailabilityZone*/ AvailabilityZone *string /*CredentialName*/ CredentialName *string /*PlatformVariant*/ PlatformVariant *string /*Region*/ Region *string /*WorkspaceID*/ WorkspaceID int64 timeout time.Duration Context context.Context HTTPClient *http.Client } // WithTimeout adds the timeout to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithTimeout(timeout time.Duration) *GetGatewaysCredentialIDForWorkspaceParams { o.SetTimeout(timeout) return o } // SetTimeout adds the timeout to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetTimeout(timeout time.Duration) { o.timeout = timeout } // WithContext adds the context to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithContext(ctx context.Context) *GetGatewaysCredentialIDForWorkspaceParams { o.SetContext(ctx) return o } // SetContext adds the context to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetContext(ctx context.Context) { o.Context = ctx } // WithHTTPClient adds the HTTPClient to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithHTTPClient(client *http.Client) *GetGatewaysCredentialIDForWorkspaceParams { o.SetHTTPClient(client) return o } // SetHTTPClient adds the HTTPClient to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetHTTPClient(client *http.Client) { o.HTTPClient = client } // WithAvailabilityZone adds the availabilityZone to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithAvailabilityZone(availabilityZone *string) *GetGatewaysCredentialIDForWorkspaceParams { o.SetAvailabilityZone(availabilityZone) return o } // SetAvailabilityZone adds the availabilityZone to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetAvailabilityZone(availabilityZone *string) { o.AvailabilityZone = availabilityZone } // WithCredentialName adds the credentialName to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithCredentialName(credentialName *string) *GetGatewaysCredentialIDForWorkspaceParams { o.SetCredentialName(credentialName) return o } // SetCredentialName adds the credentialName to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetCredentialName(credentialName *string) { o.CredentialName = credentialName } // WithPlatformVariant adds the platformVariant to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithPlatformVariant(platformVariant *string) *GetGatewaysCredentialIDForWorkspaceParams { o.SetPlatformVariant(platformVariant) return o } // SetPlatformVariant adds the platformVariant to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetPlatformVariant(platformVariant *string) { o.PlatformVariant = platformVariant } // WithRegion adds the region to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithRegion(region *string) *GetGatewaysCredentialIDForWorkspaceParams { o.SetRegion(region) return o } // SetRegion adds the region to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetRegion(region *string) { o.Region = region } // WithWorkspaceID adds the workspaceID to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) WithWorkspaceID(workspaceID int64) *GetGatewaysCredentialIDForWorkspaceParams { o.SetWorkspaceID(workspaceID) return o } // SetWorkspaceID adds the workspaceId to the get gateways credential Id for workspace params func (o *GetGatewaysCredentialIDForWorkspaceParams) SetWorkspaceID(workspaceID int64) { o.WorkspaceID = workspaceID } // WriteToRequest writes these params to a swagger request func (o *GetGatewaysCredentialIDForWorkspaceParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error { if err := r.SetTimeout(o.timeout); err != nil { return err } var res []error if o.AvailabilityZone != nil { // query param availabilityZone var qrAvailabilityZone string if o.AvailabilityZone != nil { qrAvailabilityZone = *o.AvailabilityZone } qAvailabilityZone := qrAvailabilityZone if qAvailabilityZone != "" { if err := r.SetQueryParam("availabilityZone", qAvailabilityZone); err != nil { return err } }
// query param credentialName var qrCredentialName string if o.CredentialName != nil { qrCredentialName = *o.CredentialName } qCredentialName := qrCredentialName if qCredentialName != "" { if err := r.SetQueryParam("credentialName", qCredentialName); err != nil { return err } } } if o.PlatformVariant != nil { // query param platformVariant var qrPlatformVariant string if o.PlatformVariant != nil { qrPlatformVariant = *o.PlatformVariant } qPlatformVariant := qrPlatformVariant if qPlatformVariant != "" { if err := r.SetQueryParam("platformVariant", qPlatformVariant); err != nil { return err } } } if o.Region != nil { // query param region var qrRegion string if o.Region != nil { qrRegion = *o.Region } qRegion := qrRegion if qRegion != "" { if err := r.SetQueryParam("region", qRegion); err != nil { return err } } } // path param workspaceId if err := r.SetPathParam("workspaceId", swag.FormatInt64(o.WorkspaceID)); err != nil { return err } if len(res) > 0 { return errors.CompositeValidationError(res...) } return nil }
} if o.CredentialName != nil {
door.ts
import Tile from "./tile"; import Wall from "../tiles/wall"; import None from "../tiles/none"; import { Room } from "../rooms/room"; export default class
extends Tile { clearance?: { xInc?: number; yInc?: number; dir?: string }; constructor(x: number, y: number, room: Room) { super(x, y, room); this.clearance = this.determineClearance(); this.tileLabel = "Door"; } placeTile(): void { this.tileIndex = 23; return super.placeTile(); } // Calculate which way the door is facing determineClearance?(): { xInc: number; yInc: number; dir: string } { return this.x === 0 ? { xInc: 1, yInc: 0, dir: "e" } : this.x === this.room.width - 1 ? { xInc: -1, yInc: 0, dir: "w" } : this.y === 0 ? { xInc: 0, yInc: 1, dir: "s" } : { xInc: 0, yInc: -1, dir: "n" }; } clearDoorway(room) { const doorTile: Door = room.tiles[this.y][this.x]; // what direction to head in const { xInc, yInc } = doorTile.clearance; let [x, y] = [xInc, yInc]; // walk in a direction and check for blocking walls let clear = false; while (!clear) { const tileY = room.tiles[this.y + y] || []; const nextTile = tileY[this.x + x]; if (!nextTile) { // if we hit the edge of the room, step back and place wall const lastY = this.y + y - yInc; const lastX = this.x + x - xInc; room.tiles[lastY][lastX] = new Wall(lastX, lastY, room); clear = true; } else if (nextTile.tileLabel === "Wall") { room.tiles[nextTile.y][nextTile.x] = new None(nextTile.x, nextTile.y, room); x += xInc; y += yInc; } else { clear = true; } } } }
Door
results_spider.py
from os import environ import base64 from multiprocessing import Process, Queue from scrapy.spiders.init import InitSpider from scrapy.http import Request, FormRequest from scrapy_splash import SplashRequest import scrapy.crawler as crawler from twisted.internet import reactor from ..captcha import captcha_solver class ResultsSpider(InitSpider): name = 'results' allowed_domains = ['report.aldel.org'] login_page = 'http://report.aldel.org/student_page.php' start_urls = ['http://report.aldel.org/student/test_marks_report.php'] def __init__(self, USERNAME, PASSWORD, *args, **kwargs): super(ResultsSpider, self).__init__(*args, **kwargs) self.USERNAME = USERNAME self.PASSWORD = PASSWORD def init_request(self): """This function is called before crawling starts.""" return Request(url=self.login_page, callback=self.login) def
(self, response): """Generate a login request.""" sessionID = str(response.headers.getlist('Set-Cookie')[0].decode().split(';')[0].split("=")[1]) captcha_answer = captcha_solver(sessionID) self.logger.info("Captcha Answer: %s" % (captcha_answer)) return FormRequest.from_response(response, formdata={'studentid': self.USERNAME, 'studentpwd': self.PASSWORD, 'captcha_code':captcha_answer}, callback=self.check_login_response) def check_login_response(self, response): """Check the response returned by a login request to see if we are successfully logged in.""" if self.USERNAME in response.body.decode(): self.logger.info("Login Successful!") # Now the crawling can begin.. return self.initialized() else: self.logger.warning("Login failed! Check site status and credentials.") # Something went wrong, we couldn't log in, so nothing happens. def parse(self, response): '''Start SplashRequest''' url = 'http://report.aldel.org/student/test_marks_report.php' splash_args = { 'html': 1, 'png': 1, 'wait':0.1, 'render_all':1 } self.logger.info("Taking snapshot of Test Report for %s..." %(self.USERNAME)) yield SplashRequest(url, self.parse_result, endpoint='render.json', args=splash_args) def parse_result(self, response): '''Store the screenshot''' imgdata = base64.b64decode(response.data['png']) filename = 'files/{}_tests.png'.format(self.USERNAME) with open(filename, 'wb') as f: f.write(imgdata) self.logger.info("Saved test report as: {}_tests.png".format(self.USERNAME)) def scrape_results(USERNAME, PASSWORD): '''Run the spider multiple times, without hitting ReactorNotRestartable.Forks own process.''' def f(q): try: runner = crawler.CrawlerRunner({ 'DOWNLOADER_MIDDLEWARES': {'scrapy_splash.SplashCookiesMiddleware': 723, 'scrapy_splash.SplashMiddleware': 725, 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,}, 'SPLASH_URL':environ['SPLASH_INSTANCE'], 'SPIDER_MIDDLEWARES':{'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,}, 'DUPEFILTER_CLASS':'scrapy_splash.SplashAwareDupeFilter', }) deferred = runner.crawl(ResultsSpider, USERNAME=USERNAME, PASSWORD=PASSWORD) deferred.addBoth(lambda _: reactor.stop()) reactor.run() q.put(None) except Exception as e: q.put(e) q = Queue() p = Process(target=f, args=(q,)) p.start() result = q.get() p.join() if result is not None: raise result
login
SpecializedDefenses.spec.js
describe('Specialized Defenses', function() { integration(function() { describe('Specialized Defenses\'s ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['matsu-berserker'], hand: ['charge'], dynastyDiscard: ['isawa-kaede'] }, player2: { provinces: ['kuroi-mori', 'toshi-ranbo'], hand: ['specialized-defenses'] } }); this.isawaKaede = this.player1.placeCardInProvince('isawa-kaede'); this.kuroiMori = this.player2.findCardByName('kuroi-mori'); this.toshiRanbo = this.player2.findCardByName('toshi-ranbo'); this.specializedDefenses = this.player2.findCardByName('specialized-defenses'); });
expect(this.player2).toHavePrompt('Initiate an action'); }); describe('during a conflict', function () { beforeEach(function () { this.noMoreActions(); this.initiateConflict({ province: this.kuroiMori, attackers: ['matsu-berserker'], defenders: [] }); }); it('should not be playable when the element and the contested ring do not match', function () { expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard('specialized-defenses'); expect(this.player2).toHavePrompt('Conflict Action Window'); }); it('should be playable when the contested ring matches the province element', function () { this.player2.clickCard(this.kuroiMori); this.player2.clickPrompt('Switch the contested ring'); this.player2.clickRing('void'); expect(this.game.currentConflict.ring.element).toBe('void'); expect(this.player1).toHavePrompt('Conflict Action Window'); this.player1.pass(); this.player2.clickCard('specialized-defenses'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.kuroiMori.strength).toBe(8); }); it('should be playable if the player has claimed the matching ring', function () { this.player2.claimRing('void'); this.player2.clickCard('specialized-defenses'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.kuroiMori.strength).toBe(8); }); it('should be playable if the contested ring has an additional element which matches', function () { this.player2.pass(); this.player1.clickCard('charge'); this.player1.clickCard(this.isawaKaede); expect(this.isawaKaede.inConflict).toBe(true); this.player2.clickCard('specialized-defenses'); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.kuroiMori.strength).toBe(8); }); }); it('should interact correctly with Toshi Ranbo', function() { this.noMoreActions(); this.initiateConflict({ province: this.toshiRanbo, attackers: ['matsu-berserker'], defenders: [] }); this.player2.clickCard(this.specializedDefenses); expect(this.player1).toHavePrompt('Conflict Action Window'); expect(this.toshiRanbo.strength).toBe(6); }); }); }); });
it('should not be playable outside of a conflict', function () { this.player1.pass(); this.player2.clickCard('specialized-defenses');
product-list.component.ts
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { Product } from '../product'; @Component({ selector: 'pm-product-list', templateUrl: './product-list.component.html', styleUrls: ['./product-list.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class
{ // TODO: Component should be simplified further. Should purely be a list. // It doesn't make sense to know that the display code can be toggled but not know how to toggle it - this should be completely controlled by a parent component pageTitle = 'Products'; @Input() products: Product[]; @Input() selectedProduct: Product; @Input() displayCode: boolean; @Input() errorMessage: string; @Output() displayCodeChanged = new EventEmitter<void>(); @Output() initializeNewProduct = new EventEmitter<void>(); @Output() productWasSelected = new EventEmitter<Product>(); constructor() { } checkChanged(): void { this.displayCodeChanged.emit(); } newProduct(): void { this.initializeNewProduct.emit(); } productSelected(product: Product): void { this.productWasSelected.emit(product); } }
ProductListComponent
kindle_notebook.py
#!/usr/local/bin/python # encoding: utf-8 """ *Convert the HTML export of kindle notebooks (from kindle apps) to markdown* :Author: David Young :Date Created: October 17, 2016 """ ################# GLOBAL IMPORTS #################### import sys import os import re import collections os.environ['TERM'] = 'vt100' from fundamentals import tools # THESE ARE THE 4 KINDLE COLORS ARE HOW THEY TRANSLATE TO MD colorCode = { "blue": "code", "yellow": "text", "orange": "quote", "pink": "header" } class kindle_notebook(): """ *convert the HTML export of kindle notebooks (from kindle apps) to markdown* **Key Arguments:** - ``log`` -- logger - ``kindleExportPath`` -- path to the exported kindle HTML file - ``outputPath`` -- the output path to the md file. **Usage:** To convert the exported HTML file of annotation and notes from a kindle book or document to markdown, run the code: .. code-block:: python from polyglot.markdown import kindle_notebook nb = kindle_notebook( log=log, kindleExportPath="/path/to/kindle_export.html", outputPath="/path/to/coverted_annotations.md" ) nb.convert() The colours of the annotations convert to markdown attributes via the following key: .. code-block: json colorCode = { "blue": "code", "yellow": "text", "orange": "quote", "pink": "header" } """ # Initialisation def __init__( self, log, kindleExportPath, outputPath ): self.log = log log.debug("instansiating a new 'kindle_notebook' object") self.kindleExportPath = kindleExportPath self.outputPath = outputPath # xt-self-arg-tmpx # Initial Actions return None def convert(self): """ *convert the kindle_notebook object* **Return:** - ``kindle_notebook`` **Usage:** .. todo:: - add usage info - create a sublime snippet for usage - update the package tutorial if needed .. code-block:: python usage code """ self.log.debug('starting the ``convert`` method') import codecs pathToReadFile = self.kindleExportPath try: self.log.debug("attempting to open the file %s" % (pathToReadFile,)) readFile = codecs.open(pathToReadFile, encoding='utf-8', mode='r') annotations = readFile.read() readFile.close() except IOError, e: message = 'could not open the file %s' % (pathToReadFile,) self.log.critical(message) raise IOError(message) annotations = annotations.replace(u"’", "'").replace( u"“ ", '"').replace(u"“", '"').replace(u"”", '"').replace(u"–", "-").replace(u"—", "-") # COLLECT KEY COMPONENTS try: title = self.find_component("bookTitle", annotations) except: return False regex = re.compile(r'_xx\d*xx$') title = regex.sub("", title) authors = self.find_component("authors", annotations) citation = self.find_component("citation", annotations) # CLEAN THE CITATION regex = re.compile(r'</?i>', re.S) citation = regex.sub('*', citation) regex = re.compile(r'Citation \(.*?\): ', re.S) citation = regex.sub('', citation).replace(" Kindle edition.", "") # COLLECT ANNOTATIONS annotationDict = {} matchObject = re.finditer( r"""<div class="noteHeading">\s+Highlight\(<span.*?>(?P<color>.*?)</span>\)((?P<section>.*?)Page (?P<page>\d+))?.*?Location (?P<location>\d+)\s+</div>\s+<div class="noteText">(?P<note>.*?)</div>""", annotations, flags=re.S ) for match in matchObject: location = int(match.group("location")) location = "%(location)09d" % locals() if match.group("page"): try: annotationDict[location] = {"color": match.group("color"), "page": match.group( "page"), "section": self.clean(match.group("section"))[3:-2], "note": self.clean(match.group("note"))} except: print match.group("note") sys.exit(0) else: try: annotationDict[location] = {"color": match.group( "color"), "note": self.clean(match.group("note"))} except: print match.group("note") sys.exit(0) # COLLECT PERSONAL NOTES matchObject = re.finditer(
flags=re.S ) for match in matchObject: location = int(match.group("location")) location = "%(location)09dnote" % locals() if match.group("page"): annotationDict[location] = {"color": None, "page": match.group( "page"), "note": self.clean(match.group("note"))} else: annotationDict[location] = { "color": None, "note": self.clean(match.group("note"))} annotationDict = collections.OrderedDict( sorted(annotationDict.items())) mdContent = "\n# %(title)s\n\nAuthors: **%(authors)s**\n\n" % locals() for k, v in annotationDict.iteritems(): mdContent += self.convertToMD(v) + "\n\n" if len(annotationDict) == 0: return False pathToWriteFile = self.outputPath try: self.log.debug("attempting to open the file %s" % (pathToWriteFile,)) writeFile = codecs.open( pathToWriteFile, encoding='utf-8', mode='w') except IOError, e: message = 'could not open the file %s' % (pathToWriteFile,) self.log.critical(message) raise IOError(message) writeFile.write(mdContent) writeFile.close() self.log.debug('completed the ``convert`` method') return pathToWriteFile def clean(self, text): return text.strip().replace(u"’", "'").replace(u"“ ", '"').replace(u"“", '"').replace(u"”", '"').replace(u"–", "-").replace(u"—", "-") def find_component(self, divtag, annotations): component = re.search( r"""<div class="%(divtag)s">(.*?)</div>""" % locals(), annotations, re.S) return self.clean(component.group(1)) def convertToMD(self, kindleNote): if kindleNote["color"] == None: return "**NOTE**\n: " + kindleNote["note"].replace("\n", " ") mdType = colorCode[kindleNote["color"]] if mdType == "code": return "```\n" + kindleNote["note"] + "\n```" elif mdType == "text": return kindleNote["note"] elif mdType == "header": regex = re.compile(r'_xx\d*xx$') kindleNote["note"] = regex.sub("", kindleNote["note"]) return "## " + kindleNote["note"].replace("\n", " ").replace(" ", " ").replace(" ", " ").replace(" ", " ") elif mdType == "quote": return "> " + kindleNote["note"].replace("\n", "> ") # xt-class-method # 5. @flagged: what actions of the base class(es) need ammending? ammend them here # Override Method Attributes # method-override-tmpx
r"""<div class="noteHeading">\s+Note -( Page (?P<page>\d+))?.*?Location (?P<location>\d+)\s+</div>\s+<div class="noteText">(?P<note>.*?)</div>""", annotations,
code.py
# -------------- # Importing header files import numpy as np # Path of the file has been stored in variable called 'path' #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] data = np.genfromtxt(path, delimiter=",", skip_header=1) print("\nData: \n\n", data) print("\nType of data: \n\n", type(data)) census = np.concatenate((data, new_record), axis=0) print(census) #Code starts here # -------------- #Code starts here age=census[:,0] print(age) max_age = np.max(age) min_age = np.min(age) age_mean = np.mean(age) age_std = np.std(age)
print("max of age : ", max_age) print("min of age : ", min_age) print("mean of age : ", age_mean) print("standard deviation of age : ", age_std) # -------------- #Code starts here race_0 = census[census[:,2] == 0] race_1 = census[census[:,2] == 1] race_2 = census[census[:,2] == 2] race_3 = census[census[:,2] == 3] race_4 = census[census[:,2] == 4] len_0 = len(race_0) len_1 = len(race_1) len_2 = len(race_2) len_3 = len(race_3) len_4 = len(race_4) minority_race = 3 print(race_0) # -------------- #Code starts here senior_citizens = census[census[:, 0] > 60] working_hours = senior_citizens[:,6] working_hours_sum = working_hours.sum() senior_citizens_len = len(senior_citizens) avg_working_hours = working_hours_sum / senior_citizens_len print(avg_working_hours) # -------------- #Code starts here high = census[census[:,1] > 10] low = census[census[:,1] <= 10] avg_pay_high = high[:, 7].mean() avg_pay_low = low[:, 7].mean() if avg_pay_high > avg_pay_low: print("Better education leads to better pay") else: print("Better education does not lead to better pay")
conjure.go
package tapdance import ( "bytes" "context" "crypto/hmac" "crypto/sha256" "encoding/binary" "encoding/hex" "fmt" "io" "math/big" "net" "net/http" "strconv" "sync" "time" pt "git.torproject.org/pluggable-transports/goptlib.git" "github.com/golang/protobuf/proto" pb "github.com/refraction-networking/gotapdance/protobuf" ps "github.com/refraction-networking/gotapdance/tapdance/phantoms" tls "github.com/refraction-networking/utls" "gitlab.com/yawning/obfs4.git/common/ntor" "gitlab.com/yawning/obfs4.git/transports/obfs4" "golang.org/x/crypto/curve25519" "golang.org/x/crypto/hkdf" ) // V6 - Struct to track V6 support and cache result across sessions type V6 struct { support bool include uint } // Registrar defines the interface for a service executing // decoy registrations. type Registrar interface { Register(*ConjureSession, context.Context) (*ConjureReg, error) } type DecoyRegistrar struct { // TcpDialer is a custom TCP dailer to use when establishing TCP connections // to decoys. When nil, Dialer.TcpDialer will be used. TcpDialer func(context.Context, string, string) (net.Conn, error) } func (r DecoyRegistrar) Register(cjSession *ConjureSession, ctx context.Context) (*ConjureReg, error) { Logger().Debugf("%v Registering V4 and V6 via DecoyRegistrar", cjSession.IDString()) // Choose N (width) decoys from decoylist decoys, err := SelectDecoys(cjSession.Keys.SharedSecret, cjSession.V6Support.include, cjSession.Width) if err != nil { Logger().Warnf("%v failed to select decoys: %v", cjSession.IDString(), err) return nil, err } cjSession.RegDecoys = decoys phantom4, phantom6, err := SelectPhantom(cjSession.Keys.ConjureSeed, cjSession.V6Support.include) if err != nil { Logger().Warnf("%v failed to select Phantom: %v", cjSession.IDString(), err) return nil, err } //[reference] Prepare registration reg := &ConjureReg{ sessionIDStr: cjSession.IDString(), keys: cjSession.Keys, stats: &pb.SessionStats{}, phantom4: phantom4, phantom6: phantom6, v6Support: cjSession.V6Support.include, covertAddress: cjSession.CovertAddress, transport: cjSession.Transport, TcpDialer: cjSession.TcpDialer, useProxyHeader: cjSession.UseProxyHeader, } if r.TcpDialer != nil { reg.TcpDialer = r.TcpDialer } // //[TODO]{priority:later} How to pass context to multiple registration goroutines? if ctx == nil { ctx = context.Background() } width := uint(len(cjSession.RegDecoys)) if width < cjSession.Width { Logger().Warnf("%v Using width %v (default %v)", cjSession.IDString(), width, cjSession.Width) } Logger().Debugf("%v Registration - v6:%v, covert:%v, phantoms:%v,[%v], width:%v, transport:%v", reg.sessionIDStr, reg.v6SupportStr(), reg.covertAddress, reg.phantom4.String(), reg.phantom6.String(), cjSession.Width, cjSession.Transport, ) //[reference] Send registrations to each decoy dialErrors := make(chan error, width) for _, decoy := range cjSession.RegDecoys { Logger().Debugf("%v Sending Reg: %v, %v", cjSession.IDString(), decoy.GetHostname(), decoy.GetIpAddrStr()) //decoyAddr := decoy.GetIpAddrStr() go reg.send(ctx, decoy, dialErrors, cjSession.registrationCallback) } //[reference] Dial errors happen immediately so block until all N dials complete var unreachableCount uint = 0 for err := range dialErrors { if err != nil { Logger().Debugf("%v %v", cjSession.IDString(), err) if dialErr, ok := err.(RegError); ok && dialErr.code == Unreachable { // If we failed because ipv6 network was unreachable try v4 only. unreachableCount++ if unreachableCount < width { continue } else { break } } } //[reference] if we succeed or fail for any other reason then the network is reachable and we can continue break } //[reference] if ALL fail to dial return error (retry in parent if ipv6 unreachable) if unreachableCount == width { Logger().Debugf("%v NETWORK UNREACHABLE", cjSession.IDString()) return nil, &RegError{code: Unreachable, msg: "All decoys failed to register -- Dial Unreachable"} } // randomized sleeping here to break the intraflow signal toSleep := reg.getRandomDuration(3000, 212, 3449) Logger().Debugf("%v Successfully sent registrations, sleeping for: %v", cjSession.IDString(), toSleep) sleepWithContext(ctx, toSleep) return reg, nil } // Registration strategy using a centralized REST API to // create registrations. Only the Endpoint need be specified; // the remaining fields are valid with their zero values and // provide the opportunity for additional control over the process. type APIRegistrar struct { // Endpoint to use in registration request Endpoint string // HTTP client to use in request Client *http.Client // Length of time to delay after confirming successful // registration before attempting a connection, // allowing for propagation throughout the stations. ConnectionDelay time.Duration // Maximum number of retries before giving up MaxRetries int // A secondary registration method to use on failure. // Because the API registration can give us definite // indication of a failure to register, this can be // used as a "backup" in the case of the API being // down or being blocked. // // If this field is nil, no secondary registration will // be attempted. If it is non-nil, after failing to register // (retrying MaxRetries times) we will fall back to // the Register method on this field. SecondaryRegistrar Registrar } func (r APIRegistrar) Register(cjSession *ConjureSession, ctx context.Context) (*ConjureReg, error) { Logger().Debugf("%v registering via APIRegistrar", cjSession.IDString()) // TODO: this section is duplicated from DecoyRegistrar; consider consolidating phantom4, phantom6, err := SelectPhantom(cjSession.Keys.ConjureSeed, cjSession.V6Support.include) if err != nil { Logger().Warnf("%v failed to select Phantom: %v", cjSession.IDString(), err) return nil, err } // [reference] Prepare registration reg := &ConjureReg{ sessionIDStr: cjSession.IDString(), keys: cjSession.Keys, stats: &pb.SessionStats{}, phantom4: phantom4, phantom6: phantom6, v6Support: cjSession.V6Support.include, covertAddress: cjSession.CovertAddress, transport: cjSession.Transport, TcpDialer: cjSession.TcpDialer, useProxyHeader: cjSession.UseProxyHeader, } c2s := reg.generateClientToStation() protoPayload := pb.C2SWrapper{ SharedSecret: cjSession.Keys.SharedSecret, RegistrationPayload: c2s, } payload, err := proto.Marshal(&protoPayload) if err != nil { Logger().Warnf("%v failed to marshal ClientToStation payload: %v", cjSession.IDString(), err) return nil, err } if r.Client == nil { // Transports should ideally be re-used for TCP connection pooling, // but each registration is most likely making precisely one request, // or if it's making more than one, is most likely due to an underlying // connection issue rather than an application-level error anyways. t := http.DefaultTransport.(*http.Transport).Clone() t.DialContext = reg.TcpDialer r.Client = &http.Client{Transport: t} } tries := 0 for tries < r.MaxRetries+1 { tries++ err = r.executeHTTPRequest(ctx, cjSession, payload) if err == nil { Logger().Debugf("%v API registration succeeded", cjSession.IDString()) if r.ConnectionDelay != 0 { Logger().Debugf("%v sleeping for %v", cjSession.IDString(), r.ConnectionDelay) sleepWithContext(ctx, r.ConnectionDelay) } return reg, nil } Logger().Warnf("%v failed API registration, attempt %d/%d", cjSession.IDString(), tries, r.MaxRetries+1) } // If we make it here, we failed API registration Logger().Warnf("%v giving up on API registration", cjSession.IDString()) if r.SecondaryRegistrar != nil { Logger().Debugf("%v trying secondary registration method", cjSession.IDString()) return r.SecondaryRegistrar.Register(cjSession, ctx) } return nil, err } func (r APIRegistrar) executeHTTPRequest(ctx context.Context, cjSession *ConjureSession, payload []byte) error { req, err := http.NewRequestWithContext(ctx, "POST", r.Endpoint, bytes.NewReader(payload)) if err != nil { Logger().Warnf("%v failed to create HTTP request to registration endpoint %s: %v", cjSession.IDString(), r.Endpoint, err) return err } resp, err := r.Client.Do(req) if err != nil { Logger().Warnf("%v failed to do HTTP request to registration endpoint %s: %v", cjSession.IDString(), r.Endpoint, err) return err } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { Logger().Warnf("%v got non-success response code %d from registration endpoint %v", cjSession.IDString(), resp.StatusCode, r.Endpoint) return fmt.Errorf("non-success response code %d on %s", resp.StatusCode, r.Endpoint) } return nil } const ( v4 uint = iota v6 both ) //[TODO]{priority:winter-break} make this not constant const defaultRegWidth = 5 // DialConjureAddr - Perform Registration and Dial after creating a Conjure session from scratch func DialConjureAddr(ctx context.Context, address string, registrationMethod Registrar) (net.Conn, error) { cjSession := makeConjureSession(address, pb.TransportType_Min) return DialConjure(ctx, cjSession, registrationMethod) } // DialConjure - Perform Registration and Dial on an existing Conjure session func
(ctx context.Context, cjSession *ConjureSession, registrationMethod Registrar) (net.Conn, error) { if cjSession == nil { return nil, fmt.Errorf("No Session Provided") } cjSession.setV6Support(both) // TODO: WebRTC Init Connection and get LocalSDP, send with Register() // Choose Phantom Address in Register depending on v6 support. registration, err := registrationMethod.Register(cjSession, ctx) if err != nil { Logger().Debugf("%v Failed to register: %v", cjSession.IDString(), err) return nil, err } Logger().Debugf("%v Attempting to Connect ...", cjSession.IDString()) // TODO: WebRTC Set RemoteSDP in Connect() return registration.Connect(ctx) // return Connect(cjSession) } // // testV6 -- This is over simple and incomplete (currently unused) // // checking for unreachable alone does not account for local ipv6 addresses // // [TODO]{priority:winter-break} use getifaddr reverse bindings // func testV6() bool { // dialError := make(chan error, 1) // d := Assets().GetV6Decoy() // go func() { // conn, err := net.Dial("tcp", d.GetIpAddrStr()) // if err != nil { // dialError <- err // return // } // conn.Close() // dialError <- nil // }() // time.Sleep(500 * time.Microsecond) // // The only error that would return before this is a network unreachable error // select { // case err := <-dialError: // Logger().Debugf("v6 unreachable received: %v", err) // return false // default: // return true // } // } // Connect - Dial the Phantom IP address after registration func Connect(ctx context.Context, reg *ConjureReg) (net.Conn, error) { return reg.Connect(ctx) } // ConjureSession - Create a session with details for registration and connection type ConjureSession struct { Keys *sharedKeys Width uint V6Support *V6 UseProxyHeader bool SessionID uint64 RegDecoys []*pb.TLSDecoySpec // pb.DecoyList Phantom *net.IP Transport pb.TransportType CovertAddress string // rtt uint // tracked in stats // THIS IS REQUIRED TO INTERFACE WITH PSIPHON ANDROID // we use their dialer to prevent connection loopback into our own proxy // connection when tunneling the whole device. TcpDialer func(context.Context, string, string) (net.Conn, error) // This part is temporary, for webrtc debugging Webrtc *pb.WebrtcSDP // performance tracking stats *pb.SessionStats } func makeConjureSession(covert string, transport pb.TransportType) *ConjureSession { keys, err := generateSharedKeys(getStationKey()) if err != nil { return nil } //[TODO]{priority:NOW} move v6support initialization to assets so it can be tracked across dials cjSession := &ConjureSession{ Keys: keys, Width: defaultRegWidth, V6Support: &V6{support: true, include: both}, UseProxyHeader: false, Transport: transport, CovertAddress: covert, SessionID: sessionsTotal.GetAndInc(), } // TODO: Optimization // Webrtc Transport: Generate or just Fetch SharedSecret & Seed if transport == pb.TransportType_Webrtc { var seed string = "seedseedseedseed" var sharedsecret string = "secretsecretsecretsecret" paramsWebRTCRandseed := pb.WebrtcRandseed{ Seed: &seed, SharedSecret: &sharedsecret, } paramsWebRTC := pb.WebrtcSDP{ RandSeed: &paramsWebRTCRandseed, } cjSession.Webrtc = &paramsWebRTC } sharedSecretStr := make([]byte, hex.EncodedLen(len(keys.SharedSecret))) hex.Encode(sharedSecretStr, keys.SharedSecret) Logger().Debugf("%v Shared Secret - %s", cjSession.IDString(), sharedSecretStr) Logger().Debugf("%v covert %s", cjSession.IDString(), covert) reprStr := make([]byte, hex.EncodedLen(len(keys.Representative))) hex.Encode(reprStr, keys.Representative) Logger().Debugf("%v Representative - %s", cjSession.IDString(), reprStr) return cjSession } // IDString - Get the ID string for the session func (cjSession *ConjureSession) IDString() string { if cjSession.Keys == nil || cjSession.Keys.SharedSecret == nil { return fmt.Sprintf("[%v-000000]", strconv.FormatUint(cjSession.SessionID, 10)) } secret := make([]byte, hex.EncodedLen(len(cjSession.Keys.SharedSecret))) n := hex.Encode(secret, cjSession.Keys.SharedSecret) if n < 6 { return fmt.Sprintf("[%v-000000]", strconv.FormatUint(cjSession.SessionID, 10)) } return fmt.Sprintf("[%v-%s]", strconv.FormatUint(cjSession.SessionID, 10), secret[:6]) } // String - Print the string for debug and/or logging func (cjSession *ConjureSession) String() string { return cjSession.IDString() // expand for debug?? } type resultTuple struct { conn net.Conn err error } // Simple type alias for brevity type dialFunc = func(ctx context.Context, network, addr string) (net.Conn, error) func (reg *ConjureReg) connect(ctx context.Context, addr string, dialer dialFunc) (net.Conn, error) { //[reference] Create Context with deadline deadline, deadlineAlreadySet := ctx.Deadline() if !deadlineAlreadySet { //[reference] randomized timeout to Dial dark decoy address deadline = time.Now().Add(reg.getRandomDuration(0, 1061*2, 1953*3)) //[TODO]{priority:@sfrolov} explain these numbers and why they were chosen for the boundaries. } childCtx, childCancelFunc := context.WithDeadline(ctx, deadline) defer childCancelFunc() //[reference] Connect to Phantom Host phantomAddr := net.JoinHostPort(addr, "443") // conn, err := reg.TcpDialer(childCtx, "tcp", phantomAddr) return dialer(childCtx, "tcp", phantomAddr) } func (reg *ConjureReg) getFirstConnection(ctx context.Context, dialer dialFunc, phantoms []net.IP) (net.Conn, error) { connChannel := make(chan resultTuple, len(phantoms)) for _, p := range phantoms { go func(phantom net.IP) { conn, err := reg.connect(ctx, phantom.String(), dialer) if err != nil { Logger().Infof("%v failed to dial phantom %v: %v", reg.sessionIDStr, phantom.String(), err) connChannel <- resultTuple{nil, err} return } Logger().Infof("%v Connected to phantom %v using transport %d", reg.sessionIDStr, phantom.String(), reg.transport) connChannel <- resultTuple{conn, nil} }(p) } open := len(phantoms) for open > 0 { rt := <-connChannel if rt.err != nil { open-- continue } // If we made it here we're returning the connection, so // set up a goroutine to close the others go func() { // Close all but one connection (the good one) for open > 1 { t := <-connChannel if t.err == nil { t.conn.Close() } open-- } }() return rt.conn, nil } return nil, fmt.Errorf("no open connections") } // Connect - Use a registration (result of calling Register) to connect to a phantom // Note: This is hacky but should work for v4, v6, or both as any nil phantom addr will // return a dial error and be ignored. func (reg *ConjureReg) Connect(ctx context.Context) (net.Conn, error) { phantoms := []net.IP{*reg.phantom4, *reg.phantom6} //[reference] Provide chosen transport to sent bytes (or connect) if necessary switch reg.transport { case pb.TransportType_Min: conn, err := reg.getFirstConnection(ctx, reg.TcpDialer, phantoms) if err != nil { Logger().Infof("%v failed to form phantom connection: %v", reg.sessionIDStr, err) return nil, err } // Send hmac(seed, str) bytes to indicate to station (min transport) connectTag := conjureHMAC(reg.keys.SharedSecret, "MinTrasportHMACString") conn.Write(connectTag) return conn, nil case pb.TransportType_Obfs4: args := pt.Args{} args.Add("node-id", reg.keys.Obfs4Keys.NodeID.Hex()) args.Add("public-key", reg.keys.Obfs4Keys.PublicKey.Hex()) args.Add("iat-mode", "1") Logger().Infof("%v node_id = %s; public key = %s", reg.sessionIDStr, reg.keys.Obfs4Keys.NodeID.Hex(), reg.keys.Obfs4Keys.PublicKey.Hex()) t := obfs4.Transport{} c, err := t.ClientFactory("") if err != nil { Logger().Infof("%v failed to create client factory: %v", reg.sessionIDStr, err) return nil, err } parsedArgs, err := c.ParseArgs(&args) if err != nil { Logger().Infof("%v failed to parse obfs4 args: %v", reg.sessionIDStr, err) return nil, err } dialer := func(dialContext context.Context, network string, address string) (net.Conn, error) { d := func(network, address string) (net.Conn, error) { return reg.TcpDialer(dialContext, network, address) } return c.Dial("tcp", address, d, parsedArgs) } conn, err := reg.getFirstConnection(ctx, dialer, phantoms) if err != nil { Logger().Infof("%v failed to form obfs4 connection: %v", reg.sessionIDStr, err) return nil, err } return conn, err case pb.TransportType_Null: // Dial and do nothing to the connection before returning it to the user. return reg.getFirstConnection(ctx, reg.TcpDialer, phantoms) default: // If transport is unrecognized use min transport. return nil, fmt.Errorf("Unknown Transport") } } // ConjureReg - Registration structure created for each individual registration within a session. type ConjureReg struct { seed []byte sessionIDStr string phantom4 *net.IP phantom6 *net.IP useProxyHeader bool covertAddress string phantomSNI string v6Support uint transport pb.TransportType // THIS IS REQUIRED TO INTERFACE WITH PSIPHON ANDROID // we use their dialer to prevent connection loopback into our own proxy // connection when tunneling the whole device. TcpDialer func(context.Context, string, string) (net.Conn, error) stats *pb.SessionStats keys *sharedKeys m sync.Mutex } func (reg *ConjureReg) createRequest(tlsConn *tls.UConn, decoy *pb.TLSDecoySpec) ([]byte, error) { //[reference] generate and encrypt variable size payload vsp, err := reg.generateVSP() if err != nil { return nil, err } if len(vsp) > int(^uint16(0)) { return nil, fmt.Errorf("Variable-Size Payload exceeds %v", ^uint16(0)) } encryptedVsp, err := aesGcmEncrypt(vsp, reg.keys.VspKey, reg.keys.VspIv) if err != nil { return nil, err } //[reference] generate and encrypt fixed size payload fsp := reg.generateFSP(uint16(len(encryptedVsp))) encryptedFsp, err := aesGcmEncrypt(fsp, reg.keys.FspKey, reg.keys.FspIv) if err != nil { return nil, err } var tag []byte // tag will be base-64 style encoded tag = append(encryptedVsp, reg.keys.Representative...) tag = append(tag, encryptedFsp...) httpRequest := generateHTTPRequestBeginning(decoy.GetHostname()) keystreamOffset := len(httpRequest) keystreamSize := (len(tag)/3+1)*4 + keystreamOffset // we can't use first 2 bits of every byte wholeKeystream, err := tlsConn.GetOutKeystream(keystreamSize) if err != nil { return nil, err } keystreamAtTag := wholeKeystream[keystreamOffset:] httpRequest = append(httpRequest, reverseEncrypt(tag, keystreamAtTag)...) httpRequest = append(httpRequest, []byte("\r\n\r\n")...) return httpRequest, nil } // Being called in parallel -> no changes to ConjureReg allowed in this function func (reg *ConjureReg) send(ctx context.Context, decoy *pb.TLSDecoySpec, dialError chan error, callback func(*ConjureReg)) { deadline, deadlineAlreadySet := ctx.Deadline() if !deadlineAlreadySet { deadline = time.Now().Add(getRandomDuration(deadlineTCPtoDecoyMin, deadlineTCPtoDecoyMax)) } childCtx, childCancelFunc := context.WithDeadline(ctx, deadline) defer childCancelFunc() //[reference] TCP to decoy tcpToDecoyStartTs := time.Now() //[Note] decoy.GetIpAddrStr() will get only v4 addr if a decoy has both dialConn, err := reg.TcpDialer(childCtx, "tcp", decoy.GetIpAddrStr()) reg.setTCPToDecoy(durationToU32ptrMs(time.Since(tcpToDecoyStartTs))) if err != nil { if opErr, ok := err.(*net.OpError); ok && opErr.Err.Error() == "connect: network is unreachable" { dialError <- RegError{msg: err.Error(), code: Unreachable} return } dialError <- err return } //[reference] connection stats tracking rtt := rttInt(uint32(time.Since(tcpToDecoyStartTs).Milliseconds())) delay := getRandomDuration(1061*rtt*2, 1953*rtt*3) //[TODO]{priority:@sfrolov} why these values?? TLSDeadline := time.Now().Add(delay) tlsToDecoyStartTs := time.Now() tlsConn, err := reg.createTLSConn(dialConn, decoy.GetIpAddrStr(), decoy.GetHostname(), TLSDeadline) if err != nil { dialConn.Close() msg := fmt.Sprintf("%v - %v createConn: %v", decoy.GetHostname(), decoy.GetIpAddrStr(), err.Error()) dialError <- RegError{msg: msg, code: TLSError} return } reg.setTLSToDecoy(durationToU32ptrMs(time.Since(tlsToDecoyStartTs))) //[reference] Create the HTTP request for the registration httpRequest, err := reg.createRequest(tlsConn, decoy) if err != nil { msg := fmt.Sprintf("%v - %v createReq: %v", decoy.GetHostname(), decoy.GetIpAddrStr(), err.Error()) dialError <- RegError{msg: msg, code: TLSError} return } //[reference] Write reg into conn _, err = tlsConn.Write(httpRequest) if err != nil { // // This will not get printed because it is executed in a goroutine. // Logger().Errorf("%v - %v Could not send Conjure registration request, error: %v", decoy.GetHostname(), decoy.GetIpAddrStr(), err.Error()) tlsConn.Close() msg := fmt.Sprintf("%v - %v Write: %v", decoy.GetHostname(), decoy.GetIpAddrStr(), err.Error()) dialError <- RegError{msg: msg, code: TLSError} return } dialError <- nil readAndClose(dialConn, time.Second*15) callback(reg) } func (reg *ConjureReg) createTLSConn(dialConn net.Conn, address string, hostname string, deadline time.Time) (*tls.UConn, error) { var err error //[reference] TLS to Decoy config := tls.Config{ServerName: hostname} if config.ServerName == "" { // if SNI is unset -- try IP config.ServerName, _, err = net.SplitHostPort(address) if err != nil { return nil, err } Logger().Debugf("%v SNI was nil. Setting it to %v ", reg.sessionIDStr, config.ServerName) } //[TODO]{priority:medium} parroting Chrome 62 ClientHello -- parrot newer. tlsConn := tls.UClient(dialConn, &config, tls.HelloChrome_62) err = tlsConn.BuildHandshakeState() if err != nil { return nil, err } err = tlsConn.MarshalClientHello() if err != nil { return nil, err } tlsConn.SetDeadline(deadline) err = tlsConn.Handshake() if err != nil { return nil, err } return tlsConn, nil } func (reg *ConjureReg) setTCPToDecoy(tcprtt *uint32) { reg.m.Lock() defer reg.m.Unlock() if reg.stats == nil { reg.stats = &pb.SessionStats{} } reg.stats.TcpToDecoy = tcprtt } func (reg *ConjureReg) setTLSToDecoy(tlsrtt *uint32) { reg.m.Lock() defer reg.m.Unlock() if reg.stats == nil { reg.stats = &pb.SessionStats{} } reg.stats.TlsToDecoy = tlsrtt } func (reg *ConjureReg) getPbTransport() pb.TransportType { return pb.TransportType(reg.transport) } func (reg *ConjureReg) generateFlags() *pb.RegistrationFlags { flags := &pb.RegistrationFlags{} mask := default_flags if reg.useProxyHeader { mask |= tdFlagProxyHeader } uploadOnly := mask&tdFlagUploadOnly == tdFlagUploadOnly proxy := mask&tdFlagProxyHeader == tdFlagProxyHeader til := mask&tdFlagUseTIL == tdFlagUseTIL flags.UploadOnly = &uploadOnly flags.ProxyHeader = &proxy flags.Use_TIL = &til return flags } func (reg *ConjureReg) generateClientToStation() *pb.ClientToStation { var covert *string if len(reg.covertAddress) > 0 { //[TODO]{priority:medium} this isn't the correct place to deal with signaling to the station //transition = pb.C2S_Transition_C2S_SESSION_COVERT_INIT covert = &reg.covertAddress } //[reference] Generate ClientToStation protobuf // transition := pb.C2S_Transition_C2S_SESSION_INIT currentGen := Assets().GetGeneration() transport := reg.getPbTransport() initProto := &pb.ClientToStation{ CovertAddress: covert, DecoyListGeneration: &currentGen, V6Support: reg.getV6Support(), V4Support: reg.getV4Support(), Transport: &transport, Flags: reg.generateFlags(), // StateTransition: &transition, //[TODO]{priority:medium} specify width in C2S because different width might // be useful in different regions (constant for now.) } if len(reg.phantomSNI) > 0 { initProto.MaskedDecoyServerName = &reg.phantomSNI } for (proto.Size(initProto)+AES_GCM_TAG_SIZE)%3 != 0 { initProto.Padding = append(initProto.Padding, byte(0)) } return initProto } func (reg *ConjureReg) generateVSP() ([]byte, error) { //[reference] Marshal ClientToStation protobuf return proto.Marshal(reg.generateClientToStation()) } func (reg *ConjureReg) generateFSP(espSize uint16) []byte { buf := make([]byte, 6) binary.BigEndian.PutUint16(buf[0:2], espSize) return buf } func (reg *ConjureReg) getV4Support() *bool { // for now return true and register both support := true if reg.v6Support == v6 { support = false } return &support } func (reg *ConjureReg) getV6Support() *bool { support := true if reg.v6Support == v4 { support = false } return &support } func (reg *ConjureReg) v6SupportStr() string { switch reg.v6Support { case both: return "Both" case v4: return "V4" case v6: return "V6" default: return "unknown" } } func (reg *ConjureReg) digestStats() string { //[TODO]{priority:eventually} add decoy details to digest if reg == nil || reg.stats == nil { return fmt.Sprint("{result:\"no stats tracked\"}") } reg.m.Lock() defer reg.m.Unlock() return fmt.Sprintf("{result:\"success\", tcp_to_decoy:%v, tls_to_decoy:%v, total_time_to_connect:%v}", reg.stats.GetTcpToDecoy(), reg.stats.GetTlsToDecoy(), reg.stats.GetTotalTimeToConnect()) } func (reg *ConjureReg) getRandomDuration(base, min, max int) time.Duration { addon := getRandInt(min, max) / 1000 // why this min and max??? rtt := rttInt(reg.getTcpToDecoy()) return time.Millisecond * time.Duration(base+rtt*addon) } func (reg *ConjureReg) getTcpToDecoy() uint32 { reg.m.Lock() defer reg.m.Unlock() if reg != nil { if reg.stats != nil { return reg.stats.GetTcpToDecoy() } } return 0 } func (cjSession *ConjureSession) setV6Support(support uint) { switch support { case v4: cjSession.V6Support.support = false cjSession.V6Support.include = v4 case v6: cjSession.V6Support.support = true cjSession.V6Support.include = v6 case both: cjSession.V6Support.support = true cjSession.V6Support.include = both default: cjSession.V6Support.support = true cjSession.V6Support.include = v6 } } // When a registration send goroutine finishes it will call this and log // session stats and/or errors. func (cjSession *ConjureSession) registrationCallback(reg *ConjureReg) { //[TODO]{priority:NOW} Logger().Infof("%v %v", cjSession.IDString(), reg.digestStats()) } func (cjSession *ConjureSession) getRandomDuration(base, min, max int) time.Duration { addon := getRandInt(min, max) / 1000 // why this min and max??? rtt := rttInt(cjSession.getTcpToDecoy()) return time.Millisecond * time.Duration(base+rtt*addon) } func (cjSession *ConjureSession) getTcpToDecoy() uint32 { if cjSession != nil { if cjSession.stats != nil { return cjSession.stats.GetTcpToDecoy() } } return 0 } func sleepWithContext(ctx context.Context, duration time.Duration) { timer := time.NewTimer(duration) defer timer.Stop() select { case <-timer.C: case <-ctx.Done(): } } func rttInt(millis uint32) int { defaultValue := 300 if millis == 0 { return defaultValue } return int(millis) } // SelectDecoys - Get an array of `width` decoys to be used for registration func SelectDecoys(sharedSecret []byte, version uint, width uint) ([]*pb.TLSDecoySpec, error) { //[reference] prune to v6 only decoys if useV6 is true var allDecoys []*pb.TLSDecoySpec switch version { case v6: allDecoys = Assets().GetV6Decoys() case v4: allDecoys = Assets().GetV4Decoys() case both: allDecoys = Assets().GetAllDecoys() default: allDecoys = Assets().GetAllDecoys() } if len(allDecoys) == 0 { return nil, fmt.Errorf("no decoys") } decoys := make([]*pb.TLSDecoySpec, width) numDecoys := big.NewInt(int64(len(allDecoys))) hmacInt := new(big.Int) idx := new(big.Int) //[reference] select decoys for i := uint(0); i < width; i++ { macString := fmt.Sprintf("registrationdecoy%d", i) hmac := conjureHMAC(sharedSecret, macString) hmacInt = hmacInt.SetBytes(hmac[:8]) hmacInt.SetBytes(hmac) hmacInt.Abs(hmacInt) idx.Mod(hmacInt, numDecoys) decoys[i] = allDecoys[int(idx.Int64())] } return decoys, nil } // var phantomSubnets = []conjurePhantomSubnet{ // {subnet: "192.122.190.0/24", weight: 90.0}, // {subnet: "2001:48a8:687f:1::/64", weight: 90.0}, // {subnet: "141.219.0.0/16", weight: 10.0}, // {subnet: "35.8.0.0/16", weight: 10.0}, // } // SelectPhantom - select one phantom IP address based on shared secret func SelectPhantom(seed []byte, support uint) (*net.IP, *net.IP, error) { phantomSubnets := Assets().GetPhantomSubnets() switch support { case v4: phantomIPv4, err := ps.SelectPhantom(seed, phantomSubnets, ps.V4Only, true) if err != nil { return nil, nil, err } return phantomIPv4, nil, nil case v6: phantomIPv6, err := ps.SelectPhantom(seed, phantomSubnets, ps.V6Only, true) if err != nil { return nil, nil, err } return nil, phantomIPv6, nil case both: phantomIPv4, err := ps.SelectPhantom(seed, phantomSubnets, ps.V4Only, true) if err != nil { return nil, nil, err } phantomIPv6, err := ps.SelectPhantom(seed, phantomSubnets, ps.V6Only, true) if err != nil { return nil, nil, err } return phantomIPv4, phantomIPv6, nil default: return nil, nil, fmt.Errorf("unknown v4/v6 support") } } func getStationKey() [32]byte { return *Assets().GetConjurePubkey() } type Obfs4Keys struct { PrivateKey *ntor.PrivateKey PublicKey *ntor.PublicKey NodeID *ntor.NodeID } func generateObfs4Keys(rand io.Reader) (Obfs4Keys, error) { keys := Obfs4Keys{ PrivateKey: new(ntor.PrivateKey), PublicKey: new(ntor.PublicKey), NodeID: new(ntor.NodeID), } _, err := rand.Read(keys.PrivateKey[:]) if err != nil { return keys, err } keys.PrivateKey[0] &= 248 keys.PrivateKey[31] &= 127 keys.PrivateKey[31] |= 64 pub, err := curve25519.X25519(keys.PrivateKey[:], curve25519.Basepoint) if err != nil { return keys, err } copy(keys.PublicKey[:], pub) _, err = rand.Read(keys.NodeID[:]) return keys, err } type sharedKeys struct { SharedSecret, Representative []byte FspKey, FspIv, VspKey, VspIv, NewMasterSecret, ConjureSeed []byte Obfs4Keys Obfs4Keys } func generateSharedKeys(pubkey [32]byte) (*sharedKeys, error) { sharedSecret, representative, err := generateEligatorTransformedKey(pubkey[:]) if err != nil { return nil, err } tdHkdf := hkdf.New(sha256.New, sharedSecret, []byte("conjureconjureconjureconjure"), nil) keys := &sharedKeys{ SharedSecret: sharedSecret, Representative: representative, FspKey: make([]byte, 16), FspIv: make([]byte, 12), VspKey: make([]byte, 16), VspIv: make([]byte, 12), NewMasterSecret: make([]byte, 48), ConjureSeed: make([]byte, 16), } if _, err := tdHkdf.Read(keys.FspKey); err != nil { return keys, err } if _, err := tdHkdf.Read(keys.FspIv); err != nil { return keys, err } if _, err := tdHkdf.Read(keys.VspKey); err != nil { return keys, err } if _, err := tdHkdf.Read(keys.VspIv); err != nil { return keys, err } if _, err := tdHkdf.Read(keys.NewMasterSecret); err != nil { return keys, err } if _, err := tdHkdf.Read(keys.ConjureSeed); err != nil { return keys, err } keys.Obfs4Keys, err = generateObfs4Keys(tdHkdf) return keys, err } // func conjureHMAC(key []byte, str string) []byte { hash := hmac.New(sha256.New, key) hash.Write([]byte(str)) return hash.Sum(nil) } // RegError - Registration Error passed during registration to indicate failure mode type RegError struct { code uint msg string } func (err RegError) Error() string { return fmt.Sprintf("Registration Error [%v]: %v", err.CodeStr(), err.msg) } // CodeStr - Get desctriptor associated with error code func (err RegError) CodeStr() string { switch err.code { case Unreachable: return "UNREACHABLE" case DialFailure: return "DIAL_FAILURE" case NotImplemented: return "NOT_IMPLEMENTED" case TLSError: return "TLS_ERROR" default: return "UNKNOWN" } } const ( // Unreachable -Dial Error Unreachable -- likely network unavailable (i.e. ipv6 error) Unreachable = iota // DialFailure - Dial Error Other than unreachable DialFailure // NotImplemented - Related Function Not Implemented NotImplemented // TLS Error (Expired, Wrong-Host, Untrusted-Root, ...) TLSError // Unknown - Error occurred without obvious explanation Unknown )
DialConjure
indexer.controller.ts
import { Client } from '@elastic/elasticsearch'; import { Inject, Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { unique } from '@vendure/common/lib/unique'; import { Asset, asyncObservable, AsyncQueue, Channel, Collection, ConfigService, FacetValue, ID, LanguageCode, Logger, Product, ProductVariant, ProductVariantService, RequestContext, TransactionalConnection, Translatable, Translation, } from '@vendure/core'; import { Observable } from 'rxjs'; import { ELASTIC_SEARCH_OPTIONS, loggerCtx, PRODUCT_INDEX_NAME, VARIANT_INDEX_NAME } from './constants'; import { createIndices, deleteIndices } from './indexing-utils'; import { ElasticsearchOptions } from './options'; import { BulkOperation, BulkOperationDoc, BulkResponseBody, ProductChannelMessageData, ProductIndexItem, ReindexMessageData, UpdateAssetMessageData, UpdateProductMessageData, UpdateVariantMessageData, UpdateVariantsByIdMessageData, VariantChannelMessageData, VariantIndexItem, } from './types'; export const productRelations = [ 'variants', 'featuredAsset', 'facetValues', 'facetValues.facet', 'channels', 'channels.defaultTaxZone', ]; export const variantRelations = [ 'featuredAsset', 'facetValues', 'facetValues.facet', 'collections', 'taxCategory', 'channels', 'channels.defaultTaxZone', ]; export interface ReindexMessageResponse { total: number; completed: number; duration: number; } type BulkProductOperation = { index: typeof PRODUCT_INDEX_NAME; operation: BulkOperation | BulkOperationDoc<ProductIndexItem>; }; type BulkVariantOperation = { index: typeof VARIANT_INDEX_NAME; operation: BulkOperation | BulkOperationDoc<VariantIndexItem>; }; @Injectable() export class
implements OnModuleInit, OnModuleDestroy { private client: Client; private asyncQueue = new AsyncQueue('elasticsearch-indexer', 5); constructor( private connection: TransactionalConnection, @Inject(ELASTIC_SEARCH_OPTIONS) private options: Required<ElasticsearchOptions>, private productVariantService: ProductVariantService, private configService: ConfigService, ) {} onModuleInit(): any { const { host, port } = this.options; this.client = new Client({ node: `${host}:${port}`, }); } onModuleDestroy(): any { return this.client.close(); } /** * Updates the search index only for the affected product. */ async updateProduct({ ctx: rawContext, productId }: UpdateProductMessageData): Promise<boolean> { await this.updateProductsInternal([productId]); return true; } /** * Updates the search index only for the affected product. */ async deleteProduct({ ctx: rawContext, productId }: UpdateProductMessageData): Promise<boolean> { const operations = await this.deleteProductOperations(productId); await this.executeBulkOperations(operations); return true; } /** * Updates the search index only for the affected product. */ async assignProductToChannel({ ctx: rawContext, productId, channelId, }: ProductChannelMessageData): Promise<boolean> { await this.updateProductsInternal([productId]); return true; } /** * Updates the search index only for the affected product. */ async removeProductFromChannel({ ctx: rawContext, productId, channelId, }: ProductChannelMessageData): Promise<boolean> { await this.updateProductsInternal([productId]); return true; } async assignVariantToChannel({ ctx: rawContext, productVariantId, channelId, }: VariantChannelMessageData): Promise<boolean> { const productIds = await this.getProductIdsByVariantIds([productVariantId]); await this.updateProductsInternal(productIds); return true; } async removeVariantFromChannel({ ctx: rawContext, productVariantId, channelId, }: VariantChannelMessageData): Promise<boolean> { const productIds = await this.getProductIdsByVariantIds([productVariantId]); await this.updateProductsInternal(productIds); return true; } /** * Updates the search index only for the affected entities. */ async updateVariants({ ctx: rawContext, variantIds }: UpdateVariantMessageData): Promise<boolean> { return this.asyncQueue.push(async () => { const productIds = await this.getProductIdsByVariantIds(variantIds); await this.updateProductsInternal(productIds); return true; }); } async deleteVariants({ ctx: rawContext, variantIds }: UpdateVariantMessageData): Promise<boolean> { const productIds = await this.getProductIdsByVariantIds(variantIds); for (const productId of productIds) { await this.updateProductsInternal([productId]); } return true; } updateVariantsById({ ctx: rawContext, ids, }: UpdateVariantsByIdMessageData): Observable<ReindexMessageResponse> { return asyncObservable(async observer => { return this.asyncQueue.push(async () => { const timeStart = Date.now(); const productIds = await this.getProductIdsByVariantIds(ids); if (productIds.length) { let finishedProductsCount = 0; for (const productId of productIds) { await this.updateProductsInternal([productId]); finishedProductsCount++; observer.next({ total: productIds.length, completed: Math.min(finishedProductsCount, productIds.length), duration: +new Date() - timeStart, }); } } Logger.verbose(`Completed updating variants`, loggerCtx); return { total: productIds.length, completed: productIds.length, duration: +new Date() - timeStart, }; }); }); } reindex({ ctx: rawContext, dropIndices }: ReindexMessageData): Observable<ReindexMessageResponse> { return asyncObservable(async observer => { return this.asyncQueue.push(async () => { const timeStart = Date.now(); const operations: Array<BulkProductOperation | BulkVariantOperation> = []; if (dropIndices) { await deleteIndices(this.client, this.options.indexPrefix); await createIndices( this.client, this.options.indexPrefix, this.configService.entityIdStrategy.primaryKeyType, ); } const deletedProductIds = await this.connection .getRepository(Product) .createQueryBuilder('product') .select('product.id') .where('product.deletedAt IS NOT NULL') .getMany(); for (const { id: deletedProductId } of deletedProductIds) { operations.push(...(await this.deleteProductOperations(deletedProductId))); } const productIds = await this.connection .getRepository(Product) .createQueryBuilder('product') .select('product.id') .where('product.deletedAt IS NULL') .getMany(); Logger.verbose(`Reindexing ${productIds.length} Products`, loggerCtx); let finishedProductsCount = 0; for (const { id: productId } of productIds) { operations.push(...(await this.updateProductsOperations([productId]))); finishedProductsCount++; observer.next({ total: productIds.length, completed: Math.min(finishedProductsCount, productIds.length), duration: +new Date() - timeStart, }); } Logger.verbose(`Will execute ${operations.length} bulk update operations`, loggerCtx); await this.executeBulkOperations(operations); Logger.verbose(`Completed reindexing!`, loggerCtx); return { total: productIds.length, completed: productIds.length, duration: +new Date() - timeStart, }; }); }); } async updateAsset(data: UpdateAssetMessageData): Promise<boolean> { const result1 = await this.updateAssetFocalPointForIndex(PRODUCT_INDEX_NAME, data.asset); const result2 = await this.updateAssetFocalPointForIndex(VARIANT_INDEX_NAME, data.asset); await this.client.indices.refresh({ index: [ this.options.indexPrefix + PRODUCT_INDEX_NAME, this.options.indexPrefix + VARIANT_INDEX_NAME, ], }); return result1 && result2; } async deleteAsset(data: UpdateAssetMessageData): Promise<boolean> { const result1 = await this.deleteAssetForIndex(PRODUCT_INDEX_NAME, data.asset); const result2 = await this.deleteAssetForIndex(VARIANT_INDEX_NAME, data.asset); await this.client.indices.refresh({ index: [ this.options.indexPrefix + PRODUCT_INDEX_NAME, this.options.indexPrefix + VARIANT_INDEX_NAME, ], }); return result1 && result2; } private async updateAssetFocalPointForIndex(indexName: string, asset: Asset): Promise<boolean> { const focalPoint = asset.focalPoint || null; const params = { focalPoint }; return this.updateAssetForIndex( indexName, asset, { source: 'ctx._source.productPreviewFocalPoint = params.focalPoint', params, }, { source: 'ctx._source.productVariantPreviewFocalPoint = params.focalPoint', params, }, ); } private async deleteAssetForIndex(indexName: string, asset: Asset): Promise<boolean> { return this.updateAssetForIndex( indexName, asset, { source: 'ctx._source.productAssetId = null' }, { source: 'ctx._source.productVariantAssetId = null' }, ); } private async updateAssetForIndex( indexName: string, asset: Asset, updateProductScript: { source: string; params?: any }, updateVariantScript: { source: string; params?: any }, ): Promise<boolean> { const result1 = await this.client.update_by_query({ index: this.options.indexPrefix + indexName, body: { script: updateProductScript, query: { term: { productAssetId: asset.id, }, }, }, }); for (const failure of result1.body.failures) { Logger.error(`${failure.cause.type}: ${failure.cause.reason}`, loggerCtx); } const result2 = await this.client.update_by_query({ index: this.options.indexPrefix + indexName, body: { script: updateVariantScript, query: { term: { productVariantAssetId: asset.id, }, }, }, }); for (const failure of result1.body.failures) { Logger.error(`${failure.cause.type}: ${failure.cause.reason}`, loggerCtx); } return result1.body.failures.length === 0 && result2.body.failures === 0; } private async updateProductsInternal(productIds: ID[]) { const operations = await this.updateProductsOperations(productIds); await this.executeBulkOperations(operations); } private async updateProductsOperations( productIds: ID[], ): Promise<Array<BulkProductOperation | BulkVariantOperation>> { Logger.verbose(`Updating ${productIds.length} Products`, loggerCtx); const operations: Array<BulkProductOperation | BulkVariantOperation> = []; for (const productId of productIds) { operations.push(...(await this.deleteProductOperations(productId))); const product = await this.connection.getRepository(Product).findOne(productId, { relations: productRelations, where: { deletedAt: null, }, }); if (product) { const updatedProductVariants = await this.connection.getRepository(ProductVariant).findByIds( product.variants.map(v => v.id), { relations: variantRelations, where: { deletedAt: null, }, order: { id: 'ASC', }, }, ); updatedProductVariants.forEach(variant => (variant.product = product)); if (product.enabled === false) { updatedProductVariants.forEach(v => (v.enabled = false)); } Logger.verbose(`Updating Product (${productId})`, loggerCtx); if (updatedProductVariants.length) { operations.push(...(await this.updateVariantsOperations(updatedProductVariants))); } const languageVariants = product.translations.map(t => t.languageCode); for (const channel of product.channels) { const channelCtx = new RequestContext({ channel, apiType: 'admin', authorizedAsOwnerOnly: false, isAuthorized: true, session: {} as any, }); const variantsInChannel = updatedProductVariants.filter(v => v.channels.map(c => c.id).includes(channelCtx.channelId), ); for (const variant of variantsInChannel) { await this.productVariantService.applyChannelPriceAndTax(variant, channelCtx); } for (const languageCode of languageVariants) { operations.push( { index: PRODUCT_INDEX_NAME, operation: { update: { _id: this.getId(product.id, channelCtx.channelId, languageCode), }, }, }, { index: PRODUCT_INDEX_NAME, operation: { doc: variantsInChannel.length ? this.createProductIndexItem( variantsInChannel, channelCtx.channelId, languageCode, ) : this.createSyntheticProductIndexItem( channelCtx, product, languageCode, ), doc_as_upsert: true, }, }, ); } } } } return operations; } private async updateVariantsOperations( productVariants: ProductVariant[], ): Promise<BulkVariantOperation[]> { if (productVariants.length === 0) { return []; } const operations: BulkVariantOperation[] = []; for (const variant of productVariants) { const languageVariants = variant.translations.map(t => t.languageCode); for (const channel of variant.channels) { const channelCtx = new RequestContext({ channel, apiType: 'admin', authorizedAsOwnerOnly: false, isAuthorized: true, session: {} as any, }); await this.productVariantService.applyChannelPriceAndTax(variant, channelCtx); for (const languageCode of languageVariants) { operations.push( { index: VARIANT_INDEX_NAME, operation: { update: { _id: this.getId(variant.id, channelCtx.channelId, languageCode) }, }, }, { index: VARIANT_INDEX_NAME, operation: { doc: this.createVariantIndexItem(variant, channelCtx.channelId, languageCode), doc_as_upsert: true, }, }, ); } } } Logger.verbose(`Updating ${productVariants.length} ProductVariants`, loggerCtx); return operations; } private async deleteProductOperations( productId: ID, ): Promise<Array<BulkProductOperation | BulkVariantOperation>> { const channels = await this.connection .getRepository(Channel) .createQueryBuilder('channel') .select('channel.id') .getMany(); const product = await this.connection.getRepository(Product).findOne(productId, { relations: ['variants'], }); if (!product) { return []; } Logger.verbose(`Deleting 1 Product (id: ${productId})`, loggerCtx); const operations: Array<BulkProductOperation | BulkVariantOperation> = []; for (const { id: channelId } of channels) { const languageVariants = product.translations.map(t => t.languageCode); for (const languageCode of languageVariants) { operations.push({ index: PRODUCT_INDEX_NAME, operation: { delete: { _id: this.getId(product.id, channelId, languageCode) } }, }); } } operations.push( ...(await this.deleteVariantsInternalOperations( product.variants, channels.map(c => c.id), )), ); return operations; } private async deleteVariantsInternalOperations( variants: ProductVariant[], channelIds: ID[], ): Promise<BulkVariantOperation[]> { Logger.verbose(`Deleting ${variants.length} ProductVariants`, loggerCtx); const operations: BulkVariantOperation[] = []; for (const variant of variants) { for (const channelId of channelIds) { const languageVariants = variant.translations.map(t => t.languageCode); for (const languageCode of languageVariants) { operations.push({ index: VARIANT_INDEX_NAME, operation: { delete: { _id: this.getId(variant.id, channelId, languageCode) }, }, }); } } } return operations; } private async getProductIdsByVariantIds(variantIds: ID[]): Promise<ID[]> { const variants = await this.connection.getRepository(ProductVariant).findByIds(variantIds, { relations: ['product'], loadEagerRelations: false, }); return unique(variants.map(v => v.product.id)); } private async executeBulkOperations(operations: Array<BulkProductOperation | BulkVariantOperation>) { const productOperations: Array<BulkOperation | BulkOperationDoc<ProductIndexItem>> = []; const variantOperations: Array<BulkOperation | BulkOperationDoc<VariantIndexItem>> = []; for (const operation of operations) { if (operation.index === PRODUCT_INDEX_NAME) { productOperations.push(operation.operation); } else { variantOperations.push(operation.operation); } } return Promise.all([ this.runBulkOperationsOnIndex(PRODUCT_INDEX_NAME, productOperations), this.runBulkOperationsOnIndex(VARIANT_INDEX_NAME, variantOperations), ]); } private async runBulkOperationsOnIndex( indexName: string, operations: Array<BulkOperation | BulkOperationDoc<VariantIndexItem | ProductIndexItem>>, ) { if (operations.length === 0) { return; } try { const fullIndexName = this.options.indexPrefix + indexName; const { body }: { body: BulkResponseBody } = await this.client.bulk({ refresh: true, index: fullIndexName, body: operations, }); if (body.errors) { Logger.error( `Some errors occurred running bulk operations on ${fullIndexName}! Set logger to "debug" to print all errors.`, loggerCtx, ); body.items.forEach(item => { if (item.index) { Logger.debug(JSON.stringify(item.index.error, null, 2), loggerCtx); } if (item.update) { Logger.debug(JSON.stringify(item.update.error, null, 2), loggerCtx); } if (item.delete) { Logger.debug(JSON.stringify(item.delete.error, null, 2), loggerCtx); } }); } else { Logger.debug( `Executed ${body.items.length} bulk operations on index [${fullIndexName}]`, loggerCtx, ); } return body; } catch (e) { Logger.error(`Error when attempting to run bulk operations [${e.toString()}]`, loggerCtx); Logger.error('Error details: ' + JSON.stringify(e.body?.error, null, 2), loggerCtx); } } private createVariantIndexItem( v: ProductVariant, channelId: ID, languageCode: LanguageCode, ): VariantIndexItem { const productAsset = v.product.featuredAsset; const variantAsset = v.featuredAsset; const productTranslation = this.getTranslation(v.product, languageCode); const variantTranslation = this.getTranslation(v, languageCode); const collectionTranslations = v.collections.map(c => this.getTranslation(c, languageCode)); const item: VariantIndexItem = { channelId, languageCode, productVariantId: v.id, sku: v.sku, slug: productTranslation.slug, productId: v.product.id, productName: productTranslation.name, productAssetId: productAsset ? productAsset.id : undefined, productPreview: productAsset ? productAsset.preview : '', productPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined, productVariantName: variantTranslation.name, productVariantAssetId: variantAsset ? variantAsset.id : undefined, productVariantPreview: variantAsset ? variantAsset.preview : '', productVariantPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined, price: v.price, priceWithTax: v.priceWithTax, currencyCode: v.currencyCode, description: productTranslation.description, facetIds: this.getFacetIds([v]), channelIds: v.channels.map(c => c.id), facetValueIds: this.getFacetValueIds([v]), collectionIds: v.collections.map(c => c.id.toString()), collectionSlugs: collectionTranslations.map(c => c.slug), enabled: v.enabled && v.product.enabled, }; const customMappings = Object.entries(this.options.customProductVariantMappings); for (const [name, def] of customMappings) { item[name] = def.valueFn(v, languageCode); } return item; } private createProductIndexItem( variants: ProductVariant[], channelId: ID, languageCode: LanguageCode, ): ProductIndexItem { const first = variants[0]; const prices = variants.map(v => v.price); const pricesWithTax = variants.map(v => v.priceWithTax); const productAsset = first.product.featuredAsset; const variantAsset = variants.filter(v => v.featuredAsset).length ? variants.filter(v => v.featuredAsset)[0].featuredAsset : null; const productTranslation = this.getTranslation(first.product, languageCode); const variantTranslation = this.getTranslation(first, languageCode); const collectionTranslations = variants.reduce( (translations, variant) => [ ...translations, ...variant.collections.map(c => this.getTranslation(c, languageCode)), ], [] as Array<Translation<Collection>>, ); const item: ProductIndexItem = { channelId, languageCode, sku: first.sku, slug: productTranslation.slug, productId: first.product.id, productName: productTranslation.name, productAssetId: productAsset ? productAsset.id : undefined, productPreview: productAsset ? productAsset.preview : '', productPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined, productVariantId: first.id, productVariantName: variantTranslation.name, productVariantAssetId: variantAsset ? variantAsset.id : undefined, productVariantPreview: variantAsset ? variantAsset.preview : '', productVariantPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined, priceMin: Math.min(...prices), priceMax: Math.max(...prices), priceWithTaxMin: Math.min(...pricesWithTax), priceWithTaxMax: Math.max(...pricesWithTax), currencyCode: first.currencyCode, description: productTranslation.description, facetIds: this.getFacetIds(variants), facetValueIds: this.getFacetValueIds(variants), collectionIds: variants.reduce((ids, v) => [...ids, ...v.collections.map(c => c.id)], [] as ID[]), collectionSlugs: collectionTranslations.map(c => c.slug), channelIds: first.product.channels.map(c => c.id), enabled: variants.some(v => v.enabled) && first.product.enabled, }; const customMappings = Object.entries(this.options.customProductMappings); for (const [name, def] of customMappings) { item[name] = def.valueFn(variants[0].product, variants, languageCode); } return item; } /** * If a Product has no variants, we create a synthetic variant for the purposes * of making that product visible via the search query. */ private createSyntheticProductIndexItem( ctx: RequestContext, product: Product, languageCode: LanguageCode, ): ProductIndexItem { const productTranslation = this.getTranslation(product, ctx.languageCode); return { channelId: ctx.channelId, languageCode, sku: '', slug: productTranslation.slug, productId: product.id, productName: productTranslation.name, productAssetId: product.featuredAsset?.id ?? undefined, productPreview: product.featuredAsset?.preview ?? '', productPreviewFocalPoint: product.featuredAsset?.focalPoint ?? undefined, productVariantId: 0, productVariantName: productTranslation.name, productVariantAssetId: undefined, productVariantPreview: '', productVariantPreviewFocalPoint: undefined, priceMin: 0, priceMax: 0, priceWithTaxMin: 0, priceWithTaxMax: 0, currencyCode: ctx.channel.currencyCode, description: productTranslation.description, facetIds: product.facetValues?.map(fv => fv.facet.id.toString()) ?? [], facetValueIds: product.facetValues?.map(fv => fv.id.toString()) ?? [], collectionIds: [], collectionSlugs: [], channelIds: [ctx.channelId], enabled: false, }; } private getTranslation<T extends Translatable>( translatable: T, languageCode: LanguageCode, ): Translation<T> { return ((translatable.translations.find(t => t.languageCode === languageCode) || translatable.translations.find(t => t.languageCode === this.configService.defaultLanguageCode) || translatable.translations[0]) as unknown) as Translation<T>; } private getFacetIds(variants: ProductVariant[]): string[] { const facetIds = (fv: FacetValue) => fv.facet.id.toString(); const variantFacetIds = variants.reduce( (ids, v) => [...ids, ...v.facetValues.map(facetIds)], [] as string[], ); const productFacetIds = variants[0].product.facetValues.map(facetIds); return unique([...variantFacetIds, ...productFacetIds]); } private getFacetValueIds(variants: ProductVariant[]): string[] { const facetValueIds = (fv: FacetValue) => fv.id.toString(); const variantFacetValueIds = variants.reduce( (ids, v) => [...ids, ...v.facetValues.map(facetValueIds)], [] as string[], ); const productFacetValueIds = variants[0].product.facetValues.map(facetValueIds); return unique([...variantFacetValueIds, ...productFacetValueIds]); } private getId(entityId: ID, channelId: ID, languageCode: LanguageCode): string { return `${channelId.toString()}_${entityId.toString()}_${languageCode}`; } }
ElasticsearchIndexerController
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class W3m(AutotoolsPackage): """ w3m is a text-based web browser as well as a pager like `more' or `less'. With w3m you can browse web pages through a terminal emulator window (xterm, rxvt or something like that). Moreover, w3m can be used as a text formatting tool which typesets HTML into plain text. """ homepage = "http://w3m.sourceforge.net/index.en.html" url = "https://downloads.sourceforge.net/project/w3m/w3m/w3m-0.5.3/w3m-0.5.3.tar.gz" maintainers = ['ronin_gw'] version('0.5.3', sha256='e994d263f2fd2c22febfbe45103526e00145a7674a0fda79c822b97c2770a9e3') # mandatory dependency depends_on('bdw-gc') # termlib variant('termlib', default='ncurses', description='select termlib', values=('ncurses', 'termcap', 'none'), multi=False) depends_on('termcap', when='termlib=termcap') depends_on('ncurses+termlib', when='termlib=ncurses') # https support variant('https', default=True, description='support https protocol') depends_on('openssl@:1.0.2u', when='+https') # X11 support variant('image', default=True, description='enable image') depends_on('libx11', when='+image') # inline image support variant('imagelib', default='imlib2', description='select imagelib', values=('gdk-pixbuf', 'imlib2'), multi=False) depends_on('gdk-pixbuf@2:+x11', when='imagelib=gdk-pixbuf +image') depends_on('[email protected]:', when='imagelib=imlib2 +image') # fix for modern libraries patch('fix_redef.patch') patch('fix_gc.patch') def _add_arg_for_variant(self, args, variant, choices): for avail_lib in choices: if self.spec.variants[variant].value == avail_lib: args.append('--with-{0}={1}'.format(variant, avail_lib)) return def
(self): args = [] self._add_arg_for_variant(args, 'termlib', ('termcap', 'ncurses')) if '+image' in self.spec: args.append('--enable-image') self._add_arg_for_variant(args, 'imagelib', ('gdk-pixbuf', 'imlib2')) return args def setup_build_environment(self, env): if self.spec.variants['termlib'].value == 'ncurses': env.append_flags('LDFLAGS', '-ltinfo') env.append_flags('LDFLAGS', '-lncurses') if '+image' in self.spec: env.append_flags('LDFLAGS', '-lX11') # parallel build causes build failure def build(self, spec, prefix): make(parallel=False)
configure_args
channels.ts
export const CONFIG_CHANNEL = { CONFIG_READ: 'CONFIG_READ',
PLUGINS_UNINSTALL: 'PLUGINS_UNINSTALL', PLUGIN_UPGRADE: 'PLUGIN_UPGRADE', } as const
CONFIG_WINDOW_OPEN: 'CONFIG_WINDOW_OPEN', PLUGINS_INSTALL: 'PLUGINS_INSTALL', PLUGINS_LIST: 'PLUGINS_LIST', PLUGINS_REFRESH: 'PLUGINS_REFRESH',
mount.go
package service import ( "context" "fmt" "os" "path/filepath" "strings" "time" csi "github.com/container-storage-interface/spec/lib/go/csi" "github.com/dell/gofsutil" log "github.com/sirupsen/logrus" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // Variables set only for unit testing. var unitTestEmulateBlockDevice bool // Variables populdated from the environment var mountAllowRWOMultiPodAccess bool // Device is a struct for holding details about a block device type Device struct { FullPath string Name string RealDev string } // GetDevice returns a Device struct with info about the given device, or // an error if it doesn't exist or is not a block device func
(path string) (*Device, error) { fi, err := os.Lstat(path) if err != nil { return nil, err } // eval any symlinks and make sure it points to a device d, err := filepath.EvalSymlinks(path) if err != nil { return nil, err } // TODO does EvalSymlinks throw error if link is to non- // existent file? assuming so by masking error below ds, _ := os.Stat(d) dm := ds.Mode() if unitTestEmulateBlockDevice { // For unit testing only, emulate a block device on windows dm = dm | os.ModeDevice } if dm&os.ModeDevice == 0 { return nil, fmt.Errorf( "%s is not a block device", path) } return &Device{ Name: fi.Name(), FullPath: replaceBackslashWithSlash(path), RealDev: replaceBackslashWithSlash(d), }, nil } // publishVolume uses the parameters in req to bindmount the underlying block // device to the requested target path. A private mount is performed first // within the given privDir directory. // // publishVolume handles both Mount and Block access types func publishVolume( req *csi.NodePublishVolumeRequest, privDir, device string, reqID string) error { id := req.GetVolumeId() target := req.GetTargetPath() if target == "" { return status.Error(codes.InvalidArgument, "target path required") } ro := req.GetReadonly() volCap := req.GetVolumeCapability() if volCap == nil { return status.Error(codes.InvalidArgument, "volume capability required") } // make sure device is valid sysDevice, err := GetDevice(device) if err != nil { return status.Errorf(codes.Internal, "error getting block device for volume: %s, err: %s", id, err.Error()) } isBlock, mntVol, accMode, multiAccessFlag, err := validateVolumeCapability(volCap, ro) if err != nil { return err } // Make sure target is created. The spec says the driver is responsible // for creating the target, but Kubernetes generallly creates the target. privTgt := getPrivateMountPoint(privDir, id) err = createTarget(target, isBlock) if err != nil { // Unmount and remove the private directory for the retry so clean start next time. // K8S probably removed part of the path. cleanupPrivateTarget(reqID, privTgt) return status.Error(codes.FailedPrecondition, fmt.Sprintf("Could not create %s: %s", target, err.Error())) } // make sure privDir exists and is a directory if _, err := mkdir(privDir); err != nil { return err } // Handle block as a short cut if isBlock { // BLOCK only mntFlags := mntVol.GetMountFlags() err = mountBlock(sysDevice, target, mntFlags, singleAccessMode(accMode)) return err } // check that target is right type for vol type // Path to mount device to f := log.Fields{ "id": id, "volumePath": sysDevice.FullPath, "device": sysDevice.RealDev, "CSIRequestID": reqID, "target": target, "privateMount": privTgt, } log.WithFields(f).Debugf("fields") ctx := context.WithValue(context.Background(), gofsutil.ContextKey("RequestID"), reqID) // Check if device is already mounted devMnts, err := getDevMounts(sysDevice) if err != nil { return status.Errorf(codes.Internal, "could not reliably determine existing mount status: %s", err.Error()) } if len(devMnts) == 0 { // Device isn't mounted anywhere, do the private mount log.WithFields(f).Printf("attempting mount to private area") // Make sure private mount point exists created, err := mkdir(privTgt) if err != nil { return status.Errorf(codes.Internal, "Unable to create private mount point: %s", err.Error()) } alreadyMounted := false if !created { log.WithFields(f).Printf("private mount target already exists") // The place where our device is supposed to be mounted // already exists, but we also know that our device is not mounted anywhere // Either something didn't clean up correctly, or something else is mounted // If the private mount is not in use, it's okay to re-use it. But make sure // it's not in use first mnts, err := gofsutil.GetMounts(ctx) if err != nil { return status.Errorf(codes.Internal, "could not reliably determine existing mount status: %s", err.Error()) } if len(mnts) == 0 { return status.Errorf(codes.Unavailable, "volume %s not published to node", id) } for _, m := range mnts { if m.Path == privTgt { log.Debug(fmt.Sprintf("MOUNT: %#v", m)) resolvedMountDevice := evalSymlinks(m.Device) if resolvedMountDevice != sysDevice.RealDev { log.WithFields(f).WithField("mountedDevice", m.Device).Error( "mount point already in use by device") return status.Error(codes.Internal, "Mount point already in use by device") } alreadyMounted = true } } } if !alreadyMounted { fs := mntVol.GetFsType() mntFlags := mntVol.GetMountFlags() if fs == "xfs" { mntFlags = append(mntFlags, "nouuid") } if err := handlePrivFSMount( ctx, accMode, sysDevice, mntFlags, fs, privTgt); err != nil { // K8S may have removed the desired mount point. Clean up the private target. cleanupPrivateTarget(reqID, privTgt) return err } } } else { // Device is already mounted. Need to ensure that it is already // mounted to the expected private mount, with correct rw/ro perms mounted := false for _, m := range devMnts { if m.Path == target { log.Printf("mount %#v already mounted to requested target %s", m, target) } else if m.Path == privTgt { log.WithFields(f).Printf("mount Path %s Source %s Device %s Opts %v", m.Path, m.Source, m.Device, m.Opts) mounted = true rwo := multiAccessFlag if ro { rwo = "ro" } if rwo == "" || contains(m.Opts, rwo) { log.WithFields(f).Printf("private mount already in place") } else { log.WithFields(f).Printf("mount %#v rwo %s", m, rwo) return status.Error(codes.InvalidArgument, "Access mode conflicts with existing mounts") } } else if singleAccessMode(accMode) { return status.Error(codes.FailedPrecondition, fmt.Sprintf("Access mode conflicts with existing mounts for privTgt %s", privTgt)) } } if !mounted { return status.Error(codes.Internal, fmt.Sprintf("Device already in use and mounted elsewhere for privTgt %s", privTgt)) } } // Private mount in place, now bind mount to target path targetMnts, err := getPathMounts(target) if err != nil { return status.Errorf(codes.Internal, "could not reliably determine existing mount status: %s", err.Error()) } // If mounts already existed for this device, check if mount to // target path was already there if len(targetMnts) > 0 { for _, m := range targetMnts { if m.Path == target { // volume already published to target // if mount options look good, do nothing rwo := multiAccessFlag if ro { rwo = "ro" } if rwo != "" && !contains(m.Opts, rwo) { log.WithFields(f).Printf("mount %#v rwo %s\n", m, rwo) return status.Error(codes.Internal, "volume previously published with different options") } // Existing mount satisfies request log.WithFields(f).Debug("volume already published to target") return nil } } } // Recheck that target is created. k8s has this awful habit of deleting the target if it times out the request. // This will narrow the window. err = createTarget(target, isBlock) if err != nil { // Unmount and remove the private directory for the retry so clean start next time. // K8S probably removed part of the path. cleanupPrivateTarget(reqID, privTgt) return status.Error(codes.FailedPrecondition, fmt.Sprintf("Could not create %s: %s", target, err.Error())) } var mntFlags []string mntFlags = mntVol.GetMountFlags() if mntVol.FsType == "xfs" { mntFlags = append(mntFlags, "nouuid") } if ro || accMode.GetMode() == csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY { mntFlags = append(mntFlags, "ro") } if err := gofsutil.BindMount(ctx, privTgt, target, mntFlags...); err != nil { // Unmount and remove the private directory for the retry so clean start next time. // K8S probably removed part of the path. cleanupPrivateTarget(reqID, privTgt) return status.Errorf(codes.Internal, "error publish volume to target path: %s", err.Error()) } return nil } func handlePrivFSMount( ctx context.Context, accMode *csi.VolumeCapability_AccessMode, sysDevice *Device, mntFlags []string, fs, privTgt string) error { // Invoke the formats with a No Discard option to reduce formatting time formatCtx := context.WithValue(ctx, gofsutil.ContextKey(gofsutil.NoDiscard), gofsutil.NoDiscard) // If read-only access mode, we don't allow formatting if accMode.GetMode() == csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY || accMode.GetMode() == csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY { mntFlags = append(mntFlags, "ro") if err := gofsutil.Mount(ctx, sysDevice.FullPath, privTgt, fs, mntFlags...); err != nil { return status.Errorf(codes.Internal, "error performing private mount: %s", err.Error()) } return nil } else if accMode.GetMode() == csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER { if err := gofsutil.FormatAndMount(formatCtx, sysDevice.FullPath, privTgt, fs, mntFlags...); err != nil { return status.Errorf(codes.Internal, "error performing private mount: %s", err.Error()) } return nil } return status.Error(codes.Internal, "Invalid access mode") } func getPrivateMountPoint(privDir string, name string) string { return filepath.Join(privDir, name) } func contains(list []string, item string) bool { for _, x := range list { if x == item { return true } } return false } // mkfile creates a file specified by the path if needed. // return pair is a bool flag of whether file was created, and an error func mkfile(path string) (bool, error) { st, err := os.Stat(path) if os.IsNotExist(err) { /* #nosec G302 G304 */ file, err := os.OpenFile(path, os.O_CREATE, 0755) if err != nil { log.WithField("dir", path).WithError( err).Error("Unable to create dir") return false, err } err = file.Close() if err != nil { // Log the error but keep going log.WithField("file", path).WithError( err).Error("Unable to close file") } log.WithField("path", path).Debug("created file") return true, nil } if st.IsDir() { return false, fmt.Errorf("existing path is a directory") } return false, nil } // mkdir creates the directory specified by path if needed. // return pair is a bool flag of whether dir was created, and an error func mkdir(path string) (bool, error) { st, err := os.Stat(path) if os.IsNotExist(err) { /* #nosec G301 */ if err := os.Mkdir(path, 0755); err != nil { log.WithField("dir", path).WithError( err).Error("Unable to create dir") return false, err } log.WithField("path", path).Debug("created directory") return true, nil } if !st.IsDir() { return false, fmt.Errorf("existing path is not a directory") } return false, nil } // unpublishVolume removes the bind mount to the target path, and also removes // the mount to the private mount directory if the volume is no longer in use. // It determines this by checking to see if the volume is mounted anywhere else // other than the private mount. func unpublishVolume( req *csi.NodeUnpublishVolumeRequest, privDir, device string, reqID string) error { ctx := context.Background() id := req.GetVolumeId() target := req.GetTargetPath() if target == "" { return status.Error(codes.InvalidArgument, "target path required") } // make sure device is valid sysDevice, err := GetDevice(device) if err != nil { return status.Errorf(codes.Internal, "error getting block device for volume: %s, err: %s", id, err.Error()) } // Path to mount device to privTgt := getPrivateMountPoint(privDir, id) f := log.Fields{ "device": sysDevice.RealDev, "privTgt": privTgt, "CSIRequestID": reqID, "target": target, } mnts, err := gofsutil.GetMounts(ctx) if err != nil { return status.Errorf(codes.Internal, "could not reliably determine existing mount status: %s", err.Error()) } tgtMnt := false privMnt := false for _, m := range mnts { if m.Source == sysDevice.RealDev || m.Device == sysDevice.RealDev || m.Device == sysDevice.FullPath { if m.Path == privTgt { privMnt = true } else if m.Path == target { tgtMnt = true } if !privMnt { log.Printf("found some other device matching private mount %s , %#v do manual cleanup if needed \n", privTgt, m) } } } log.Printf("Cleanup flags tgtMnt=%t privMnt=%t\n", tgtMnt, privMnt) if tgtMnt { log.WithFields(f).Debug(fmt.Sprintf("Unmounting %s", target)) if err := gofsutil.Unmount(ctx, target); err != nil { return status.Errorf(codes.Internal, "Error unmounting target: %s", err.Error()) } if err := removeWithRetry(target); err != nil { return status.Errorf(codes.Internal, "Error remove target folder: %s", err.Error()) } } if privMnt { log.WithFields(f).Debug(fmt.Sprintf("Unmounting %s", privTgt)) if err := unmountPrivMount(ctx, sysDevice, privTgt); err != nil { return status.Errorf(codes.Internal, "Error unmounting private mount: %s", err.Error()) } } return nil } func unmountPrivMount( ctx context.Context, dev *Device, target string) error { mnts, err := getDevMounts(dev) if err != nil { return err } // remove private mount if we can if len(mnts) == 1 && mnts[0].Path == target { if err := gofsutil.Unmount(ctx, target); err != nil { return err } log.WithField("directory", target).Debug( "removing directory") if err := os.Remove(target); err != nil { log.Errorf("Unable to remove directory: %v", err) } } return nil } func getDevMounts( sysDevice *Device) ([]gofsutil.Info, error) { ctx := context.Background() devMnts := make([]gofsutil.Info, 0) mnts, err := gofsutil.GetMounts(ctx) if err != nil { return devMnts, err } for _, m := range mnts { if m.Device == sysDevice.RealDev || (m.Device == "devtmpfs" && m.Source == sysDevice.RealDev) { devMnts = append(devMnts, m) } } return devMnts, nil } // For Windows testing, replace any paths with \\ to have / func replaceBackslashWithSlash(input string) string { return strings.Replace(input, "\\", "/", -1) } // getPathMounts finds all the mounts for a given path. func getPathMounts(path string) ([]gofsutil.Info, error) { ctx := context.Background() devMnts := make([]gofsutil.Info, 0) mnts, err := gofsutil.GetMounts(ctx) if err != nil { return devMnts, err } for _, m := range mnts { if m.Path == path { devMnts = append(devMnts, m) } } return devMnts, nil } func removeWithRetry(target string) error { var err error for i := 0; i < 3; i++ { err = os.Remove(target) if err != nil && !os.IsNotExist(err) { log.Error("error removing private mount target: " + err.Error()) err = os.RemoveAll(target) if err != nil { log.Errorf("Error removing directory: %v", err.Error()) } time.Sleep(3 * time.Second) } else { err = nil break } } return err } // Evaulate symlinks to a resolution. In case of an error, // logs the error but returns the original path. func evalSymlinks(path string) string { // eval any symlinks and make sure it points to a device d, err := filepath.EvalSymlinks(path) if err != nil { log.Error("Could not evaluate symlinks for path: " + path) return path } return d } // Given a volume capability, validates it and returns: // boolean isBlock -- the capability is for a block device // csi.VolumeCapability_MountVolume - contains FsType and MountFlags // csi.VolumeCapability_AccessMode accMode gives the access mode // string multiAccessFlag - "rw" or "ro" or "" as appropriate // error func validateVolumeCapability(volCap *csi.VolumeCapability, readOnly bool) (bool, *csi.VolumeCapability_MountVolume, *csi.VolumeCapability_AccessMode, string, error) { var mntVol *csi.VolumeCapability_MountVolume isBlock := false isMount := false multiAccessFlag := "" accMode := volCap.GetAccessMode() if accMode == nil { return false, mntVol, nil, "", status.Error(codes.InvalidArgument, "Volume Access Mode is required") } if blockVol := volCap.GetBlock(); blockVol != nil { isBlock = true switch accMode.GetMode() { case csi.VolumeCapability_AccessMode_UNKNOWN: return true, mntVol, accMode, "", status.Error(codes.InvalidArgument, "Unknown Access Mode") case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER: case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY: case csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY: multiAccessFlag = "ro" case csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER: case csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER: multiAccessFlag = "rw" } if readOnly { return true, mntVol, accMode, "", status.Error(codes.InvalidArgument, "read only not supported for Block Volume") } } mntVol = volCap.GetMount() if mntVol != nil { isMount = true switch accMode.GetMode() { case csi.VolumeCapability_AccessMode_UNKNOWN: return false, mntVol, accMode, "", status.Error(codes.InvalidArgument, "Unknown Access Mode") case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER: if mountAllowRWOMultiPodAccess { multiAccessFlag = "rw" } case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY: if mountAllowRWOMultiPodAccess { multiAccessFlag = "ro" } case csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY: multiAccessFlag = "ro" case csi.VolumeCapability_AccessMode_MULTI_NODE_SINGLE_WRITER: case csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER: return false, mntVol, accMode, "", status.Error(codes.AlreadyExists, "Mount volumes do not support AccessMode MULTI_NODE_MULTI_WRITER") } } if !isBlock && !isMount { return false, mntVol, accMode, "", status.Error(codes.InvalidArgument, "Volume Access Type is required") } return isBlock, mntVol, accMode, multiAccessFlag, nil } // singleAccessMode returns true if only a single access is allowed SINGLE_NODE_WRITER or SINGLE_NODE_READER_ONLY func singleAccessMode(accMode *csi.VolumeCapability_AccessMode) bool { if mountAllowRWOMultiPodAccess { // User specifically asks for multi-pod access on same nodes return false } switch accMode.GetMode() { case csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER: return true case csi.VolumeCapability_AccessMode_SINGLE_NODE_READER_ONLY: return true } return false } func createTarget(target string, isBlock bool) error { var err error // Make sure target is created. The spec says the driver is responsible // for creating the target, but Kubernetes generallly creates the target. if isBlock { _, err = mkfile(target) if err != nil { return status.Error(codes.FailedPrecondition, fmt.Sprintf("Could not create %s: %s", target, err.Error())) } } else { _, err = mkdir(target) if err != nil { return status.Error(codes.FailedPrecondition, fmt.Sprintf("Could not create %s: %s", target, err.Error())) } } return nil } // cleanupPrivateTarget unmounts and removes the private directory for the retry so clean start next time. func cleanupPrivateTarget(reqID, privTgt string) { log.WithField("CSIRequestID", reqID).WithField("privTgt", privTgt).Info("Cleaning up private target") if privErr := gofsutil.Unmount(context.Background(), privTgt); privErr != nil { log.WithField("CSIRequestID", reqID).Printf("Error unmounting privTgt %s: %s", privTgt, privErr) } if privErr := removeWithRetry(privTgt); privErr != nil { log.WithField("CSIRequestID", reqID).Printf("Error removing privTgt %s: %s", privTgt, privErr) } } // mountBlock bind mounts the device to the required target func mountBlock(device *Device, target string, mntFlags []string, singleAccess bool) error { log.Printf("mountBlock called device %#v target %s mntFlags %#v", device, target, mntFlags) // Check to see if already mounted mnts, err := getDevMounts(device) if err != nil { return status.Errorf(codes.Internal, "Could not getDevMounts for: %s", device.RealDev) } for _, mnt := range mnts { if mnt.Path == target { log.Info("Block volume target is already mounted") return nil } else if singleAccess { return status.Error(codes.InvalidArgument, "Access mode conflicts with existing mounts") } } err = createTarget(target, true) if err != nil { return status.Error(codes.FailedPrecondition, fmt.Sprintf("Could not create %s: %s", target, err.Error())) } err = gofsutil.BindMount(context.Background(), device.RealDev, target, mntFlags...) if err != nil { return status.Errorf(codes.Internal, "error bind mounting to target path: %s", target) } return nil }
GetDevice
geos_test.go
package geos import ( "regexp" "testing" ) func TestVersion(t *testing.T) { t.Skip() const re = `3\.6\.\d+-CAPI-(\d|.)+ [0-9a-z]+$` version := Version() matched, err := regexp.MatchString(re, version) if err != nil { t.Fatal("Version regex:", err) } if !matched
}
{ t.Errorf("Version(): %q didn't match regex \"%s\"", version, re) }
savp.py
# coding=utf-8 # Copyright 2018 The Tensor2Tensor Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Stochastic Adversarial Video Prediction model. Reference: https://arxiv.org/abs/1804.01523 """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import numbers import numpy as np from tensor2tensor.layers import common_layers from tensor2tensor.layers import common_video from tensor2tensor.models.video import savp_params # pylint: disable=unused-import from tensor2tensor.models.video import sv2p from tensor2tensor.utils import registry from tensor2tensor.utils import update_ops_hook import tensorflow as tf gan_losses = tf.contrib.gan.losses.wargs
def encoder(self, inputs, n_layers=3): """Convnet that encodes inputs into mean and std of a gaussian. Args: inputs: 5-D Tensor, shape (batch_size, num_frames, width, height, channels) n_layers: Number of layers. Returns: z_mu: Mean of the latent gaussians. z_log_var: log(var) of the latent gaussians. Raises: ValueError: If inputs is not a 5-D tensor or not float32. """ latent_dims = self.hparams.z_dim shape_as_list = inputs.shape.as_list() if len(shape_as_list) != 5: raise ValueError("Expected inputs to be a 5-D, got %d" % len(shape_as_list)) if inputs.dtype != tf.float32: raise ValueError("Expected dtype tf.float32, got %s" % inputs.dtype) # Flatten (N,T,W,H,C) into (NT,W,H,C) batch_size, _ = shape_as_list[:2] inputs = tf.reshape(inputs, [-1] + list(inputs.shape)[2:]) n_filters = 64 rectified = None # Applies 3 layer conv-net with padding, instance normalization # and leaky relu as per the encoder in # https://github.com/alexlee-gk/video_prediction padding = [[0, 0], [1, 1], [1, 1], [0, 0]] for i in range(n_layers): with tf.variable_scope("layer_%d" % (i + 1)): n_filters *= 2**i if i: padded = tf.pad(rectified, padding) else: padded = tf.pad(inputs, padding) convolved = tf.layers.conv2d(padded, filters=n_filters, kernel_size=4, strides=2, padding="VALID") normalized = tf.contrib.layers.instance_norm(convolved) rectified = tf.nn.leaky_relu(normalized, alpha=0.2) # Mean pooling across all spatial dimensions. pooled = tf.nn.avg_pool( rectified, [1] + rectified.shape[1:3].as_list() + [1], strides=[1, 1, 1, 1], padding="VALID") squeezed = tf.squeeze(pooled, [1, 2]) # Down-project and output the mean and log of the standard deviation of # the latents. with tf.variable_scope("z_mu"): z_mu = tf.layers.dense(squeezed, latent_dims) with tf.variable_scope("z_log_sigma_sq"): z_log_var = tf.layers.dense(squeezed, latent_dims) z_log_var = tf.clip_by_value(z_log_var, -10, 10) # Reshape to (batch_size X num_frames X latent_dims) z_mu = tf.reshape(z_mu, (batch_size, -1, latent_dims)) z_log_var = tf.reshape( z_log_var, (batch_size, -1, latent_dims)) return z_mu, z_log_var def expected_output_shape(self, input_shape, stride, padding, kernel_size): return (input_shape + 2*padding - kernel_size) // stride + 1 def get_fc_dimensions(self, strides, kernel_sizes): """Get expected fully connected shape after a series of convolutions.""" output_height, output_width, _ = self.hparams.problem.frame_shape output_steps = self.hparams.video_num_target_frames output_shape = np.array([output_steps, output_height, output_width]) for curr_stride, kernel_size in zip(strides, kernel_sizes): output_shape = self.expected_output_shape( output_shape, np.array(curr_stride), 1, kernel_size) return np.prod(output_shape) * self.hparams.num_discriminator_filters * 8 def discriminator(self, frames): """3-D SNGAN discriminator. Args: frames: a list of batch-major tensors indexed by time. Returns: logits: 1-D Tensor with shape=batch_size. Positive logits imply that the discriminator thinks that it belongs to the true class. """ ndf = self.hparams.num_discriminator_filters frames = tf.stack(frames) # Switch from time-major axis to batch-major axis. frames = common_video.swap_time_and_batch_axes(frames) # 3-D Conv-net mapping inputs to activations. num_outputs = [ndf, ndf*2, ndf*2, ndf*4, ndf*4, ndf*8, ndf*8] kernel_sizes = [3, 4, 3, 4, 3, 4, 3] strides = [[1, 1, 1], [1, 2, 2], [1, 1, 1], [1, 2, 2], [1, 1, 1], [2, 2, 2], [1, 1, 1]] names = ["video_sn_conv0_0", "video_sn_conv0_1", "video_sn_conv1_0", "video_sn_conv1_1", "video_sn_conv2_0", "video_sn_conv2_1", "video_sn_conv3_0"] iterable = zip(num_outputs, kernel_sizes, strides, names) activations = frames for num_filters, kernel_size, stride, name in iterable: activations = self.pad_conv3d_lrelu(activations, num_filters, kernel_size, stride, name) num_fc_dimensions = self.get_fc_dimensions(strides, kernel_sizes) activations = tf.reshape(activations, (-1, num_fc_dimensions)) return tf.squeeze(tf.layers.dense(activations, 1)) def d_step(self, true_frames, gen_frames): """Performs the discriminator step in computing the GAN loss. Applies stop-gradient to the generated frames while computing the discriminator loss to make sure that the gradients are not back-propagated to the generator. This makes sure that only the discriminator is updated. Args: true_frames: True outputs gen_frames: Generated frames. Returns: d_loss: Loss component due to the discriminator. """ hparam_to_disc_loss = { "least_squares": gan_losses.least_squares_discriminator_loss, "cross_entropy": gan_losses.modified_discriminator_loss, "wasserstein": gan_losses.wasserstein_discriminator_loss} # Concat across batch-axis. _, batch_size, _, _, _ = common_layers.shape_list(true_frames) all_frames = tf.concat( [true_frames, tf.stop_gradient(gen_frames)], axis=1) all_logits = self.discriminator(all_frames) true_logits, fake_logits_stop = \ all_logits[:batch_size], all_logits[batch_size:] mean_true_logits = tf.reduce_mean(true_logits) tf.summary.scalar("mean_true_logits", mean_true_logits) mean_fake_logits_stop = tf.reduce_mean(fake_logits_stop) tf.summary.scalar("mean_fake_logits_stop", mean_fake_logits_stop) discriminator_loss_func = hparam_to_disc_loss[self.hparams.gan_loss] gan_d_loss = discriminator_loss_func( discriminator_real_outputs=true_logits, discriminator_gen_outputs=fake_logits_stop, add_summaries=True) return gan_d_loss, true_logits, fake_logits_stop def g_step(self, gen_frames, fake_logits_stop): """Performs the generator step in computing the GAN loss. Args: gen_frames: Generated frames fake_logits_stop: Logits corresponding to the generated frames as per the discriminator. Assumed to have a stop-gradient term. Returns: gan_g_loss_pos_d: Loss. gan_g_loss_neg_d: -gan_g_loss_pos_d but with a stop gradient on generator. """ hparam_to_gen_loss = { "least_squares": gan_losses.least_squares_generator_loss, "cross_entropy": gan_losses.modified_generator_loss, "wasserstein": gan_losses.wasserstein_generator_loss } fake_logits = self.discriminator(gen_frames) mean_fake_logits = tf.reduce_mean(fake_logits) tf.summary.scalar("mean_fake_logits", mean_fake_logits) # Generator loss. # Using gan_g_loss_pos_d updates the discriminator as well. # To avoid this add gan_g_loss_neg_d = -gan_g_loss_pos_d # but with stop gradient on the generator. # This makes sure that the net gradient on the discriminator is zero and # net-gradient on the generator is just due to the gan_g_loss_pos_d. generator_loss_func = hparam_to_gen_loss[self.hparams.gan_loss] gan_g_loss_pos_d = generator_loss_func( discriminator_gen_outputs=fake_logits, add_summaries=True) gan_g_loss_neg_d = -generator_loss_func( discriminator_gen_outputs=fake_logits_stop, add_summaries=True) return gan_g_loss_pos_d, gan_g_loss_neg_d def get_gan_loss(self, true_frames, gen_frames, name): """Get the discriminator + generator loss at every step. This performs an 1:1 update of the discriminator and generator at every step. Args: true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be ground truth. gen_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C) Assumed to be fake. name: discriminator scope. Returns: loss: 0-D Tensor, with d_loss + g_loss """ # D - STEP with tf.variable_scope("%s_discriminator" % name, reuse=tf.AUTO_REUSE): gan_d_loss, _, fake_logits_stop = self.d_step( true_frames, gen_frames) # G - STEP with tf.variable_scope("%s_discriminator" % name, reuse=True): gan_g_loss_pos_d, gan_g_loss_neg_d = self.g_step( gen_frames, fake_logits_stop) gan_g_loss = gan_g_loss_pos_d + gan_g_loss_neg_d tf.summary.scalar("gan_loss_%s" % name, gan_g_loss_pos_d + gan_d_loss) if self.hparams.gan_optimization == "joint": gan_loss = gan_g_loss + gan_d_loss else: curr_step = self.get_iteration_num() gan_loss = tf.cond( tf.logical_not(curr_step % 2 == 0), lambda: gan_g_loss, lambda: gan_d_loss) return gan_loss def get_extra_loss(self, latent_means=None, latent_stds=None, true_frames=None, gen_frames=None): """Gets extra loss from VAE and GAN.""" if not self.is_training: return 0.0 vae_loss, d_vae_loss, d_gan_loss = 0.0, 0.0, 0.0 # Use sv2p's KL divergence computation. if self.hparams.use_vae: vae_loss = super(NextFrameSavpBase, self).get_extra_loss( latent_means=latent_means, latent_stds=latent_stds) if self.hparams.use_gan: # Strip out the first context_frames for the true_frames # Strip out the first context_frames - 1 for the gen_frames context_frames = self.hparams.video_num_input_frames true_frames = tf.stack( tf.unstack(true_frames, axis=0)[context_frames:]) # discriminator for VAE. if self.hparams.use_vae: gen_enc_frames = tf.stack( tf.unstack(gen_frames, axis=0)[context_frames-1:]) d_vae_loss = self.get_gan_loss(true_frames, gen_enc_frames, name="vae") # discriminator for GAN. gen_prior_frames = tf.stack( tf.unstack(self.gen_prior_video, axis=0)[context_frames-1:]) d_gan_loss = self.get_gan_loss(true_frames, gen_prior_frames, name="gan") return ( vae_loss + self.hparams.gan_loss_multiplier * d_gan_loss + self.hparams.gan_vae_loss_multiplier * d_vae_loss) def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides, scope): """Pad, apply 3-D convolution and leaky relu.""" padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]] # tf.nn.conv3d accepts a list of 5 values for strides # with first and last value equal to 1 if isinstance(strides, numbers.Integral): strides = [strides] * 3 strides = [1] + strides + [1] # Filter_shape = [K, K, K, num_input, num_output] filter_shape = ( [kernel_size]*3 + activations.shape[-1:].as_list() + [n_filters]) with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): conv_filter = tf.get_variable( "conv_filter", shape=filter_shape, initializer=tf.truncated_normal_initializer(stddev=0.02)) if self.hparams.use_spectral_norm: conv_filter, assign_op = common_layers.apply_spectral_norm(conv_filter) if self.is_training: tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, assign_op) padded = tf.pad(activations, padding) convolved = tf.nn.conv3d( padded, conv_filter, strides=strides, padding="VALID") rectified = tf.nn.leaky_relu(convolved, alpha=0.2) return rectified @staticmethod def train_hooks(hook_context): del hook_context return [update_ops_hook.UpdateOpsHook()] @registry.register_model class NextFrameSAVP(NextFrameSavpBase, sv2p.NextFrameSv2pLegacy): """Stochastic Adversarial Video Prediction.""" def construct_model(self, images, actions, rewards): """Model that takes in images and returns predictions. Args: images: list of 4-D Tensors indexed by time. (batch_size, width, height, channels) actions: list of action tensors each action should be in the shape ?x1xZ rewards: list of reward tensors each reward should be in the shape ?x1xZ Returns: video: list of 4-D predicted frames. all_rewards: predicted rewards. latent_means: list of gaussian means conditioned on the input at every frame. latent_stds: list of gaussian stds conditioned on the input at every frame. Raises: ValueError: If not exactly one of self.hparams.vae or self.hparams.gan is set to True. """ if not self.hparams.use_vae and not self.hparams.use_gan: raise ValueError("Set at least one of use_vae or use_gan to be True") if self.hparams.gan_optimization not in ["joint", "sequential"]: raise ValueError("self.hparams.gan_optimization should be either joint " "or sequential got %s" % self.hparams.gan_optimization) images = tf.unstack(images, axis=0) actions = tf.unstack(actions, axis=0) rewards = tf.unstack(rewards, axis=0) latent_dims = self.hparams.z_dim context_frames = self.hparams.video_num_input_frames seq_len = len(images) input_shape = common_layers.shape_list(images[0]) batch_size = input_shape[0] # Model does not support reward-conditioned frame generation. fake_rewards = rewards[:-1] # Concatenate x_{t-1} and x_{t} along depth and encode it to # produce the mean and standard deviation of z_{t-1} image_pairs = tf.concat([images[:seq_len - 1], images[1:seq_len]], axis=-1) z_mu, z_log_sigma_sq = self.encoder(image_pairs) # Unstack z_mu and z_log_sigma_sq along the time dimension. z_mu = tf.unstack(z_mu, axis=0) z_log_sigma_sq = tf.unstack(z_log_sigma_sq, axis=0) iterable = zip(images[:-1], actions[:-1], fake_rewards, z_mu, z_log_sigma_sq) # Initialize LSTM State lstm_state = [None] * 7 gen_cond_video, gen_prior_video, all_rewards, latent_means, latent_stds = \ [], [], [], [], [] pred_image = tf.zeros_like(images[0]) prior_latent_state, cond_latent_state = None, None train_mode = self.hparams.mode == tf.estimator.ModeKeys.TRAIN # Create scheduled sampling function ss_func = self.get_scheduled_sample_func(batch_size) with tf.variable_scope("prediction", reuse=tf.AUTO_REUSE): for step, (image, action, reward, mu, log_sigma_sq) in enumerate(iterable): # pylint:disable=line-too-long # Sample latents using a gaussian centered at conditional mu and std. latent = common_video.get_gaussian_tensor(mu, log_sigma_sq) # Sample prior latents from isotropic normal distribution. prior_latent = tf.random_normal(tf.shape(latent), dtype=tf.float32) # LSTM that encodes correlations between conditional latents. # Pg 22 in https://arxiv.org/pdf/1804.01523.pdf enc_cond_latent, cond_latent_state = common_video.basic_lstm( latent, cond_latent_state, latent_dims, name="cond_latent") # LSTM that encodes correlations between prior latents. enc_prior_latent, prior_latent_state = common_video.basic_lstm( prior_latent, prior_latent_state, latent_dims, name="prior_latent") # Scheduled Sampling done_warm_start = step > context_frames - 1 groundtruth_items = [image] generated_items = [pred_image] input_image, = self.get_scheduled_sample_inputs( done_warm_start, groundtruth_items, generated_items, ss_func) all_latents = tf.concat([enc_cond_latent, enc_prior_latent], axis=0) all_image = tf.concat([input_image, input_image], axis=0) all_action = tf.concat([action, action], axis=0) all_rewards = tf.concat([reward, reward], axis=0) all_pred_images, lstm_state, _ = self.construct_predictive_tower( all_image, all_rewards, all_action, lstm_state, all_latents, concat_latent=True) cond_pred_images, prior_pred_images = \ all_pred_images[:batch_size], all_pred_images[batch_size:] if train_mode and self.hparams.use_vae: pred_image = cond_pred_images else: pred_image = prior_pred_images gen_cond_video.append(cond_pred_images) gen_prior_video.append(prior_pred_images) latent_means.append(mu) latent_stds.append(log_sigma_sq) gen_cond_video = tf.stack(gen_cond_video, axis=0) self.gen_prior_video = tf.stack(gen_prior_video, axis=0) fake_rewards = tf.stack(fake_rewards, axis=0) if train_mode and self.hparams.use_vae: return gen_cond_video, fake_rewards, latent_means, latent_stds else: return self.gen_prior_video, fake_rewards, latent_means, latent_stds @registry.register_model class NextFrameSavpRl(NextFrameSavpBase, sv2p.NextFrameSv2p): """Stochastic Adversarial Video Prediction for RL pipeline.""" def video_features( self, all_frames, all_actions, all_rewards, all_raw_frames): """No video wide feature.""" del all_actions, all_rewards, all_raw_frames # Concatenate x_{t-1} and x_{t} along depth and encode it to # produce the mean and standard deviation of z_{t-1} seq_len = len(all_frames) image_pairs = tf.concat([all_frames[:seq_len-1], all_frames[1:seq_len]], axis=-1) z_mu, z_log_sigma_sq = self.encoder(image_pairs) # Unstack z_mu and z_log_sigma_sq along the time dimension. z_mu = tf.unstack(z_mu, axis=0) z_log_sigma_sq = tf.unstack(z_log_sigma_sq, axis=0) return [z_mu, z_log_sigma_sq] def video_extra_loss(self, frames_predicted, frames_target, internal_states, video_features): if not self.is_training: return 0.0 latent_means, latent_stds = video_features true_frames, gen_frames = frames_target, frames_predicted loss = super(NextFrameSavpRl, self).get_extra_loss( latent_means=latent_means, latent_stds=latent_stds, true_frames=true_frames, gen_frames=gen_frames) return loss def next_frame(self, frames, actions, rewards, target_frame, internal_states, video_features): del target_frame if not self.hparams.use_vae or self.hparams.use_gan: raise NotImplementedError("Only supporting VAE for now.") if self.has_pred_actions or self.has_values: raise NotImplementedError("Parameter sharing with policy not supported.") image, action, reward = frames[0], actions[0], rewards[0] latent_dims = self.hparams.z_dim batch_size = common_layers.shape_list(image)[0] if internal_states is None: # Initialize LSTM State frame_index = 0 lstm_state = [None] * 7 cond_latent_state, prior_latent_state = None, None gen_prior_video = [] else: (frame_index, lstm_state, cond_latent_state, prior_latent_state, gen_prior_video) = internal_states z_mu, log_sigma_sq = video_features z_mu, log_sigma_sq = z_mu[frame_index], log_sigma_sq[frame_index] # Sample latents using a gaussian centered at conditional mu and std. latent = common_video.get_gaussian_tensor(z_mu, log_sigma_sq) # Sample prior latents from isotropic normal distribution. prior_latent = tf.random_normal(tf.shape(latent), dtype=tf.float32) # # LSTM that encodes correlations between conditional latents. # # Pg 22 in https://arxiv.org/pdf/1804.01523.pdf enc_cond_latent, cond_latent_state = common_video.basic_lstm( latent, cond_latent_state, latent_dims, name="cond_latent") # LSTM that encodes correlations between prior latents. enc_prior_latent, prior_latent_state = common_video.basic_lstm( prior_latent, prior_latent_state, latent_dims, name="prior_latent") all_latents = tf.concat([enc_cond_latent, enc_prior_latent], axis=0) all_image = tf.concat([image, image], 0) all_action = tf.concat([action, action], 0) if self.has_actions else None all_pred_images, lstm_state = self.construct_predictive_tower( all_image, None, all_action, lstm_state, all_latents, concat_latent=True) cond_pred_images, prior_pred_images = \ all_pred_images[:batch_size], all_pred_images[batch_size:] if self.is_training and self.hparams.use_vae: pred_image = cond_pred_images else: pred_image = prior_pred_images gen_prior_video.append(prior_pred_images) internal_states = (frame_index + 1, lstm_state, cond_latent_state, prior_latent_state, gen_prior_video) if not self.has_rewards: return pred_image, None, 0.0, internal_states pred_reward = self.reward_prediction( pred_image, action, reward, latent) return pred_image, pred_reward, None, None, 0.0, internal_states
class NextFrameSavpBase(object): """Main function for Stochastic Adversarial Video Prediction."""
index.js
import BaseRoute from '../-privates/routes/base'; export default BaseRoute.extend({ title: 'Ember Tracker: A simpler way to track your Ember JS application.',
});
msgs_test.py
from terra_sdk.core.slashing import MsgUnjail def test_deserializes_msg_unjail_examples(load_msg_examples):
examples = load_msg_examples(MsgUnjail.type, "./MsgUnjail.data.json") for example in examples: assert MsgUnjail.from_data(example).to_data() == example
devsite.js
'use strict'; (function() { function getCookieValue(name, defaultValue) { var value = document.cookie.match('(^|;)\\s*' + name + '\\s*=\\s*([^;]+)'); return value ? value.pop() : defaultValue; } function showHeader(visible) { if (bannerVisible === visible) { return; } const body = document.querySelector('body.devsite-landing-page'); if (!body) { return; } if (visible === true) { body.querySelector('.devsite-wrapper') .style.marginTop = navHeadHeight + 'px'; body.querySelector('header.devsite-top-section') .classList.remove('devsite-top-section-pinned'); body.querySelector('.devsite-top-logo-row-wrapper-wrapper') .style.position = 'fixed'; body.querySelector('.devsite-collapsible-section') .style.marginTop = '0px'; } else { body.querySelector('.devsite-wrapper') .style.marginTop = (navHeadHeight + bannerHeight) + 'px'; body.querySelector('header.devsite-top-section') .classList.add('devsite-top-section-pinned'); body.querySelector('.devsite-top-logo-row-wrapper-wrapper') .style.position = 'relative'; body.querySelector('.devsite-collapsible-section') .style.marginTop = '-190px'; } bannerVisible = visible; } function initNavToggles() { var elems = document .querySelectorAll('.devsite-section-nav .devsite-nav-item-section-expandable'); elems.forEach(function(elem) { var span = elem.querySelector('span'); span.addEventListener('click', toggleNav); var link = elem.querySelector('a.devsite-nav-toggle'); link.addEventListener('click', toggleNav); }); } function initLangSelector() { var currentLang = getCookieValue('hl'); var langSelector = document.querySelector('#langSelector'); var langOptions = langSelector.querySelectorAll('option'); langOptions.forEach(function(opt) { if (opt.value === currentLang) { opt.setAttribute('selected', true); } }); langSelector.addEventListener('change', function(evt) { var newLang = langSelector.selectedOptions[0].value; var newUrl = window.location.origin + window.location.pathname; newUrl += '?hl=' + newLang; newUrl += window.location.hash; window.location = newUrl; }); } /* Expand/Collapses the Primary Left Hand Nav */ function toggleNav(event) { var srcElement = event.srcElement || event.target; var srcParent = srcElement.parentElement; // Ensure's we're in the outer most <span> if (srcElement.localName === 'span' && srcParent.localName === 'span') { srcElement = srcElement.parentElement; srcParent = srcElement.parentElement; } // Grabs the anchor and the UL so we can update them var anchor = srcParent.querySelector('a.devsite-nav-toggle'); var ul = srcParent.querySelector('ul.devsite-nav-section'); // Toggles the expanded/collapsed classes anchor.classList.toggle('devsite-nav-toggle-expanded'); anchor.classList.toggle('devsite-nav-toggle-collapsed'); ul.classList.toggle('devsite-nav-section-collapsed'); ul.classList.toggle('devsite-nav-section-expanded'); } function
() { var elems = document.querySelectorAll('.devsite-section-nav a.devsite-nav-title'); var currentURL = window.location.pathname; for (var i = 0; i < elems.length; i++) { var elem = elems[i]; if (currentURL === elem.getAttribute('href')) { var parentLI = elem.parentElement; if (parentLI.localName === 'li') { parentLI.classList.add('devsite-nav-active'); expandPathAndHighlight(parentLI); break; } } } } function expandPathAndHighlight(elem) { // Walks up the tree from the current element and expands all tree nodes var parent = elem.parentElement; var parentIsCollapsed = parent.classList.contains('devsite-nav-section-collapsed'); if (parent.localName === 'ul' && parentIsCollapsed) { parent.classList.toggle('devsite-nav-section-collapsed'); parent.classList.toggle('devsite-nav-section-expanded'); // Checks if the grandparent is an expandable element var grandParent = parent.parentElement; var grandParentIsExpandable = grandParent.classList.contains('devsite-nav-item-section-expandable'); if (grandParent.localName === 'li' && grandParentIsExpandable) { var anchor = grandParent.querySelector('a.devsite-nav-toggle'); anchor.classList.toggle('devsite-nav-toggle-expanded'); anchor.classList.toggle('devsite-nav-toggle-collapsed'); expandPathAndHighlight(grandParent); } } } function initYouTubeVideos() { var videoElements = document.querySelectorAll('iframe.devsite-embedded-youtube-video'); videoElements.forEach(function(elem) { var videoID = elem.getAttribute('data-video-id'); if (videoID) { var videoURL = 'https://www.youtube.com/embed/' + videoID; videoURL += '?autohide=1&amp;showinfo=0&amp;enablejsapi=1'; elem.src = videoURL; } }); } function initFeed() { var placeholderTitle = 'RSS Feed Widget is not supported.'; var placeholderText = 'The RSS Feed Widget is <b>NOT</b> supported in the '; placeholderText += 'local development environment. Sorry. '; placeholderText += 'Lorem ipsum dolor sit amet, perfecto volutpat prodesset duo ei. Per ne albucius consulatu. Graece repudiandae ut vis. Quot omnis vix ad, prodesset consetetur persequeris ea mel. Nostrum urbanitas usu eu, qui id graeci facilisi.'; var feedElements = document.querySelectorAll('div.feed.hfeed:not(.rendered)'); feedElements.forEach(function(elem) { elem.querySelector('article.hentry').style.display = 'block'; elem.querySelector('header').textContent = placeholderTitle; elem.querySelector('.entry-content').innerHTML = placeholderText; elem.querySelector('.published').textContent = 'January 1st, 2016'; }); } initNavToggles(); highlightActiveNavElement(); initYouTubeVideos(); initFeed(); initLangSelector(); let bannerVisible = true; const navHeadHeight = 48; const bannerHeight = document.querySelector('header.devsite-top-section') .clientHeight; window.addEventListener('scroll', function(e) { if (window.scrollY > bannerHeight) { showHeader(false); } else if (window.scrollY < bannerHeight) { showHeader(true); } }); })();
highlightActiveNavElement
guests.core.js
/* eslint-disable camelcase */ /* eslint-disable no-unused-vars */ const configs = require('configs/index'); const constant = require('common/constant'); const guestODM = require('db/odm/guest.odm'); const userODM = require('db/odm/user.odm'); const eventODM = require('db/odm/event.odm'); const { Types } = require('mongoose'); const pagination = require('utils/pagination'); const { EventNotFoundError, GuestExistedError, GuestNotFoundError, EmailVerifiedError, TicketApprovedError, TicketCheckedInError, } = require('common/error'); const { VerifyGuestEmail, TicketEmail } = require('common/mail'); const base64 = require('utils/base64'); const MailgunService = require('services/mailgun'); const { fromString } = require('uuidv4'); const { ItemsPerPage } = constant; /** * * @param {String} eventId * @param {Number} page */ async function findGuestsByEventId(eventId, page) { const totalGuests = await guestODM.countByEventId(eventId); const paginatedObject = pagination .getPaginatedObject(totalGuests, ItemsPerPage.GUESTS_LIST, page); const { offset, limit, ...paginationInfo } = paginatedObject; const listGuests = await guestODM.findByEventId(eventId, offset, limit); return { ...paginationInfo, listItems: listGuests, }; } async function findPendingGuestsByEventId(eventId, page) { const totalGuests = await guestODM.countPendingByEventId(eventId); const paginatedObject = pagination .getPaginatedObject(totalGuests, ItemsPerPage.GUESTS_LIST, page); const { offset, limit, ...paginationInfo } = paginatedObject; const listGuests = await guestODM.findPendingByEventId(eventId, offset, limit); return { ...paginationInfo, listItems: listGuests, }; } async function findApprovedGuestsByEventId(eventId, page) { const totalGuests = await guestODM.countApprovedByEventId(eventId); const paginatedObject = pagination .getPaginatedObject(totalGuests, ItemsPerPage.GUESTS_LIST, page); const { offset, limit, ...paginationInfo } = paginatedObject; const listGuests = await guestODM.findAprrovedByEventId(eventId, offset, limit); return { ...paginationInfo, listItems: listGuests, }; } async function findCheckedInGuestsByEventId(eventId, page) { const totalGuests = await guestODM.countCheckedInByEventId(eventId); const paginatedObject = pagination .getPaginatedObject(totalGuests, ItemsPerPage.GUESTS_LIST, page); const { offset, limit, ...paginationInfo } = paginatedObject; const listGuests = await guestODM.findCheckedInByEventId(eventId, offset, limit); return { ...paginationInfo, listItems: listGuests, }; } /** * * @param {String} guestId */ async function findGuestById(guestId) { const guest = await guestODM.findById(guestId); return guest; } /** * * @param {String} userId * @param {String} eventId * @param {Object} guestInfo */ async function saveNewGuestWithEventId(userId, eventId, guestInfo) { const { email, full_name, phone_number, gender, answers, } = guestInfo; const event = await eventODM.findById(eventId); if (!event) { throw new EventNotFoundError(); } const exGuest = await guestODM.findByEventIdAndEmail(eventId, email); if (exGuest) { throw new GuestExistedError({ data: exGuest }); } const user = await userODM.findById(userId); const emailVerified = (user && user.email_verified) ? user.email_verified : false; const newGuest = { event: Types.ObjectId(eventId), email, user: (userId) ? Types.ObjectId(userId) : null, info: { full_name, phone_number, gender, answers, }, status: { email_verified: emailVerified, ticket_approved: false, }, ticket: { code: null, issue_at: null, checkin_at: null, }, }; const savedGuest = await guestODM.save(newGuest); if (!emailVerified) { const verifyLink = `${configs.FE_URL}/verify?eventId=${eventId}&guestId=${savedGuest.id}`; const verifyEmail = new VerifyGuestEmail({ to: `${newGuest.email}`, html: `Xin chào ${newGuest.email} <br/> Bạn đã đăng ký tham gia sự kiện ${event.name}. <br/> Chúng tôi cần bạn xác nhận lại email. Vui lòng ấn vào đường dẫn sau để xác nhận: <br/> <a href="${verifyLink}">${verifyLink}</a><br/> Chúng tôi sẽ gửi thông tin vé sớm nhất cho bạn`, }); verifyEmail.send(); } return { savedGuest, }; } async function sendTicketMail(guest, event, ticketCode) { const da
stId: guest.id, eventId: event.id, ticketCode, }; const dataImage = await base64.getBufferFromObject(data); const ticketMail = new TicketEmail({ to: `${guest.email}`, html: `Xin chào ${guest.email}, lại là Easy Event đây !<br/> Sau đây là vé dành cho sự kiện ${event.name} <br/> <ul> <li>Email: ${guest.email}</li> <li>Gender: ${guest.info.gender}</li> </ul> <br/> Bạn hãy vui lòng sử dụng mã QR Code trong file đính kèm để check in tại sự kiện nhé !`, attachment: new MailgunService.api.Attachment({ data: dataImage, filename: 'ticket.png' }), }); ticketMail.send(); } /** * * @param {String} guestId */ async function updateVerifyGuestEmail(guestId) { const guest = await guestODM.findById(guestId); if (!guest) { throw new GuestNotFoundError(); } if (guest.get('status.email_verified')) { throw new EmailVerifiedError(); } if (guest.user) { const userId = guest.user; await guestODM.update(userId, { email_verified: true }); } const updates = { 'status.email_verified': true, }; const updatedGuest = await guestODM.update(guestId, updates); return { updatedGuest, }; } /** * * @param {String} guestId */ async function updateApproveGuest(guestId) { const guest = await guestODM.findById(guestId); if (!guest) { throw new GuestNotFoundError(); } const event = await eventODM.findById(guest.get('event')); if (guest.get('status.ticket_approved')) { throw new TicketApprovedError(); } const ticketCode = fromString(guestId); const updates = { 'status.ticket_approved': true, 'ticket.code': ticketCode, 'ticket.issue_at': Date.now(), }; sendTicketMail(guest, event, ticketCode); const updatedGuest = await guestODM.update(guestId, updates); return { updatedGuest, }; } /** * * @param {String} guestId */ async function updateCheckinGuest(ticketCode) { const guest = await guestODM.findByCode(ticketCode); if (!guest) { throw new GuestNotFoundError(); } if (guest.get('ticket.checkin_at') !== null) { throw new TicketCheckedInError(); } const guestId = guest.id; const updates = { 'ticket.checkin_at': Date.now(), }; const updatedGuest = await guestODM.update(guestId, updates); return { updatedGuest, }; } /** * * @param {String} code */ async function findGuestByCode(code) { const guest = await guestODM.findByCode(code); return guest; } module.exports = { findGuestsByEventId, findGuestById, findPendingGuestsByEventId, findApprovedGuestsByEventId, findCheckedInGuestsByEventId, saveNewGuestWithEventId, updateVerifyGuestEmail, updateApproveGuest, updateCheckinGuest, findGuestByCode, };
ta = { gue
list.ts
import { Command, CommandResult, help, success, failure, ErrorCodes, shortName, longName, hasArg, required } from "../../../util/commandline"; import { out } from "../../../util/interaction"; import { AppCenterClient, models, clientRequest } from "../../../util/apis"; const debug = require("debug")("appcenter-cli:commands:orgs:collaborators:list"); import { inspect } from "util"; import { getPortalOrgLink } from "../../../util/portal/portal-helper"; import { getOrgUsers } from "../lib/org-users-helper"; @help("Lists collaborators of organization") export default class
extends Command { @help("Name of the organization") @shortName("n") @longName("name") @required @hasArg name: string; async run(client: AppCenterClient, portalBaseUrl: string): Promise<CommandResult> { const users: models.OrganizationUserResponse[] = await getOrgUsers(client, this.name, debug); out.table(out.getCommandOutputTableOptions(["Name", "Display Name", "Email"]), users.map((user) => [user.name, user.displayName, user.email])); return success(); } }
OrgCollaboratorsListCommand
peer_test.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package peer import ( reqContext "context" "reflect" "testing" "time" "github.com/OCRVblockchain/fabric-sdk-go/pkg/common/providers/fab" "github.com/OCRVblockchain/fabric-sdk-go/pkg/common/providers/test/mockfab" "github.com/golang/mock/gomock" ) const ( normalTimeout = 5 * time.Second ) // TestNewPeerWithCertNoTLS tests that a peer can be constructed without using a cert func TestNewPeerWithCertNoTLS(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) url := "http://example.com" p, err := New(config, WithURL(url)) if err != nil { t.Fatal("Expected peer to be constructed") } if p.URL() != url { t.Fatal("Unexpected peer URL") } } // TestNewPeerTLSFromCert tests that a peer can be constructed using a cert func TestNewPeerTLSFromCert(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) url := "grpcs://0.0.0.0:1234" // TODO - test actual parameters and test server name override _, err := New(config, WithURL(url), WithTLSCert(mockfab.GoodCert)) if err != nil
} // TestNewPeerWithCertBadParams tests that bad parameters causes an expected failure func TestNewPeerWithCertBadParams(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) _, err := New(config) if err == nil { t.Fatal("Peer should not be constructed - bad params") } } // TestNewPeerTLSFromCertBad tests that bad parameters causes an expected failure func TestNewPeerTLSFromCertBad(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.BadTLSClientMockConfig(mockCtrl) url := "grpcs://0.0.0.0:1234" _, err := New(config, WithURL(url)) if err == nil { t.Fatal("Expected peer construction to fail") } } func TestMSPIDs(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) testMSP := "orgN" peer, err := New(config, WithURL(peer1URL), WithMSPID(testMSP)) if err != nil { t.Fatalf("Failed to create NewPeer error(%s)", err) } if peer.MSPID() != testMSP { t.Fatal("Unexpected peer msp id") } } // Test that peer is proxy for proposal processor interface func TestProposalProcessorSendProposal(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() proc := mockfab.NewMockProposalProcessor(mockCtrl) tp := mockProcessProposalRequest() tpr := fab.TransactionProposalResponse{Endorser: "example.com", Status: 99, ProposalResponse: nil} proc.EXPECT().ProcessTransactionProposal(gomock.Any(), tp).Return(&tpr, nil) p := Peer{processor: proc} ctx, cancel := reqContext.WithTimeout(reqContext.Background(), normalTimeout) defer cancel() tpr1, err := p.ProcessTransactionProposal(ctx, tp) if err != nil || !reflect.DeepEqual(&tpr, tpr1) { t.Fatal("Peer didn't proxy proposal processing") } } func TestPeersToTxnProcessors(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) peer1, err := New(config, WithURL(peer1URL)) if err != nil { t.Fatalf("Failed to create NewPeer error(%s)", err) } peer2, err := New(config, WithURL(peer2URL)) if err != nil { t.Fatalf("Failed to create NewPeer error(%s)", err) } peers := []fab.Peer{peer1, peer2} processors := PeersToTxnProcessors(peers) for i := range peers { if !reflect.DeepEqual(peers[i], processors[i]) { t.Fatal("Peer to Processors mismatch") } } } func TestInterfaces(t *testing.T) { var apiPeer fab.Peer var peer Peer apiPeer = &peer if apiPeer == nil { t.Fatal("this shouldn't happen.") } } func TestWithServerName(t *testing.T) { option := WithServerName("name") if option == nil { t.Fatal("Failed to get option for server name.") } } func TestPeerOptions(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() grpcOpts := make(map[string]interface{}) grpcOpts["fail-fast"] = true grpcOpts["keep-alive-time"] = 1 * time.Second grpcOpts["keep-alive-timeout"] = 2 * time.Second grpcOpts["keep-alive-permit"] = false grpcOpts["ssl-target-name-override"] = "mnq" grpcOpts["allow-insecure"] = true config := mockfab.DefaultMockConfig(mockCtrl) peerConfig := fab.PeerConfig{ URL: "abc.com", GRPCOptions: grpcOpts, } networkPeer := &fab.NetworkPeer{ PeerConfig: peerConfig, MSPID: "Org1MSP", } //from config with grpc _, err := New(config, FromPeerConfig(networkPeer)) if err != nil { t.Fatalf("Failed to create new peer FromPeerConfig (%s)", err) } //with peer processor _, err = New(config, WithPeerProcessor(nil)) if err == nil { t.Fatal("Expected 'Failed to create new peer WithPeerProcessor ((target is required))") } //with peer processor _, err = New(config, WithServerName("server-name")) if err == nil { t.Fatal("Expected 'Failed to create new peer WithServerName ((target is required))") } } // TestNewPeerSecured validates that insecure option func TestNewPeerSecured(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() config := mockfab.DefaultMockConfig(mockCtrl) url := "grpc://0.0.0.0:1234" conn, err := New(config, WithURL(url), WithInsecure()) if err != nil { t.Fatal("Peer conn should be constructed") } if !conn.inSecure { t.Fatal("Expected insecure to be true") } }
{ t.Fatal("Expected peer to be constructed") }
test_prophet_regressor.py
import numpy as np import pandas as pd import pytest from pytest import importorskip from evalml.model_family import ModelFamily from evalml.pipelines.components import ProphetRegressor from evalml.problem_types import ProblemTypes prophet = importorskip("prophet", reason="Skipping test because prophet not installed") def test_model_family(): assert ProphetRegressor.model_family == ModelFamily.PROPHET def test_cmdstanpy_backend(): m = prophet.Prophet(stan_backend="CMDSTANPY") assert m.stan_backend.get_type() == "CMDSTANPY" def test_problem_types(): assert set(ProphetRegressor.supported_problem_types) == { ProblemTypes.TIME_SERIES_REGRESSION } def test_init_with_other_params(): clf = ProphetRegressor( daily_seasonality=True, mcmc_samples=5, interval_width=0.8, uncertainty_samples=0, ) assert clf.parameters == { "changepoint_prior_scale": 0.05, "daily_seasonality": True, "date_index": None, "holidays_prior_scale": 10, "interval_width": 0.8, "mcmc_samples": 5, "seasonality_mode": "additive", "seasonality_prior_scale": 10, "uncertainty_samples": 0, "stan_backend": "CMDSTANPY", } def test_feature_importance(ts_data): X, y = ts_data clf = ProphetRegressor(uncertainty_samples=False, changepoint_prior_scale=2.0) clf.fit(X, y) clf.feature_importance == np.zeros(1) def test_get_params(ts_data): clf = ProphetRegressor() assert clf.get_params() == { "changepoint_prior_scale": 0.05, "date_index": None, "seasonality_prior_scale": 10, "holidays_prior_scale": 10, "seasonality_mode": "additive", "stan_backend": "CMDSTANPY", } def test_fit_predict_ts_with_X_index(ts_data): X, y = ts_data assert isinstance(X.index, pd.DatetimeIndex) p_clf = prophet.Prophet(uncertainty_samples=False, changepoint_prior_scale=2.0) prophet_df = ProphetRegressor.build_prophet_df(X=X, y=y, date_column="ds") p_clf.fit(prophet_df) y_pred_p = p_clf.predict(prophet_df)["yhat"] clf = ProphetRegressor(uncertainty_samples=False, changepoint_prior_scale=2.0) clf.fit(X, y) y_pred = clf.predict(X) np.array_equal(y_pred_p.values, y_pred.values) def test_fit_predict_ts_with_y_index(ts_data): X, y = ts_data X = X.reset_index(drop=True) assert isinstance(y.index, pd.DatetimeIndex) p_clf = prophet.Prophet(uncertainty_samples=False, changepoint_prior_scale=2.0) prophet_df = ProphetRegressor.build_prophet_df(X=X, y=y, date_column="ds") p_clf.fit(prophet_df) y_pred_p = p_clf.predict(prophet_df)["yhat"] clf = ProphetRegressor(uncertainty_samples=False, changepoint_prior_scale=2.0) clf.fit(X, y) y_pred = clf.predict(X, y) np.array_equal(y_pred_p.values, y_pred.values) def
(ts_data): y = pd.Series( range(1, 32), name="dates", index=pd.date_range("2020-10-01", "2020-10-31") ) p_clf = prophet.Prophet(uncertainty_samples=False, changepoint_prior_scale=2.0) prophet_df = ProphetRegressor.build_prophet_df( X=pd.DataFrame(), y=y, date_column="ds" ) p_clf.fit(prophet_df) y_pred_p = p_clf.predict(prophet_df)["yhat"] clf = ProphetRegressor(uncertainty_samples=False, changepoint_prior_scale=2.0) clf.fit(X=None, y=y) y_pred = clf.predict(X=None, y=y) np.array_equal(y_pred_p.values, y_pred.values) def test_fit_predict_date_col(ts_data): X = pd.DataFrame( { "features": range(100), "these_dates": pd.date_range("1/1/21", periods=100), "more_dates": pd.date_range("7/4/1987", periods=100), } ) y = pd.Series(np.random.randint(1, 5, 100), name="y") clf = ProphetRegressor( date_index="these_dates", uncertainty_samples=False, changepoint_prior_scale=2.0 ) clf.fit(X, y) y_pred = clf.predict(X) p_clf = prophet.Prophet(uncertainty_samples=False, changepoint_prior_scale=2.0) prophet_df = ProphetRegressor.build_prophet_df(X=X, y=y, date_column="these_dates") p_clf.fit(prophet_df) y_pred_p = p_clf.predict(prophet_df)["yhat"] np.array_equal(y_pred_p.values, y_pred.values) def test_fit_predict_no_date_col_or_index(ts_data): X, y = ts_data X = X.reset_index(drop=True) y = y.reset_index(drop=True) assert not isinstance(X.index, pd.DatetimeIndex) assert not isinstance(y.index, pd.DatetimeIndex) clf = ProphetRegressor() with pytest.raises( ValueError, match="Prophet estimator requires input data X to have a datetime column", ): clf.fit(X, y)
test_fit_predict_ts_no_X
my_data_mining.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Sep 26 17:33:03 2021 @author: ubuntu204 """ import numpy as np from scipy import stats import statsmodels.stats.multitest as multitest import matplotlib.pyplot as plt import os import pandas as pd from pandas import Series,DataFrame # import seaborn as sns # import palettable from sklearn import datasets from tqdm import tqdm plt.rcParams['font.sans-serif']=['SimHei'] # plt.rcParams['axes.unicode_mnius']=False epsilon=1e-10 def volcano_mine(data1,data2,method='hs',flag_output_src=0,flag_plot=0): data1=data1+epsilon data2=data2+epsilon mdata1=data1.mean(axis=0) mdata2=data2.mean(axis=0) fold_change=(mdata2)/(mdata1) log2_fold_change=np.log2(fold_change) p_values=np.zeros_like(mdata1) for i in tqdm(range(len(p_values))): t,p=stats.ttest_ind(data1[:,i],data2[:,i])
log10_pvals_corrected=np.log10(pvals_corrected+epsilon)*(-1) return log2_fold_change,log10_pvals_corrected def plot_volume(log2_fold_change,log10_pvals_corrected,title=None,saved_name=None): npt=len(log2_fold_change) colors=list(['grey']*npt) idx_green=(log2_fold_change>=np.log2(1.2))&(log10_pvals_corrected>(-np.log10(0.05))) for i in range(len(idx_green)): if idx_green[i]: colors[i]='green' idx_red=(log2_fold_change<=-np.log2(1.2))&(log10_pvals_corrected>(-np.log10(0.05))) for i in range(len(idx_red)): if idx_red[i]: colors[i]='red' # colors[idx_red]='red' plt.figure() plt.style.use('seaborn-whitegrid') plt.scatter(log2_fold_change, log10_pvals_corrected, color=colors) plt.xlabel('Log2 Fold Change') plt.ylabel('-Log10 P-Value') if title: plt.title(title) if saved_name: plt.savefig(saved_name,bbox_inches='tight',dpi=300) return # def plot_heatmap(data,row_c=None,dpi=300,figsize=(8/2.54,16/2.54),saved_name=None): # # plt.figure(dpi=dpi) # data_show=data.copy() # # data_show=data.drop(['class'],axis=1) # if row_c: # row_colors=data['class'].map(row_c) # sns.clustermap(data=data_show,method='single',metric='euclidean', # figsize=figsize,row_cluster=False,col_cluster=False, # cmap='rainbow') # sns.set(font_scale=1.5) # if saved_name: # plt.savefig(saved_name,bbox_inches='tight',dpi=dpi) if __name__=='__main__': # data1=np.random.rand(5, 10) # data2=np.random.rand(5, 10) # data2[:,0]=data1[:,0]*2.5 # data2[:,1]=data1[:,1]*10 # data2[:,2]=data1[:,2]/2.5 # data2[:,3]=data1[:,3]/10 # logFC,logP=volcano_mine(data1, data2) # plot_volume(logFC,logP) iris=datasets.load_iris() x,y=iris.data,iris.target data=np.hstack((x,y.reshape(150,1))) pd_iris=pd.DataFrame(data,columns=['sepal length(cm)','sepal width(cm)','petal length(cm)','petal width(cm)','class']) row_c=dict(zip(pd_iris['class'].unique(),['green','yellow','pink'])) # plot_heatmap(pd_iris,row_c=row_c)
p_values[i]=p rejects,pvals_corrected,alphaSidak,alphaBonf=multitest.multipletests(p_values,method=method)
twitterBot.py
#!/usr/bin/python3 import tweepy import time, datetime consumer_key = 'REDACTED' consumer_secret = 'REDACTED' key = 'REDACTED' secret = 'REDACTED' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(key, secret) api = tweepy.API(auth) def
(hashtag, delay): while True: print(f"\n{datetime.datetime.now()}\n") for tweet in tweepy.Cursor(api.search, q=hashtag, rpp=200).items(200): try: tweet_id = dict(tweet._json)["id"] tweet_text = dict(tweet._json)["text"] print("id" + str(tweet_id)) print("text: " + str(tweet_text)) api.retweet(tweet_id) api.create_favorite(tweet_id) #store_last_seen(FILE_NAME, tweet_id) except tweepy.TweepError as error: print(error.reason) time.sleep(delay) twitter_bot("$FTM", 60)
twitter_bot
main.rs
mod get; mod utils; use async_std::task; use chrono::{Duration, NaiveDate, NaiveDateTime, NaiveTime, Weekday}; use get::get_html; use scraper::{Html, Selector}; use std::error::Error; use std::str::FromStr; use tide::{http::Mime, Request, Response, StatusCode}; use utils::{get_period_time, parse_list_uint, parse_weekday, to_ics}; use std::collections::HashMap; fn main() { task::block_on(async { let mut app = tide::new(); app.at("/").get(|_| async { let mut res = Response::new(StatusCode::Accepted); res.set_content_type(tide::http::mime::HTML); res.set_body(include_str!("index.html")); Ok(res) }); app.at("/ics/*").get(|req: Request<()>| async move { let info: String = req.url().path().replace("/ics/", ""); if info.find('_').is_some() { let vec = info.split('_').collect::<Vec<&str>>(); let content = process(&vec[0].to_uppercase(), &vec[1]).await; let content = to_ics(content.unwrap_or(Vec::new())); let mut res = Response::new(StatusCode::Accepted); res.set_content_type(Mime::from_str("text/calendar").unwrap()); res.set_body(content); Ok(res) } else { Ok("Example CT010101_Passwd".into()) } }); app.at("/json/*").get(|req: Request<()>| async move { let path = req.url().path().replace("/json/", ""); let (usr, pwd) = path.split_at(path.find('/').unwrap_or(0)); let pwd: String = pwd[1..].to_string(); let vec = process(&usr.to_uppercase(), &pwd).await.unwrap_or(Vec::new()); let doc = vec.iter() .map(|dat| dat.to_map()) .collect::<Vec<HashMap<&'static str, String>>>(); let mut res = Response::new(StatusCode::Accepted); res.set_content_type(Mime::from_str("application/json")?); res.set_body(tide::Body::from_json(&doc)?); Ok(res) }); let port = std::env::var("PORT").unwrap_or("8080".to_string()); app.listen(format!("0.0.0.0:{}", port)).await.unwrap(); }); } async fn process(usr: &str, pwd: &str) -> Result<Vec<Data>, Box<dyn Error + Send + Sync>> { let vec = parse_html(get_html(usr, pwd).await?)?; Ok(vec.iter() .map(|(cl, ts, ps)| Data::parse(cl, ts, ps)) .flatten() .collect()) } #[derive(Debug)] pub struct Data { class: String, time_begin: NaiveDateTime, time_end: NaiveDateTime, place: String, } impl Data { pub fn to_map(&self) -> HashMap<&'static str, String>
pub fn class(&self) -> String { self.class.to_string() } pub fn place(&self) -> String { self.place.to_string() } pub fn begin(&self) -> NaiveDateTime { self.time_begin } pub fn end(&self) -> NaiveDateTime { self.time_end } fn parse(class: &str, times: &str, places: &str) -> Vec<Data> { let mut default = String::new(); let mut map = HashMap::new(); if places.find("(").is_some() { places.split("(") .skip(1) .map(|s| s .split(")") .map(|s| s.trim()) .collect::<Vec<&str>>() ).map(|vec| (vec.get(0).unwrap_or(&"1").clone(), vec.get(1).unwrap_or(&"N/A").clone()) ).map(|(i, p)| (parse_list_uint(i), p)) .map(|(vec, p)| vec .iter() .map(|i| map.insert(i.clone() as usize, p.to_string())) .all(|_| true) ).all(|_| true); } else { default = places.to_string(); } times .split("Từ ") .skip(1) .enumerate() .map(|(i, s)| s.replace(&format!("({})", i + 1), "")) .map(|s| { s.split(':') .map(|s| s.trim().to_string()) .collect::<Vec<String>>() }) .map(|vec| (vec[0].clone(), vec[1].clone())) .map(|(r, o)| (Data::parse_range(&r), Data::parse_wd_period(&o))) .map(|(r, d)| Data::merge_date_time(r, d)) .enumerate() .map(|(i, vec)| { vec.iter() .map(|(b, e)| Data { class: class.to_string(), time_begin: *b, time_end: *e, place: map.get(&(i+1)).unwrap_or(&default).clone(), }) .collect::<Vec<Data>>() }) .flatten() .collect() } fn merge_date_time( range: (NaiveDate, NaiveDate), time: Vec<(Weekday, (NaiveTime, NaiveTime))>, ) -> Vec<(NaiveDateTime, NaiveDateTime)> { time.iter() .map(|(wd, (bt, et))| { let mut vec = Vec::new(); let mut date = range.0 + Duration::days(wd.num_days_from_monday() as i64); while date < range.1 { vec.push((date.and_time(*bt), date.and_time(*et))); date += Duration::days(7); } vec }) .flatten() .collect() } fn parse_wd_period(all: &str) -> Vec<(Weekday, (NaiveTime, NaiveTime))> { fn get_ps_str_time(ps: &str) -> (NaiveTime, NaiveTime) { let vec = parse_list_uint(ps); let b = vec[0]; let e = vec.last().unwrap(); (get_period_time(b).0, get_period_time(*e).1) } all.trim() .split("Thứ") .skip(1) .map(|s| s.split("tiết").map(|s| s.trim()).collect::<Vec<&str>>()) .map(|vec| (vec[0], vec[1])) .map(|(wd, ps)| (parse_weekday(wd), get_ps_str_time(ps))) .collect() } fn parse_range(range: &str) -> (NaiveDate, NaiveDate) { let vec = range .split("đến") .map(|s| s.trim()) .map(|s| Data::parse_date(s)) .collect::<Vec<NaiveDate>>(); (vec[0], vec[1]) } fn parse_date(s: &str) -> NaiveDate { let dmy = parse_list_uint(s); NaiveDate::from_ymd(dmy[2] as i32, dmy[1], dmy[0]) } } fn parse_html(doc: String) -> Result<Vec<(String, String, String)>, Box<dyn Error + Send + Sync>> { let all = Html::parse_document(&doc); let select = Selector::parse(r#"tr[class="cssListItem"]"#).unwrap(); let select_alt = Selector::parse(r#"tr[class="cssListAlternativeItem"]"#).unwrap(); let body = all.select(&select).chain(all.select(&select_alt)); let each_col = Selector::parse("td").unwrap(); fn to_string<'a, T: Iterator<Item = R> + 'a, R: AsRef<str>>(iter: T) -> String { let mut ret = String::new(); let _ = iter .map(|s| ret.push_str(s.as_ref().trim())) .collect::<Vec<()>>(); ret } Ok(body .map(|n| { let vec = n .select(&each_col) .map(|e| to_string(e.text())) .collect::<Vec<String>>(); (vec[1].clone(), vec[3].clone(), vec[4].clone()) }) .collect()) }
{ let mut map = HashMap::new(); map.insert("title", format!("{}\n{}", self.class, self.place)); map.insert("start", utils::to_utc(self.time_begin).to_rfc3339()); map.insert("end", utils::to_utc(self.time_end).to_rfc3339()); map }
html.py
from typing import Any, Mapping, Sequence from urllib.parse import unquote_plus import bleach from importo.fields.base import Field from importo.utils.html import tidy_html class HTMLField(Field): allowed_tags = [ "a", "abbr", "acronym", "b", "bdi", "blockquote", "cite", "code", "dd", "dl", "dt", "em", "h2", "h3", "h4", "h5", "i", "li", "ol", "p", "small", "span", "strong", "ul", ] allowed_attrs = { "a": ["class", "href", "target", "title"], "abbr": ["title"], "acronym": ["title"], "cite": ["dir", "lang", "title"], "span": ["dir", "class", "lang", "title"], "h2": ["dir", "class", "lang", "title"], "h3": ["dir", "class", "lang", "title"], "h4": ["dir", "class", "lang", "title"], "h5": ["dir", "class", "lang", "title"], } def __init__( self, *args, allowed_tags: Sequence[str] = None, allowed_attrs: Mapping[str, str] = None, remove_empty_paragraphs: bool = True, remove_excess_whitespace: bool = True, remove_linebreaks: bool = False, **kwargs, ): if allowed_tags is not None: self.allowed_tags = allowed_tags if allowed_attrs is not None: self.allowed_attrs = allowed_attrs self.remove_empty_paragraphs = remove_empty_paragraphs self.remove_excess_whitespace = remove_excess_whitespace self.remove_linebreaks = remove_linebreaks super().__init__(*args, **kwargs) def to_python(self, value: Any) -> str:
value = unquote_plus(str(value)) # TODO: Add some way for the field to highlight/log when HTML is stripped value = bleach.clean( value, tags=self.allowed_tags, attributes=self.allowed_attrs, strip=True ) return tidy_html( value, remove_empty_paragraphs=self.remove_empty_paragraphs, remove_excess_whitespace=self.remove_excess_whitespace, remove_linebreaks=self.remove_linebreaks, )
bytes.go
package json import ( "encoding/json" "github.com/mono83/cfg" "io" "io/ioutil" ) // NewReaderSource reads all bytes from source reader and runs NewBytesSource // creating configurer from JSON bytes func NewReaderSource(source io.Reader) (cfg.Configurer, error)
// NewStringSource converts source to []byte and runs NewBytesSource // creating configurer from JSON bytes func NewStringSource(source string) (cfg.Configurer, error) { return NewBytesSource([]byte(source)) } // NewBytesSource creates and returns JSON configurer, that uses // provided bytes as source data func NewBytesSource(source []byte) (cfg.Configurer, error) { var t map[string]json.RawMessage err := json.Unmarshal(source, &t) if err != nil { return nil, err } return bytesSourceConfigurer(t), nil } type bytesSourceConfigurer map[string]json.RawMessage func (b bytesSourceConfigurer) Has(key string) bool { _, ok := b[key] return ok } func (b bytesSourceConfigurer) UnmarshalKey(key string, target interface{}) error { v, ok := b[key] if !ok { return cfg.ErrKeyMissing{Key: key} } return json.Unmarshal(v, target) } func (b bytesSourceConfigurer) KeyFunc(key string) func(interface{}) error { return cfg.ExtractUnmarshalFunc(b, key) }
{ bts, err := ioutil.ReadAll(source) if err != nil { return nil, err } return NewBytesSource(bts) }
curve25519.rs
extern crate rand; extern crate hacl_star; use hacl_star::curve25519; const SCALAR1: [u8; 32] = [0xa5, 0x46, 0xe3, 0x6b, 0xf0, 0x52, 0x7c, 0x9d, 0x3b, 0x16, 0x15, 0x4b, 0x82, 0x46, 0x5e, 0xdd, 0x62, 0x14, 0x4c, 0x0a, 0xc1, 0xfc, 0x5a, 0x18, 0x50, 0x6a, 0x22, 0x44, 0xba, 0x44, 0x9a, 0xc4]; const SCALAR2: [u8; 32] = [0x4b, 0x66, 0xe9, 0xd4, 0xd1, 0xb4, 0x67, 0x3c, 0x5a, 0xd2, 0x26, 0x91, 0x95, 0x7d, 0x6a, 0xf5, 0xc1, 0x1b, 0x64, 0x21, 0xe0, 0xea, 0x01, 0xd4, 0x2c, 0xa4, 0x16, 0x9e, 0x79, 0x18, 0xba, 0x0d]; const INPUT1: [u8; 32] = [0xe6, 0xdb, 0x68, 0x67, 0x58, 0x30, 0x30, 0xdb, 0x35, 0x94, 0xc1, 0xa4, 0x24, 0xb1, 0x5f, 0x7c, 0x72, 0x66, 0x24, 0xec, 0x26, 0xb3, 0x35, 0x3b, 0x10, 0xa9, 0x03, 0xa6, 0xd0, 0xab, 0x1c, 0x4c]; const INPUT2: [u8; 32] = [0xe5, 0x21, 0x0f, 0x12, 0x78, 0x68, 0x11, 0xd3, 0xf4, 0xb7, 0x95, 0x9d, 0x05, 0x38, 0xae, 0x2c, 0x31, 0xdb, 0xe7, 0x10, 0x6f, 0xc0, 0x3c, 0x3e, 0xfc, 0x4c, 0xd5, 0x49, 0xc7, 0x15, 0xa4, 0x93]; const EXPECTED1: [u8; 32] = [0xc3, 0xda, 0x55, 0x37, 0x9d, 0xe9, 0xc6, 0x90, 0x8e, 0x94, 0xea, 0x4d, 0xf2, 0x8d, 0x08, 0x4f, 0x32, 0xec, 0xcf, 0x03, 0x49, 0x1c, 0x71, 0xf7, 0x54, 0xb4, 0x07, 0x55, 0x77, 0xa2, 0x85, 0x52]; const EXPECTED2: [u8; 32] = [0x95, 0xcb, 0xde, 0x94, 0x76, 0xe8, 0x90, 0x7d, 0x7a, 0xad, 0xe4, 0x5c, 0xb4, 0xb8, 0x73, 0xf8, 0x8b, 0x59, 0x5a, 0x68, 0x79, 0x9f, 0xa1, 0x52, 0xe6, 0xf8, 0xf7, 0x64, 0x7a, 0xac, 0x79, 0x57]; #[test] fn
() { let mut output = [0; 32]; curve25519::scalarmult(&mut output, &SCALAR1, &INPUT1); assert_eq!(output, EXPECTED1); curve25519::scalarmult(&mut output, &SCALAR2, &INPUT2); assert_eq!(output, EXPECTED2); } #[test] fn test_curve25519_kx() { use rand::rngs::OsRng; use curve25519::*; let (mut out1, mut out2) = ([0; 32], [0; 32]); let (sk1, pk1) = keypair(OsRng::new().unwrap()); let (sk2, pk2) = keypair(OsRng::new().unwrap()); sk1.exchange(&pk2, &mut out1); sk2.exchange(&pk1, &mut out2); assert_eq!(out1, out2); }
test_curve25519
return_http_response_action.go
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Web Application Firewall (WAF) API // // API for the Web Application Firewall service. // Use this API to manage regional Web App Firewalls and corresponding policies for protecting HTTP services. // package waf import ( "encoding/json" "github.com/oracle/oci-go-sdk/v54/common" ) // ReturnHttpResponseAction An object that represents an action which returns a defined HTTP response. type ReturnHttpResponseAction struct { // Action name. Can be used to reference the action. Name *string `mandatory:"true" json:"name"` // Response code. // The following response codes are valid values for this property: // * 2xx // 200 OK // 201 Created // 202 Accepted // 206 Partial Content // * 3xx // 300 Multiple Choices // 301 Moved Permanently // 302 Found // 303 See Other // 307 Temporary Redirect // * 4xx // 400 Bad Request // 401 Unauthorized // 403 Forbidden // 404 Not Found // 405 Method Not Allowed // 408 Request Timeout // 409 Conflict // 411 Length Required // 412 Precondition Failed // 413 Payload Too Large // 414 URI Too Long // 415 Unsupported Media Type // 416 Range Not Satisfiable // 422 Unprocessable Entity // 494 Request Header Too Large // 495 Cert Error // 496 No Cert // 497 HTTP to HTTPS // * 5xx // 500 Internal Server Error // 501 Not Implemented // 502 Bad Gateway // 503 Service Unavailable // 504 Gateway Timeout // 507 Insufficient Storage // Example: `200` Code *int `mandatory:"true" json:"code"` // Adds headers defined in this array for HTTP response. // Hop-by-hop headers are not allowed to be set: // * Connection // * Keep-Alive // * Proxy-Authenticate // * Proxy-Authorization // * TE // * Trailer // * Transfer-Encoding // * Upgrade Headers []ResponseHeader `mandatory:"false" json:"headers"` Body HttpResponseBody `mandatory:"false" json:"body"` } //GetName returns Name func (m ReturnHttpResponseAction) GetName() *string { return m.Name } func (m ReturnHttpResponseAction) String() string { return common.PointerString(m) } // MarshalJSON marshals to json representation func (m ReturnHttpResponseAction) MarshalJSON() (buff []byte, e error) { type MarshalTypeReturnHttpResponseAction ReturnHttpResponseAction s := struct { DiscriminatorParam string `json:"type"` MarshalTypeReturnHttpResponseAction }{ "RETURN_HTTP_RESPONSE", (MarshalTypeReturnHttpResponseAction)(m), } return json.Marshal(&s) } // UnmarshalJSON unmarshals from json func (m *ReturnHttpResponseAction) UnmarshalJSON(data []byte) (e error) { model := struct { Headers []ResponseHeader `json:"headers"` Body httpresponsebody `json:"body"`
}{} e = json.Unmarshal(data, &model) if e != nil { return } var nn interface{} m.Headers = make([]ResponseHeader, len(model.Headers)) for i, n := range model.Headers { m.Headers[i] = n } nn, e = model.Body.UnmarshalPolymorphicJSON(model.Body.JsonData) if e != nil { return } if nn != nil { m.Body = nn.(HttpResponseBody) } else { m.Body = nil } m.Name = model.Name m.Code = model.Code return }
Name *string `json:"name"` Code *int `json:"code"`
MaterialButtonPrimary1.js
import React, {Component} from "react"; import {StyleSheet, TouchableOpacity, Text} from "react-native"; import configs from "../../config"; export default class
extends Component { render() { return ( <TouchableOpacity style={[styles.root, this.props.style]} onPress={this.props.handleSubmit}> <Text style={styles.caption}>{this.props.title}</Text> </TouchableOpacity> ); } } const styles = StyleSheet.create({ root: { backgroundColor: configs.theme, flexDirection: "row", alignItems: "center", justifyContent: "center", paddingRight: 16, paddingLeft: 16, elevation: 2, minWidth: 88, borderRadius: 100, borderColor: "#000000", borderWidth: 0, shadowOffset: { height: 1, width: 0 }, shadowColor: "#000", shadowOpacity: 0.35, shadowRadius: 5 }, caption: { color: "#fff", fontSize: 14, fontWeight: "200" } });
MaterialButtonPrimary1
resolute.js
"use strict"; var helpers = require("../../helpers/helpers"); exports["America/Resolute"] = { "1947" : helpers.makeTestYear("America/Resolute", [ ["1947-08-30T23:59:59+00:00", "23:59:59", "zzz", 0], ["1947-08-31T00:00:00+00:00", "18:00:00", "CST", 360] ]), "1965" : helpers.makeTestYear("America/Resolute", [ ["1965-04-25T05:59:59+00:00", "23:59:59", "CST", 360], ["1965-04-25T06:00:00+00:00", "02:00:00", "CDDT", 240], ["1965-10-31T05:59:59+00:00", "01:59:59", "CDDT", 240], ["1965-10-31T06:00:00+00:00", "00:00:00", "CST", 360] ]), "1980" : helpers.makeTestYear("America/Resolute", [ ["1980-04-27T07:59:59+00:00", "01:59:59", "CST", 360], ["1980-04-27T08:00:00+00:00", "03:00:00", "CDT", 300], ["1980-10-26T06:59:59+00:00", "01:59:59", "CDT", 300], ["1980-10-26T07:00:00+00:00", "01:00:00", "CST", 360]
"1981" : helpers.makeTestYear("America/Resolute", [ ["1981-04-26T07:59:59+00:00", "01:59:59", "CST", 360], ["1981-04-26T08:00:00+00:00", "03:00:00", "CDT", 300], ["1981-10-25T06:59:59+00:00", "01:59:59", "CDT", 300], ["1981-10-25T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1982" : helpers.makeTestYear("America/Resolute", [ ["1982-04-25T07:59:59+00:00", "01:59:59", "CST", 360], ["1982-04-25T08:00:00+00:00", "03:00:00", "CDT", 300], ["1982-10-31T06:59:59+00:00", "01:59:59", "CDT", 300], ["1982-10-31T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1983" : helpers.makeTestYear("America/Resolute", [ ["1983-04-24T07:59:59+00:00", "01:59:59", "CST", 360], ["1983-04-24T08:00:00+00:00", "03:00:00", "CDT", 300], ["1983-10-30T06:59:59+00:00", "01:59:59", "CDT", 300], ["1983-10-30T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1984" : helpers.makeTestYear("America/Resolute", [ ["1984-04-29T07:59:59+00:00", "01:59:59", "CST", 360], ["1984-04-29T08:00:00+00:00", "03:00:00", "CDT", 300], ["1984-10-28T06:59:59+00:00", "01:59:59", "CDT", 300], ["1984-10-28T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1985" : helpers.makeTestYear("America/Resolute", [ ["1985-04-28T07:59:59+00:00", "01:59:59", "CST", 360], ["1985-04-28T08:00:00+00:00", "03:00:00", "CDT", 300], ["1985-10-27T06:59:59+00:00", "01:59:59", "CDT", 300], ["1985-10-27T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1986" : helpers.makeTestYear("America/Resolute", [ ["1986-04-27T07:59:59+00:00", "01:59:59", "CST", 360], ["1986-04-27T08:00:00+00:00", "03:00:00", "CDT", 300], ["1986-10-26T06:59:59+00:00", "01:59:59", "CDT", 300], ["1986-10-26T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1987" : helpers.makeTestYear("America/Resolute", [ ["1987-04-05T07:59:59+00:00", "01:59:59", "CST", 360], ["1987-04-05T08:00:00+00:00", "03:00:00", "CDT", 300], ["1987-10-25T06:59:59+00:00", "01:59:59", "CDT", 300], ["1987-10-25T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1988" : helpers.makeTestYear("America/Resolute", [ ["1988-04-03T07:59:59+00:00", "01:59:59", "CST", 360], ["1988-04-03T08:00:00+00:00", "03:00:00", "CDT", 300], ["1988-10-30T06:59:59+00:00", "01:59:59", "CDT", 300], ["1988-10-30T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1989" : helpers.makeTestYear("America/Resolute", [ ["1989-04-02T07:59:59+00:00", "01:59:59", "CST", 360], ["1989-04-02T08:00:00+00:00", "03:00:00", "CDT", 300], ["1989-10-29T06:59:59+00:00", "01:59:59", "CDT", 300], ["1989-10-29T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1990" : helpers.makeTestYear("America/Resolute", [ ["1990-04-01T07:59:59+00:00", "01:59:59", "CST", 360], ["1990-04-01T08:00:00+00:00", "03:00:00", "CDT", 300], ["1990-10-28T06:59:59+00:00", "01:59:59", "CDT", 300], ["1990-10-28T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1991" : helpers.makeTestYear("America/Resolute", [ ["1991-04-07T07:59:59+00:00", "01:59:59", "CST", 360], ["1991-04-07T08:00:00+00:00", "03:00:00", "CDT", 300], ["1991-10-27T06:59:59+00:00", "01:59:59", "CDT", 300], ["1991-10-27T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1992" : helpers.makeTestYear("America/Resolute", [ ["1992-04-05T07:59:59+00:00", "01:59:59", "CST", 360], ["1992-04-05T08:00:00+00:00", "03:00:00", "CDT", 300], ["1992-10-25T06:59:59+00:00", "01:59:59", "CDT", 300], ["1992-10-25T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1993" : helpers.makeTestYear("America/Resolute", [ ["1993-04-04T07:59:59+00:00", "01:59:59", "CST", 360], ["1993-04-04T08:00:00+00:00", "03:00:00", "CDT", 300], ["1993-10-31T06:59:59+00:00", "01:59:59", "CDT", 300], ["1993-10-31T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1994" : helpers.makeTestYear("America/Resolute", [ ["1994-04-03T07:59:59+00:00", "01:59:59", "CST", 360], ["1994-04-03T08:00:00+00:00", "03:00:00", "CDT", 300], ["1994-10-30T06:59:59+00:00", "01:59:59", "CDT", 300], ["1994-10-30T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1995" : helpers.makeTestYear("America/Resolute", [ ["1995-04-02T07:59:59+00:00", "01:59:59", "CST", 360], ["1995-04-02T08:00:00+00:00", "03:00:00", "CDT", 300], ["1995-10-29T06:59:59+00:00", "01:59:59", "CDT", 300], ["1995-10-29T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1996" : helpers.makeTestYear("America/Resolute", [ ["1996-04-07T07:59:59+00:00", "01:59:59", "CST", 360], ["1996-04-07T08:00:00+00:00", "03:00:00", "CDT", 300], ["1996-10-27T06:59:59+00:00", "01:59:59", "CDT", 300], ["1996-10-27T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1997" : helpers.makeTestYear("America/Resolute", [ ["1997-04-06T07:59:59+00:00", "01:59:59", "CST", 360], ["1997-04-06T08:00:00+00:00", "03:00:00", "CDT", 300], ["1997-10-26T06:59:59+00:00", "01:59:59", "CDT", 300], ["1997-10-26T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1998" : helpers.makeTestYear("America/Resolute", [ ["1998-04-05T07:59:59+00:00", "01:59:59", "CST", 360], ["1998-04-05T08:00:00+00:00", "03:00:00", "CDT", 300], ["1998-10-25T06:59:59+00:00", "01:59:59", "CDT", 300], ["1998-10-25T07:00:00+00:00", "01:00:00", "CST", 360] ]), "1999" : helpers.makeTestYear("America/Resolute", [ ["1999-04-04T07:59:59+00:00", "01:59:59", "CST", 360], ["1999-04-04T08:00:00+00:00", "03:00:00", "CDT", 300], ["1999-10-31T06:59:59+00:00", "01:59:59", "CDT", 300], ["1999-10-31T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2000" : helpers.makeTestYear("America/Resolute", [ ["2000-04-02T07:59:59+00:00", "01:59:59", "CST", 360], ["2000-04-02T08:00:00+00:00", "03:00:00", "CDT", 300], ["2000-10-29T06:59:59+00:00", "01:59:59", "CDT", 300], ["2000-10-29T07:00:00+00:00", "02:00:00", "EST", 300] ]), "2001" : helpers.makeTestYear("America/Resolute", [ ["2001-04-01T07:59:59+00:00", "02:59:59", "EST", 300], ["2001-04-01T08:00:00+00:00", "03:00:00", "CDT", 300], ["2001-10-28T06:59:59+00:00", "01:59:59", "CDT", 300], ["2001-10-28T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2002" : helpers.makeTestYear("America/Resolute", [ ["2002-04-07T07:59:59+00:00", "01:59:59", "CST", 360], ["2002-04-07T08:00:00+00:00", "03:00:00", "CDT", 300], ["2002-10-27T06:59:59+00:00", "01:59:59", "CDT", 300], ["2002-10-27T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2003" : helpers.makeTestYear("America/Resolute", [ ["2003-04-06T07:59:59+00:00", "01:59:59", "CST", 360], ["2003-04-06T08:00:00+00:00", "03:00:00", "CDT", 300], ["2003-10-26T06:59:59+00:00", "01:59:59", "CDT", 300], ["2003-10-26T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2004" : helpers.makeTestYear("America/Resolute", [ ["2004-04-04T07:59:59+00:00", "01:59:59", "CST", 360], ["2004-04-04T08:00:00+00:00", "03:00:00", "CDT", 300], ["2004-10-31T06:59:59+00:00", "01:59:59", "CDT", 300], ["2004-10-31T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2005" : helpers.makeTestYear("America/Resolute", [ ["2005-04-03T07:59:59+00:00", "01:59:59", "CST", 360], ["2005-04-03T08:00:00+00:00", "03:00:00", "CDT", 300], ["2005-10-30T06:59:59+00:00", "01:59:59", "CDT", 300], ["2005-10-30T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2006" : helpers.makeTestYear("America/Resolute", [ ["2006-04-02T07:59:59+00:00", "01:59:59", "CST", 360], ["2006-04-02T08:00:00+00:00", "03:00:00", "CDT", 300], ["2006-10-29T06:59:59+00:00", "01:59:59", "CDT", 300], ["2006-10-29T07:00:00+00:00", "02:00:00", "EST", 300] ]), "2007" : helpers.makeTestYear("America/Resolute", [ ["2007-03-11T07:59:59+00:00", "02:59:59", "EST", 300], ["2007-03-11T08:00:00+00:00", "03:00:00", "CDT", 300], ["2007-11-04T06:59:59+00:00", "01:59:59", "CDT", 300], ["2007-11-04T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2008" : helpers.makeTestYear("America/Resolute", [ ["2008-03-09T07:59:59+00:00", "01:59:59", "CST", 360], ["2008-03-09T08:00:00+00:00", "03:00:00", "CDT", 300], ["2008-11-02T06:59:59+00:00", "01:59:59", "CDT", 300], ["2008-11-02T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2009" : helpers.makeTestYear("America/Resolute", [ ["2009-03-08T07:59:59+00:00", "01:59:59", "CST", 360], ["2009-03-08T08:00:00+00:00", "03:00:00", "CDT", 300], ["2009-11-01T06:59:59+00:00", "01:59:59", "CDT", 300], ["2009-11-01T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2010" : helpers.makeTestYear("America/Resolute", [ ["2010-03-14T07:59:59+00:00", "01:59:59", "CST", 360], ["2010-03-14T08:00:00+00:00", "03:00:00", "CDT", 300], ["2010-11-07T06:59:59+00:00", "01:59:59", "CDT", 300], ["2010-11-07T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2011" : helpers.makeTestYear("America/Resolute", [ ["2011-03-13T07:59:59+00:00", "01:59:59", "CST", 360], ["2011-03-13T08:00:00+00:00", "03:00:00", "CDT", 300], ["2011-11-06T06:59:59+00:00", "01:59:59", "CDT", 300], ["2011-11-06T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2012" : helpers.makeTestYear("America/Resolute", [ ["2012-03-11T07:59:59+00:00", "01:59:59", "CST", 360], ["2012-03-11T08:00:00+00:00", "03:00:00", "CDT", 300], ["2012-11-04T06:59:59+00:00", "01:59:59", "CDT", 300], ["2012-11-04T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2013" : helpers.makeTestYear("America/Resolute", [ ["2013-03-10T07:59:59+00:00", "01:59:59", "CST", 360], ["2013-03-10T08:00:00+00:00", "03:00:00", "CDT", 300], ["2013-11-03T06:59:59+00:00", "01:59:59", "CDT", 300], ["2013-11-03T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2014" : helpers.makeTestYear("America/Resolute", [ ["2014-03-09T07:59:59+00:00", "01:59:59", "CST", 360], ["2014-03-09T08:00:00+00:00", "03:00:00", "CDT", 300], ["2014-11-02T06:59:59+00:00", "01:59:59", "CDT", 300], ["2014-11-02T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2015" : helpers.makeTestYear("America/Resolute", [ ["2015-03-08T07:59:59+00:00", "01:59:59", "CST", 360], ["2015-03-08T08:00:00+00:00", "03:00:00", "CDT", 300], ["2015-11-01T06:59:59+00:00", "01:59:59", "CDT", 300], ["2015-11-01T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2016" : helpers.makeTestYear("America/Resolute", [ ["2016-03-13T07:59:59+00:00", "01:59:59", "CST", 360], ["2016-03-13T08:00:00+00:00", "03:00:00", "CDT", 300], ["2016-11-06T06:59:59+00:00", "01:59:59", "CDT", 300], ["2016-11-06T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2017" : helpers.makeTestYear("America/Resolute", [ ["2017-03-12T07:59:59+00:00", "01:59:59", "CST", 360], ["2017-03-12T08:00:00+00:00", "03:00:00", "CDT", 300], ["2017-11-05T06:59:59+00:00", "01:59:59", "CDT", 300], ["2017-11-05T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2018" : helpers.makeTestYear("America/Resolute", [ ["2018-03-11T07:59:59+00:00", "01:59:59", "CST", 360], ["2018-03-11T08:00:00+00:00", "03:00:00", "CDT", 300], ["2018-11-04T06:59:59+00:00", "01:59:59", "CDT", 300], ["2018-11-04T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2019" : helpers.makeTestYear("America/Resolute", [ ["2019-03-10T07:59:59+00:00", "01:59:59", "CST", 360], ["2019-03-10T08:00:00+00:00", "03:00:00", "CDT", 300], ["2019-11-03T06:59:59+00:00", "01:59:59", "CDT", 300], ["2019-11-03T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2020" : helpers.makeTestYear("America/Resolute", [ ["2020-03-08T07:59:59+00:00", "01:59:59", "CST", 360], ["2020-03-08T08:00:00+00:00", "03:00:00", "CDT", 300], ["2020-11-01T06:59:59+00:00", "01:59:59", "CDT", 300], ["2020-11-01T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2021" : helpers.makeTestYear("America/Resolute", [ ["2021-03-14T07:59:59+00:00", "01:59:59", "CST", 360], ["2021-03-14T08:00:00+00:00", "03:00:00", "CDT", 300], ["2021-11-07T06:59:59+00:00", "01:59:59", "CDT", 300], ["2021-11-07T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2022" : helpers.makeTestYear("America/Resolute", [ ["2022-03-13T07:59:59+00:00", "01:59:59", "CST", 360], ["2022-03-13T08:00:00+00:00", "03:00:00", "CDT", 300], ["2022-11-06T06:59:59+00:00", "01:59:59", "CDT", 300], ["2022-11-06T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2023" : helpers.makeTestYear("America/Resolute", [ ["2023-03-12T07:59:59+00:00", "01:59:59", "CST", 360], ["2023-03-12T08:00:00+00:00", "03:00:00", "CDT", 300], ["2023-11-05T06:59:59+00:00", "01:59:59", "CDT", 300], ["2023-11-05T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2024" : helpers.makeTestYear("America/Resolute", [ ["2024-03-10T07:59:59+00:00", "01:59:59", "CST", 360], ["2024-03-10T08:00:00+00:00", "03:00:00", "CDT", 300], ["2024-11-03T06:59:59+00:00", "01:59:59", "CDT", 300], ["2024-11-03T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2025" : helpers.makeTestYear("America/Resolute", [ ["2025-03-09T07:59:59+00:00", "01:59:59", "CST", 360], ["2025-03-09T08:00:00+00:00", "03:00:00", "CDT", 300], ["2025-11-02T06:59:59+00:00", "01:59:59", "CDT", 300], ["2025-11-02T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2026" : helpers.makeTestYear("America/Resolute", [ ["2026-03-08T07:59:59+00:00", "01:59:59", "CST", 360], ["2026-03-08T08:00:00+00:00", "03:00:00", "CDT", 300], ["2026-11-01T06:59:59+00:00", "01:59:59", "CDT", 300], ["2026-11-01T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2027" : helpers.makeTestYear("America/Resolute", [ ["2027-03-14T07:59:59+00:00", "01:59:59", "CST", 360], ["2027-03-14T08:00:00+00:00", "03:00:00", "CDT", 300], ["2027-11-07T06:59:59+00:00", "01:59:59", "CDT", 300], ["2027-11-07T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2028" : helpers.makeTestYear("America/Resolute", [ ["2028-03-12T07:59:59+00:00", "01:59:59", "CST", 360], ["2028-03-12T08:00:00+00:00", "03:00:00", "CDT", 300], ["2028-11-05T06:59:59+00:00", "01:59:59", "CDT", 300], ["2028-11-05T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2029" : helpers.makeTestYear("America/Resolute", [ ["2029-03-11T07:59:59+00:00", "01:59:59", "CST", 360], ["2029-03-11T08:00:00+00:00", "03:00:00", "CDT", 300], ["2029-11-04T06:59:59+00:00", "01:59:59", "CDT", 300], ["2029-11-04T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2030" : helpers.makeTestYear("America/Resolute", [ ["2030-03-10T07:59:59+00:00", "01:59:59", "CST", 360], ["2030-03-10T08:00:00+00:00", "03:00:00", "CDT", 300], ["2030-11-03T06:59:59+00:00", "01:59:59", "CDT", 300], ["2030-11-03T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2031" : helpers.makeTestYear("America/Resolute", [ ["2031-03-09T07:59:59+00:00", "01:59:59", "CST", 360], ["2031-03-09T08:00:00+00:00", "03:00:00", "CDT", 300], ["2031-11-02T06:59:59+00:00", "01:59:59", "CDT", 300], ["2031-11-02T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2032" : helpers.makeTestYear("America/Resolute", [ ["2032-03-14T07:59:59+00:00", "01:59:59", "CST", 360], ["2032-03-14T08:00:00+00:00", "03:00:00", "CDT", 300], ["2032-11-07T06:59:59+00:00", "01:59:59", "CDT", 300], ["2032-11-07T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2033" : helpers.makeTestYear("America/Resolute", [ ["2033-03-13T07:59:59+00:00", "01:59:59", "CST", 360], ["2033-03-13T08:00:00+00:00", "03:00:00", "CDT", 300], ["2033-11-06T06:59:59+00:00", "01:59:59", "CDT", 300], ["2033-11-06T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2034" : helpers.makeTestYear("America/Resolute", [ ["2034-03-12T07:59:59+00:00", "01:59:59", "CST", 360], ["2034-03-12T08:00:00+00:00", "03:00:00", "CDT", 300], ["2034-11-05T06:59:59+00:00", "01:59:59", "CDT", 300], ["2034-11-05T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2035" : helpers.makeTestYear("America/Resolute", [ ["2035-03-11T07:59:59+00:00", "01:59:59", "CST", 360], ["2035-03-11T08:00:00+00:00", "03:00:00", "CDT", 300], ["2035-11-04T06:59:59+00:00", "01:59:59", "CDT", 300], ["2035-11-04T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2036" : helpers.makeTestYear("America/Resolute", [ ["2036-03-09T07:59:59+00:00", "01:59:59", "CST", 360], ["2036-03-09T08:00:00+00:00", "03:00:00", "CDT", 300], ["2036-11-02T06:59:59+00:00", "01:59:59", "CDT", 300], ["2036-11-02T07:00:00+00:00", "01:00:00", "CST", 360] ]), "2037" : helpers.makeTestYear("America/Resolute", [ ["2037-03-08T07:59:59+00:00", "01:59:59", "CST", 360], ["2037-03-08T08:00:00+00:00", "03:00:00", "CDT", 300], ["2037-11-01T06:59:59+00:00", "01:59:59", "CDT", 300], ["2037-11-01T07:00:00+00:00", "01:00:00", "CST", 360] ]) };
]),
index.js
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an
*/ export { FilterManagerProvider } from './filter_manager';
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License.
policy.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Categorical class Policy(nn.Module): def __init__(self, s_size=4, h_size=8, a_size=2): super(Policy, self).__init__() self.fc1 = nn.Linear(s_size, h_size) self.fc2 = nn.Linear(h_size, a_size) def forward(self, x): x = F.selu(self.fc1(x)) x = self.fc2(x) return F.softmax(x, dim=1) def act(self, state, device):
state = torch.from_numpy(state).float().unsqueeze(0).to(device) probs = self.forward(state).cpu() # >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ])) # >>> m.sample() # equal probability of 0, 1, 2, 3 m = Categorical(probs) action = m.sample() return action.item(), m.log_prob(action)
loader.py
# -*- coding: utf-8 -*- """ The Salt loader is the core to Salt's plugin system, the loader scans directories for python loadable code and organizes the code into the plugin interfaces used by Salt. """ import os import re import sys import time import yaml import logging import inspect import tempfile import functools import threading import traceback import types from zipimport import zipimporter import hubblestack.config import hubblestack.syspaths import hubblestack.utils.args import hubblestack.utils.context import hubblestack.utils.data import hubblestack.utils.dictupdate import hubblestack.utils.files import hubblestack.utils.lazy import hubblestack.utils.odict import hubblestack.utils.platform import hubblestack.utils.versions from hubblestack.exceptions import LoaderError from hubblestack.template import check_render_pipe_str from hubblestack.utils.decorators import Depends import hubblestack.syspaths import importlib.machinery import importlib.util import pkg_resources try: from collections.abc import MutableMapping except ImportError: from collections import MutableMapping log = logging.getLogger(__name__) HUBBLE_BASE_PATH = os.path.abspath(hubblestack.syspaths.INSTALL_DIR) LOADED_BASE_NAME = "hubble.loaded" MODULE_KIND_SOURCE = 1 MODULE_KIND_COMPILED = 2 MODULE_KIND_EXTENSION = 3 MODULE_KIND_PKG_DIRECTORY = 5 SUFFIXES = [] for suffix in importlib.machinery.EXTENSION_SUFFIXES: SUFFIXES.append((suffix, "rb", MODULE_KIND_EXTENSION)) for suffix in importlib.machinery.SOURCE_SUFFIXES: SUFFIXES.append((suffix, "rb", MODULE_KIND_SOURCE)) for suffix in importlib.machinery.BYTECODE_SUFFIXES: SUFFIXES.append((suffix, "rb", MODULE_KIND_COMPILED)) MODULE_KIND_MAP = { MODULE_KIND_SOURCE: importlib.machinery.SourceFileLoader, MODULE_KIND_COMPILED: importlib.machinery.SourcelessFileLoader, MODULE_KIND_EXTENSION: importlib.machinery.ExtensionFileLoader, } PY3_PRE_EXT = re.compile(r"\.cpython-{0}{1}(\.opt-[1-9])?".format(*sys.version_info[:2])) # Will be set to pyximport module at runtime if cython is enabled in config. pyximport = None # pylint: disable=invalid-name PRESERVABLE_OPTS = dict() def set_preservable_opts(opts): """ This is a scope hack designed to make sure any __opts__ we pass to the modules can survive recycling of the lazy loaders. To be sure, this is to protect an anti-pattern where the modules sometimes store data for reporting in __opts__ (why did we start doing this?). We call this from hubblestack.daemon.refresh_grains. """ oid = id(opts) if oid not in PRESERVABLE_OPTS: log.debug("setting %d to be preservable opts", oid) PRESERVABLE_OPTS[oid] = opts.copy() def get_preserved_opts(opts): """part of a scope hack, see: set_preservable_opts we call this from __prep_mod_opts to invoke the scope hack """ oid = id(opts) ret = PRESERVABLE_OPTS.get(oid) if ret: log.debug("preserved opts found (%d)", oid) return ret def _module_dirs( opts, ext_type, tag=None, int_type=None, ext_dirs=True, ext_type_dirs=None, base_path=None, explain=False, ): if tag is None: tag = ext_type # NOTE: this ordering is most authoritative last. if we find a grains # module in salt, we want to replace it with the grains module from hubble, # so hubble's path should come last. ext_types = os.path.join(opts["extension_modules"], ext_type) sys_types = os.path.join(base_path or HUBBLE_BASE_PATH, int_type or ext_type) hubblestack_type = "hubblestack_" + (int_type or ext_type) files_base_types = os.path.join(base_path or HUBBLE_BASE_PATH, "files", hubblestack_type) ext_type_types = [] if ext_dirs: if tag is not None and ext_type_dirs is None: ext_type_dirs = "{0}_dirs".format(tag) if ext_type_dirs in opts: ext_type_types.extend(opts[ext_type_dirs]) for entry_point in pkg_resources.iter_entry_points("hubble.loader", ext_type_dirs): try: loaded_entry_point = entry_point.load() for path in loaded_entry_point(): ext_type_types.append(path) except Exception as exc: log.error("Error getting module directories from %s: %s", _format_entrypoint_target(entry_point), exc) log.debug("Full backtrace for module directories error", exc_info=True) cli_module_dirs = [] # The dirs can be any module dir, or a in-tree _{ext_type} dir for _dir in opts.get("module_dirs", []): # Prepend to the list to match cli argument ordering maybe_dir = os.path.join(_dir, ext_type) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) continue maybe_dir = os.path.join(_dir, "_{0}".format(ext_type)) if os.path.isdir(maybe_dir): cli_module_dirs.insert(0, maybe_dir) as_tuple = (cli_module_dirs, ext_type_types, [files_base_types, ext_types, sys_types]) log.debug("_module_dirs() => %s", as_tuple) if explain: return as_tuple return cli_module_dirs + ext_type_types + [files_base_types, ext_types, sys_types] def modules( opts, context=None, utils=None, whitelist=None, loaded_base_name=None, static_modules=None, proxy=None, ): """ Load execution modules Returns a dictionary of execution modules appropriate for the current system by evaluating the __virtual__() function in each module. :param dict opts: The Salt options dictionary :param dict context: A Salt context that should be made present inside generated modules in __context__ :param dict utils: Utility functions which should be made available to Salt modules in __utils__. See `utils_dirs` in hubblestack.config for additional information about configuration. :param list whitelist: A list of modules which should be whitelisted. :param str loaded_base_name: A string marker for the loaded base name. .. code-block:: python import hubblestack.config import hubblestack.loader __opts__ = hubblestack.config.get_config('/etc/salt/minion') __grains__ = hubblestack.loader.grains(__opts__) __opts__['grains'] = __grains__ __utils__ = hubblestack.loader.utils(__opts__) __mods__ = hubblestack.loader.modules(__opts__, utils=__utils__) __mods__['test.ping']() """ # TODO Publish documentation for module whitelisting if not whitelist: whitelist = opts.get("whitelist_modules", None) ret = LazyLoader( _module_dirs(opts, "modules", "module"), opts, tag="module", pack={"__context__": context, "__utils__": utils, "__proxy__": proxy}, whitelist=whitelist, loaded_base_name=loaded_base_name, static_modules=static_modules, ) # this is the very definition of a circular ref... we added a destructor # to deal with this, although the newest pythons periodically detect # detached circular ref items during garbage collection. ret.pack["__mods__"] = ret return ret def returners(opts, functions, whitelist=None, context=None, proxy=None): """ Returns the returner modules """ return LazyLoader( _module_dirs(opts, "returners", "returner"), opts, tag="returner", whitelist=whitelist, pack={"__mods__": functions, "__context__": context, "__proxy__": proxy or {}}, ) def utils(opts, whitelist=None, context=None, proxy=None): """ Returns the utility modules """ return LazyLoader( _module_dirs(opts, "utils", ext_type_dirs="utils_dirs"), opts, tag="utils", whitelist=whitelist, pack={"__context__": context, "__proxy__": proxy or {}}, ) def fileserver(opts, backends): """ Returns the file server modules """ return LazyLoader( _module_dirs(opts, "fileserver"), opts, tag="fileserver", whitelist=backends, pack={"__utils__": utils(opts)} ) def grain_funcs(opts): """ Returns the grain functions .. code-block:: python import hubblestack.config import hubblestack.loader __opts__ = hubblestack.config.get_config('/etc/salt/minion') grainfuncs = hubblestack.loader.grain_funcs(__opts__) """ return LazyLoader( _module_dirs( opts, "grains", "grain", ext_type_dirs="grains_dirs", ), opts, tag="grains", ) def grains(opts, force_refresh=False): """ Return the functions for the dynamic grains and the values for the static grains. Since grains are computed early in the startup process, grains functions do not have __mods__ available. .. code-block:: python import hubblestack.config import hubblestack.loader __opts__ = hubblestack.config.get_config('/etc/hubble/hubble') __grains__ = hubblestack.loader.grains(__opts__) print __grains__['id'] """ # Need to re-import hubblestack.config, somehow it got lost when a minion is starting import hubblestack.config # if we have no grains, lets try loading from disk (TODO: move to decorator?) cfn = os.path.join(opts["cachedir"], "grains.cache.p") if opts.get("skip_grains", False): return {} grains_deep_merge = opts.get("grains_deep_merge", False) is True if "conf_file" in opts: pre_opts = {} pre_opts.update( hubblestack.config.load_config( opts["conf_file"], "HUBBLE_CONFIG", hubblestack.config.DEFAULT_OPTS["conf_file"] ) ) default_include = pre_opts.get("default_include", opts["default_include"]) include = pre_opts.get("include", []) pre_opts.update(hubblestack.config.include_config(default_include, opts["conf_file"], verbose=False)) pre_opts.update(hubblestack.config.include_config(include, opts["conf_file"], verbose=True)) if "grains" in pre_opts: opts["grains"] = pre_opts["grains"] else: opts["grains"] = {} else: opts["grains"] = {} grains_data = {} funcs = grain_funcs(opts) if force_refresh: # if we refresh, lets reload grain modules funcs.clear() # Run core grains for key in funcs: if not key.startswith("core."): continue log.trace("Loading %s grain", key) ret = funcs[key]() if not isinstance(ret, dict): continue if grains_deep_merge: hubblestack.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) # Run the rest of the grains for key in funcs: if key.startswith("core.") or key == "_errors": continue try: log.trace("Loading %s grain", key) parameters = hubblestack.utils.args.get_function_argspec(funcs[key]).args kwargs = {} if "grains" in parameters: kwargs["grains"] = grains_data ret = funcs[key](**kwargs) except Exception: log.critical( "Failed to load grains defined in grain file %s in " "function %s, error:\n", key, funcs[key], exc_info=True, ) continue if not isinstance(ret, dict): continue if grains_deep_merge: hubblestack.utils.dictupdate.update(grains_data, ret) else: grains_data.update(ret) grains_data.update(opts["grains"]) # Write cache if enabled if opts.get("grains_cache", False): with hubblestack.utils.files.set_umask(0o077): try: if hubblestack.utils.platform.is_windows(): # Late import import hubblestack.modules.cmdmod # Make sure cache file isn't read-only hubblestack.modules.cmdmod._run_quiet('attrib -R "{0}"'.format(cfn)) with hubblestack.utils.files.fopen(cfn, "w+b") as fp_: try: serial = hubblestack.payload.Serial(opts) serial.dump(grains_data, fp_) except TypeError as e: log.error("Failed to serialize grains cache: %s", e) raise # re-throw for cleanup except Exception as e: log.error("Unable to write to grains cache file %s: %s", cfn, e) # Based on the original exception, the file may or may not have been # created. If it was, we will remove it now, as the exception means # the serialized data is not to be trusted, no matter what the # exception is. if os.path.isfile(cfn): os.unlink(cfn) if grains_deep_merge: hubblestack.utils.dictupdate.update(grains_data, opts["grains"]) else: grains_data.update(opts["grains"]) return hubblestack.utils.data.decode(grains_data, preserve_tuples=True) def render(opts, functions): """ Returns the render modules """ pack = {"__mods__": functions, "__grains__": opts.get("grains", {})} ret = LazyLoader( _module_dirs( opts, "renderers", "render", ext_type_dirs="render_dirs", ), opts, tag="render", pack=pack, ) rend = FilterDictWrapper(ret, ".render") if not check_render_pipe_str(opts["renderer"], rend, opts["renderer_blacklist"], opts["renderer_whitelist"]): err = ( "The renderer {0} is unavailable, this error is often because " "the needed software is unavailable".format(opts["renderer"]) ) log.critical(err) raise LoaderError(err) return rend def _generate_module(name): if name in sys.modules: return code = "'''Salt loaded {0} parent module'''".format(name.split(".")[-1]) # ModuleType can't accept a unicode type on PY2 module = types.ModuleType(str(name)) # future lint: disable=blacklisted-function exec(code, module.__dict__) sys.modules[name] = module def _mod_type(module_path): if module_path.startswith(HUBBLE_BASE_PATH): return "int" return "ext" class LazyLoader(hubblestack.utils.lazy.LazyDict): """ A pseduo-dictionary which has a set of keys which are the name of the module and function, delimited by a dot. When the value of the key is accessed, the function is then loaded from disk and into memory. .. note:: Iterating over keys will cause all modules to be loaded. :param list module_dirs: A list of directories on disk to search for modules :param dict opts: The salt options dictionary. :param str tag: The tag for the type of module to load :param func mod_type_check: A function which can be used to verify files :param dict pack: A dictionary of function to be packed into modules as they are loaded :param list whitelist: A list of modules to whitelist :param bool virtual_enable: Whether or not to respect the __virtual__ function when loading modules. :param str virtual_funcs: The name of additional functions in the module to call to verify its functionality. If not true, the module will not load. :returns: A LazyLoader object which functions as a dictionary. Keys are 'module.function' and values are function references themselves which are loaded on-demand. # TODO: - move modules_max_memory into here - singletons (per tag) """ mod_dict_class = hubblestack.utils.odict.OrderedDict def __del__(self): # trying to use logging in here works for debugging, but later causes # problems at runtime during global destruction. # log.debug("clearing possible memory leaks by emptying pack, missing_modules and loaded_modules dicts") self.pack.clear() self.missing_modules.clear() self.loaded_modules.clear() def __init__( self, module_dirs, opts=None, tag="module", loaded_base_name=None, mod_type_check=None, pack=None, whitelist=None, virtual_enable=True, static_modules=None, funcname_filter=None, xlate_modnames=None, xlate_funcnames=None, proxy=None, virtual_funcs=None, ): # pylint: disable=W0231 """ In pack, if any of the values are None they will be replaced with an empty context-specific dict """ self.funcname_filter = funcname_filter self.xlate_modnames = xlate_modnames self.xlate_funcnames = xlate_funcnames self.pack = {} if pack is None else pack if opts is None: opts = {} threadsafety = not opts.get("multiprocessing") self.context_dict = hubblestack.utils.context.ContextDict(threadsafe=threadsafety) self.opts = self.__prep_mod_opts(opts) self.module_dirs = module_dirs self.tag = tag self.loaded_base_name = loaded_base_name or LOADED_BASE_NAME self.mod_type_check = mod_type_check or _mod_type if "__context__" not in self.pack: self.pack["__context__"] = None for k, v in self.pack.items(): if v is None: # if the value of a pack is None, lets make an empty dict self.context_dict.setdefault(k, {}) self.pack[k] = hubblestack.utils.context.NamespacedDictWrapper(self.context_dict, k) self.whitelist = whitelist self.virtual_enable = virtual_enable self.initial_load = True # names of modules that we don't have (errors, __virtual__, etc.) self.missing_modules = {} # mapping of name -> error self.loaded_modules = {} # mapping of module_name -> dict_of_functions self.loaded_files = set() # TODO: just remove them from file_mapping? self.static_modules = static_modules if static_modules else [] if virtual_funcs is None: virtual_funcs = [] self.virtual_funcs = virtual_funcs self.disabled = set(self.opts.get("disable_{0}{1}".format(self.tag, "" if self.tag[-1] == "s" else "s"), [])) # A map of suffix to description for imp self.suffix_map = {} # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [""] for (suffix, mode, kind) in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) self._lock = threading.RLock() self._refresh_file_mapping() super(LazyLoader, self).__init__() # late init the lazy loader # create all of the import namespaces for subspace in ("int", "ext", "e_int", "salt"): _generate_module(".".join([self.loaded_base_name, tag])) _generate_module(".".join([self.loaded_base_name, tag, subspace])) def __getitem__(self, item): """ Override the __getitem__ in order to decorate the returned function if we need to last-minute inject globals """ return super(LazyLoader, self).__getitem__(item) def __getattr__(self, mod_name): """ Allow for "direct" attribute access-- this allows jinja templates to access things like `hubblestack.test.ping()` """ if mod_name in ("__getstate__", "__setstate__"): return object.__getattribute__(self, mod_name) # if we have an attribute named that, lets return it. try: return object.__getattr__(self, mod_name) # pylint: disable=no-member except AttributeError: pass # otherwise we assume its jinja template access if mod_name not in self.loaded_modules and not self.loaded: for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and mod_name in self.loaded_modules: break if mod_name in self.loaded_modules: return self.loaded_modules[mod_name] else: raise AttributeError(mod_name) def missing_fun_string(self, function_name): """ Return the error string for a missing function. This can range from "not available' to "__virtual__" returned False """ mod_name = function_name.split(".")[0] if mod_name in self.loaded_modules: return "'{0}' is not available.".format(function_name) else: try: reason = self.missing_modules[mod_name] except KeyError: return "'{0}' is not available.".format(function_name) else: if reason is not None: return "'{0}' __virtual__ returned False: {1}".format(mod_name, reason) else: return "'{0}' __virtual__ returned False".format(mod_name) def _refresh_file_mapping(self): """ refresh the mapping of the FS on disk """ # map of suffix to description for imp if self.opts.get("cython_enable", True) is True: try: global pyximport # pylint: disable=invalid-name pyximport = __import__("pyximport") # pylint: disable=import-error pyximport.install() # add to suffix_map so file_mapping will pick it up self.suffix_map[".pyx"] = tuple() except ImportError: log.info( "Cython is enabled in the options but not present " "in the system path. Skipping Cython modules." ) # Allow for zipimport of modules if self.opts.get("enable_zip_modules", True) is True: self.suffix_map[".zip"] = tuple() # allow for module dirs self.suffix_map[""] = ("", "", MODULE_KIND_PKG_DIRECTORY) # create mapping of filename (without suffix) to (path, suffix) # The files are added in order of priority, so order *must* be retained. self.file_mapping = hubblestack.utils.odict.OrderedDict() opt_match = [] def _replace_pre_ext(obj):
for mod_dir in self.module_dirs: try: # Make sure we have a sorted listdir in order to have # expectable override results files = sorted(x for x in os.listdir(mod_dir) if x != "__pycache__") except OSError: continue # Next mod_dir try: pycache_files = [ os.path.join("__pycache__", x) for x in sorted(os.listdir(os.path.join(mod_dir, "__pycache__"))) ] except OSError: pass else: files.extend(pycache_files) for filename in files: try: dirname, basename = os.path.split(filename) if basename.startswith("_"): # skip private modules # log messages omitted for obviousness continue # Next filename f_noext, ext = os.path.splitext(basename) f_noext = PY3_PRE_EXT.sub(_replace_pre_ext, f_noext) try: opt_level = int(opt_match.pop().group(1).rsplit("-", 1)[-1]) except (AttributeError, IndexError, ValueError): # No regex match or no optimization level matched opt_level = 0 try: opt_index = self.opts["optimization_order"].index(opt_level) except KeyError: log.trace( "Disallowed optimization level %d for module " "name '%s', skipping. Add %d to the " "'optimization_order' config option if you " "do not want to ignore this optimization " "level.", opt_level, f_noext, opt_level, ) continue else: # Optimization level not reflected in filename on PY2 opt_index = 0 # make sure it is a suffix we support if ext not in self.suffix_map: continue # Next filename if f_noext in self.disabled: log.trace("Skipping %s, it is disabled by configuration", filename) continue # Next filename fpath = os.path.join(mod_dir, filename) # if its a directory, lets allow us to load that if ext == "": # is there something __init__? subfiles = os.listdir(fpath) for suffix in self.suffix_order: if "" == suffix: continue # Next suffix (__init__ must have a suffix) init_file = "__init__{0}".format(suffix) if init_file in subfiles: break else: continue # Next filename try: curr_ext = self.file_mapping[f_noext][1] curr_opt_index = self.file_mapping[f_noext][2] except KeyError: pass else: if "" in (curr_ext, ext) and curr_ext != ext: log.error("Module/package collision: '%s' and '%s'", fpath, self.file_mapping[f_noext][0]) if ext == ".pyc" and curr_ext == ".pyc": # Check the optimization level if opt_index >= curr_opt_index: # Module name match, but a higher-priority # optimization level was already matched, skipping. continue if not dirname and ext == ".pyc": # On Python 3, we should only load .pyc files from the # __pycache__ subdirectory (i.e. when dirname is not an # empty string). continue # Made it this far - add it self.file_mapping[f_noext] = (fpath, ext, opt_index) except OSError: continue for smod in self.static_modules: f_noext = smod.split(".")[-1] self.file_mapping[f_noext] = (smod, ".o", 0) def clear(self): """ Clear the dict """ with self._lock: super(LazyLoader, self).clear() # clear the lazy loader self.loaded_files = set() self.missing_modules = {} self.loaded_modules = {} # if we have been loaded before, lets clear the file mapping since # we obviously want a re-do if hasattr(self, "opts"): self._refresh_file_mapping() self.initial_load = False def __prep_mod_opts(self, opts): """ Strip out of the opts any logger instance """ if "__grains__" not in self.pack: self.context_dict["grains"] = opts.get("grains", {}) self.pack["__grains__"] = hubblestack.utils.context.NamespacedDictWrapper(self.context_dict, "grains") if "__pillar__" not in self.pack: self.context_dict["pillar"] = opts.get("pillar", {}) self.pack["__pillar__"] = hubblestack.utils.context.NamespacedDictWrapper(self.context_dict, "pillar") ret = opts.copy() for item in ("logger",): if item in ret: del ret[item] pres_opt = get_preserved_opts(opts) if pres_opt is not None: pres_opt.update(ret) return pres_opt return ret def _iter_files(self, mod_name): """ Iterate over all file_mapping files in order of closeness to mod_name """ # do we have an exact match? if mod_name in self.file_mapping: yield mod_name # do we have a partial match? for k in self.file_mapping: if mod_name in k: yield k # anyone else? Bueller? for k in self.file_mapping: if mod_name not in k: yield k def _reload_submodules(self, mod): submodules = (getattr(mod, sname) for sname in dir(mod) if isinstance(getattr(mod, sname), mod.__class__)) # reload only custom "sub"modules for submodule in submodules: # it is a submodule if the name is in a namespace under mod if submodule.__name__.startswith(mod.__name__ + "."): reload_module(submodule) self._reload_submodules(submodule) def _load_module(self, name): mod = None fpath, suffix = self.file_mapping[name][:2] self.loaded_files.add(name) fpath_dirname = os.path.dirname(fpath) try: sys.path.append(fpath_dirname) if fpath_dirname.endswith("__pycache__"): sys.path.append(os.path.dirname(fpath_dirname)) if suffix == ".pyx": mod = pyximport.load_module(name, fpath, tempfile.gettempdir()) elif suffix == ".o": top_mod = __import__(fpath, globals(), locals(), []) comps = fpath.split(".") if len(comps) < 2: mod = top_mod else: mod = top_mod for subname in comps[1:]: mod = getattr(mod, subname) elif suffix == ".zip": mod = zipimporter(fpath).load_module(name) else: desc = self.suffix_map[suffix] # if it is a directory, we don't open a file try: mod_namespace = ".".join((self.loaded_base_name, self.mod_type_check(fpath), self.tag, name)) except TypeError: mod_namespace = "{0}.{1}.{2}.{3}".format( self.loaded_base_name, self.mod_type_check(fpath), self.tag, name ) if suffix == "": # pylint: disable=no-member # Package directory, look for __init__ loader_details = [ (importlib.machinery.SourceFileLoader, importlib.machinery.SOURCE_SUFFIXES), (importlib.machinery.SourcelessFileLoader, importlib.machinery.BYTECODE_SUFFIXES), (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES), ] file_finder = importlib.machinery.FileFinder(fpath_dirname, *loader_details) spec = file_finder.find_spec(mod_namespace) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod # reload all submodules if necessary if not self.initial_load: self._reload_submodules(mod) else: # pylint: disable=no-member loader = MODULE_KIND_MAP[desc[2]](mod_namespace, fpath) spec = importlib.util.spec_from_file_location(mod_namespace, fpath, loader=loader) if spec is None: raise ImportError() # TODO: Get rid of load_module in favor of # exec_module below. load_module is deprecated, but # loading using exec_module has been causing odd things # with the magic dunders we pack into the loaded # modules, most notably with salt-ssh's __opts__. mod = spec.loader.load_module() # mod = importlib.util.module_from_spec(spec) # spec.loader.exec_module(mod) # pylint: enable=no-member sys.modules[mod_namespace] = mod except IOError: raise except ImportError as exc: if "magic number" in str(exc): error_msg = "Failed to import {0} {1}. Bad magic number. If migrating from Python2 to Python3, remove all .pyc files and try again.".format( self.tag, name ) log.warning(error_msg) self.missing_modules[name] = error_msg log.debug("Failed to import %s %s:\n", self.tag, name, exc_info=True) self.missing_modules[name] = exc return False except Exception as error: log.error( "Failed to import %s %s, this is due most likely to a " "syntax error:\n", self.tag, name, exc_info=True, ) self.missing_modules[name] = error return False except SystemExit as error: try: fn_, _, caller, _ = traceback.extract_tb(sys.exc_info()[2])[-1] except Exception: pass else: tgt_fn = os.path.join("salt", "utils", "process.py") if fn_.endswith(tgt_fn) and "_handle_signals" in caller: # Race conditon, SIGTERM or SIGINT received while loader # was in process of loading a module. Call sys.exit to # ensure that the process is killed. sys.exit(0) log.error("Failed to import %s %s as the module called exit()\n", self.tag, name, exc_info=True) self.missing_modules[name] = error return False finally: sys.path.remove(fpath_dirname) if hasattr(mod, "__opts__"): mod.__opts__.update(self.opts) else: mod.__opts__ = self.opts # pack whatever other globals we were asked to for p_name, p_value in self.pack.items(): setattr(mod, p_name, p_value) module_name = mod.__name__.rsplit(".", 1)[-1] if callable(self.xlate_modnames): module_name = self.xlate_modnames([module_name], name, fpath, suffix, mod, mode="module_name") name = self.xlate_modnames([name], name, fpath, suffix, mod, mode="name") # Call a module's initialization method if it exists module_init = getattr(mod, "__init__", None) if inspect.isfunction(module_init): try: module_init(self.opts) except TypeError as e: log.error(e) except Exception: err_string = "__init__ failed" log.debug("Error loading %s.%s: %s", self.tag, module_name, err_string, exc_info=True) self.missing_modules[module_name] = err_string self.missing_modules[name] = err_string return False # if virtual modules are enabled, we need to look for the # __virtual__() function inside that module and run it. if self.virtual_enable: virtual_funcs_to_process = ["__virtual__"] + self.virtual_funcs for virtual_func in virtual_funcs_to_process: virtual_ret, module_name, virtual_err, virtual_aliases = self._process_virtual( mod, module_name, virtual_func ) if virtual_err is not None: log.trace("Error loading %s.%s: %s", self.tag, module_name, virtual_err) # if _process_virtual returned a non-True value then we are # supposed to not process this module if virtual_ret is not True and module_name not in self.missing_modules: # If a module has information about why it could not be loaded, record it self.missing_modules[module_name] = virtual_err self.missing_modules[name] = virtual_err return False else: virtual_aliases = () if getattr(mod, "__load__", False) is not False: log.info( "The functions from module '%s' are being loaded from the " "provided __load__ attribute", module_name ) # If we had another module by the same virtual name, we should put any # new functions under the existing dictionary. mod_names = [module_name] + list(virtual_aliases) if callable(self.xlate_modnames): mod_names = self.xlate_modnames(mod_names, name, fpath, suffix, mod, mode="mod_names") mod_dict = dict(((x, self.loaded_modules.get(x, self.mod_dict_class())) for x in mod_names)) for attr in getattr(mod, "__load__", dir(mod)): if attr.startswith("_"): # private functions are skipped continue func = getattr(mod, attr) if not inspect.isfunction(func) and not isinstance(func, functools.partial): # Not a function!? Skip it!!! continue if callable(self.funcname_filter) and not self.funcname_filter(attr, mod): # rejected by filter continue # Let's get the function name. # If the module has the __func_alias__ attribute, it must be a # dictionary mapping in the form of(key -> value): # <real-func-name> -> <desired-func-name> # # It default's of course to the found callable attribute name # if no alias is defined. funcname = getattr(mod, "__func_alias__", {}).get(attr, attr) for tgt_mod in mod_names: try: full_funcname = ".".join((tgt_mod, funcname)) except TypeError: full_funcname = "{0}.{1}".format(tgt_mod, funcname) if callable(self.xlate_funcnames): funcname, full_funcname = self.xlate_funcnames( name, fpath, suffix, tgt_mod, funcname, full_funcname, mod, func ) # Save many references for lookups # Careful not to overwrite existing (higher priority) functions if full_funcname not in self._dict: self._dict[full_funcname] = func if funcname not in mod_dict[tgt_mod]: setattr(mod_dict[tgt_mod], funcname, func) mod_dict[tgt_mod][funcname] = func self._apply_outputter(func, mod) # enforce depends try: Depends.enforce_dependencies(self._dict, self.tag, name) except RuntimeError as exc: log.info("Depends.enforce_dependencies() failed for the following " "reason: %s", exc) for tgt_mod in mod_names: self.loaded_modules[tgt_mod] = mod_dict[tgt_mod] return True def _load(self, key): """ Load a single item if you have it """ # if the key doesn't have a '.' then it isn't valid for this mod dict if not isinstance(key, str): raise KeyError("The key must be a string.") if "." not in key: raise KeyError("The key '{0}' should contain a '.'".format(key)) mod_name, _ = key.split(".", 1) with self._lock: # It is possible that the key is in the dictionary after # acquiring the lock due to another thread loading it. if mod_name in self.missing_modules or key in self._dict: return True # if the modulename isn't in the whitelist, don't bother if self.whitelist and mod_name not in self.whitelist: log.error( "Failed to load function %s because its module (%s) is " "not in the whitelist: %s", key, mod_name, self.whitelist, ) raise KeyError(key) def _inner_load(mod_name): for name in self._iter_files(mod_name): if name in self.loaded_files: continue # if we got what we wanted, we are done if self._load_module(name) and key in self._dict: return True return False # try to load the module ret = None reloaded = False # re-scan up to once, IOErrors or a failed load cause re-scans of the # filesystem while True: try: ret = _inner_load(mod_name) if not reloaded and ret is not True: self._refresh_file_mapping() reloaded = True continue break except IOError: if not reloaded: self._refresh_file_mapping() reloaded = True continue return ret def _load_all(self): """ Load all of them """ with self._lock: for name in self.file_mapping: if name in self.loaded_files or name in self.missing_modules: continue self._load_module(name) self.loaded = True def reload_modules(self): with self._lock: self.loaded_files = set() self._load_all() def _apply_outputter(self, func, mod): """ Apply the __outputter__ variable to the functions """ if hasattr(mod, "__outputter__"): outp = mod.__outputter__ if func.__name__ in outp: func.__outputter__ = outp[func.__name__] def _process_virtual(self, mod, module_name, virtual_func="__virtual__"): """ Given a loaded module and its default name determine its virtual name This function returns a tuple. The first value will be either True or False and will indicate if the module should be loaded or not (i.e. if it threw and exception while processing its __virtual__ function). The second value is the determined virtual name, which may be the same as the value provided. The default name can be calculated as follows:: module_name = mod.__name__.rsplit('.', 1)[-1] """ # The __virtual__ function will return either a True or False value. # If it returns a True value it can also set a module level attribute # named __virtualname__ with the name that the module should be # referred to as. # # This allows us to have things like the pkg module working on all # platforms under the name 'pkg'. It also allows for modules like # augeas_cfg to be referred to as 'augeas', which would otherwise have # namespace collisions. And finally it allows modules to return False # if they are not intended to run on the given platform or are missing # dependencies. virtual_aliases = getattr(mod, "__virtual_aliases__", tuple()) try: error_reason = None if hasattr(mod, "__virtual__") and inspect.isfunction(mod.__virtual__): try: start = time.time() virtual = getattr(mod, virtual_func)() if isinstance(virtual, tuple): error_reason = virtual[1] virtual = virtual[0] if self.opts.get("virtual_timer", False): end = time.time() - start msg = "Virtual function took {0} seconds for {1}".format(end, module_name) log.warning(msg) except Exception as exc: error_reason = ( "Exception raised when processing __virtual__ function" " for {0}. Module will not be loaded: {1}".format(mod.__name__, exc) ) log.error(error_reason, exc_info=True) virtual = None # Get the module's virtual name virtualname = getattr(mod, "__virtualname__", virtual) if not virtual: # if __virtual__() evaluates to False then the module # wasn't meant for this platform or it's not supposed to # load for some other reason. # Some modules might accidentally return None and are # improperly loaded if virtual is None: log.warning( "%s.__virtual__() is wrongly returning `None`. " "It should either return `True`, `False` or a new " "name. If you're the developer of the module " "'%s', please fix this.", mod.__name__, module_name, ) return (False, module_name, error_reason, virtual_aliases) # At this point, __virtual__ did not return a # boolean value, let's check for deprecated usage # or module renames if virtual is not True and module_name != virtual: # The module is renaming itself. Updating the module name # with the new name log.trace("Loaded %s as virtual %s", module_name, virtual) if not hasattr(mod, "__virtualname__"): hubblestack.utils.versions.warn_until( "Hydrogen", "The '{0}' module is renaming itself in its " "__virtual__() function ({1} => {2}). Please " "set it's virtual name as the " "'__virtualname__' module attribute. " "Example: \"__virtualname__ = '{2}'\"".format(mod.__name__, module_name, virtual), ) if virtualname != virtual: # The __virtualname__ attribute does not match what's # being returned by the __virtual__() function. This # should be considered an error. log.error( "The module '%s' is showing some bad usage. Its " "__virtualname__ attribute is set to '%s' yet the " "__virtual__() function is returning '%s'. These " "values should match!", mod.__name__, virtualname, virtual, ) module_name = virtualname # If the __virtual__ function returns True and __virtualname__ # is set then use it elif virtual is True and virtualname != module_name: if virtualname is not True: module_name = virtualname except KeyError: # Key errors come out of the virtual function when passing # in incomplete grains sets, these can be safely ignored # and logged to debug, still, it includes the traceback to # help debugging. log.error('Failed to LazyLoad "%s"', module_name, exc_info=True) except Exception: # If the module throws an exception during __virtual__() # then log the information and continue to the next. log.error("Failed to read the virtual function for %s: %s", self.tag, module_name, exc_info=True) return (False, module_name, error_reason, virtual_aliases) return (True, module_name, None, virtual_aliases) class FilterDictWrapper(MutableMapping): """ Create a dict which wraps another dict with a specific key suffix on get This is to replace "filter_load" """ def __init__(self, d, suffix): self._dict = d self.suffix = suffix def __setitem__(self, key, val): self._dict[key] = val def __delitem__(self, key): del self._dict[key] def __getitem__(self, key): return self._dict[key + self.suffix] def __len__(self): return len(self._dict) def __iter__(self): for key in self._dict: if key.endswith(self.suffix): yield key.replace(self.suffix, "") def matchers(opts): """ Return the matcher services plugins """ return LazyLoader(_module_dirs(opts, "matchers"), opts, tag="matchers") def _nova_funcname_filter(funcname, mod): # pylint: disable=unused-argument """ reject function names that aren't "audit" args: mod :- the actual imported module (allowing mod.__file__ examination, etc) funcname :- the attribute name as given by dir(mod) return: True :- sure, we can provide this function False :- skip this one """ if funcname == "audit": return True return False def _nova_xlate_modnames(mod_names, name, fpath, suffix, mod, mode="mod_names"): # pylint: disable=unused-argument """ Translate (xlate) "service" into "/service" args: name :- the name of the module we're loading (e.g., 'service') fpath :- the file path of the module we're loading suffix :- the suffix of the module we're loading (e.g., '.pyc', usually) mod :- the actual imported module (allowing mod.__file__ examination) mode :- the name of the load_module variable being translated return: either a list of new names (for "mod_names") or a single new name (for "name" and "module_name") """ new_modname = "/" + name if mode in ("module_name", "name"): return new_modname return [new_modname] def _nova_xlate_funcnames( name, fpath, suffix, tgt_mod, funcname, full_funcname, mod, func ): # pylint: disable=unused-argument """ Translate (xlate) "service.audit" into "/service.py" args: name :- the name of the module we're loading (e.g., 'service') fpath :- the file path of the module we're loading suffix :- the suffix of the module we're loading (e.g., '.pyc', usually) tgt_mod :- the current virtual name of the module we're loading (e.g., 'service') funcname :- the function name we're maping (e.g., 'audit') full_funcname :- the LazyLoader key format item (e.g., 'service.audit') mod :- the actual imported module (allowing mod.__file__ examination) func :- the actual function being mapped (allowing func.__name__) return: funcname, full_funcname The old NovaLazyLoader's behavior can be mimicked without altering the LazyLoader (very much) by simply pretending tgt_mod='/service', funcname='py' and full_funcname='/service.py'. """ new_funcname = suffix[1:] if new_funcname == "pyc": new_funcname = "py" return new_funcname, ".".join([name, new_funcname]) def nova(hubble_dir, opts, modules, context=None): """ Return a nova (!lazy) loader. This does return a LazyLoader, but hubble.audit module always iterates the keys forcing a full load, which somewhat defeates the purpose of using the LazyLoader object at all. nova() also populates loader.__data__ and loader.__missing_data__ for backwards compatibility purposes but omits some overlapping functions that were essentially unnecessary. Originally hubble.audit used a special NovaLazyLoader that was intended to make everything more readable but in fact only fragmented the codebase and obsfucated the purpose and function of the new data elements it introduced. The loader functions and file_mapping functions of the loader were also hopelessly mixed up with the yaml data loaders for no apparent reason. Presumably the original intent was to be able to use expressions like __nova__['/cis/debian-9-whatever.yaml'] to access those data elements; but this wasn't actually used, apparently favoring the form: __nova__.__data__['/cis/whatever.yaml'] instead. The __nova__.__data__['/whatever.yaml'] format is retained, but the file_mapping['/whatever.yaml'] and load_module('whatever') functionality is not. This means that anywhere refresh_filemapping() is expected to refresh yaml on disk will no-longer do so. Interestingly, it didn't seem to work before anyway, which seems to be the reason for the special sync() section of the hubble.audit. """ loader = LazyLoader( _module_dirs(opts, "nova"), opts, tag="nova", funcname_filter=_nova_funcname_filter, xlate_modnames=_nova_xlate_modnames, xlate_funcnames=_nova_xlate_funcnames, pack={"__context__": context, "__mods__": modules}, ) loader.__data__ = data = dict() loader.__missing_data__ = missing_data = dict() for mod_dir in hubble_dir: for path, _, filenames in os.walk(mod_dir): for filename in filenames: pathname = os.path.join(path, filename) name = pathname[len(mod_dir) :] if filename.endswith(".yaml"): try: with open(pathname, "r") as fh: data[name] = yaml.safe_load(fh) except Exception as exc: missing_data[name] = str(exc) log.exception("Error loading yaml from %s", pathnmame) return loader
""" Hack so we can get the optimization level that we replaced (if any) out of the re.sub call below. We use a list here because it is a persistent data structure that we will be able to access after re.sub is called. """ opt_match.append(obj) return ""
instanceProfile.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package iam import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Resource Type definition for AWS::IAM::InstanceProfile // // Deprecated: InstanceProfile is not yet supported by AWS Native, so its creation will currently fail. Please use the classic AWS provider, if possible. type InstanceProfile struct { pulumi.CustomResourceState Arn pulumi.StringOutput `pulumi:"arn"` InstanceProfileName pulumi.StringPtrOutput `pulumi:"instanceProfileName"` Path pulumi.StringPtrOutput `pulumi:"path"` Roles pulumi.StringArrayOutput `pulumi:"roles"` } // NewInstanceProfile registers a new resource with the given unique name, arguments, and options. func NewInstanceProfile(ctx *pulumi.Context, name string, args *InstanceProfileArgs, opts ...pulumi.ResourceOption) (*InstanceProfile, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.Roles == nil { return nil, errors.New("invalid value for required argument 'Roles'") } var resource InstanceProfile err := ctx.RegisterResource("aws-native:iam:InstanceProfile", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetInstanceProfile gets an existing InstanceProfile resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetInstanceProfile(ctx *pulumi.Context, name string, id pulumi.IDInput, state *InstanceProfileState, opts ...pulumi.ResourceOption) (*InstanceProfile, error) { var resource InstanceProfile err := ctx.ReadResource("aws-native:iam:InstanceProfile", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering InstanceProfile resources. type instanceProfileState struct { } type InstanceProfileState struct { } func (InstanceProfileState) ElementType() reflect.Type { return reflect.TypeOf((*instanceProfileState)(nil)).Elem() } type instanceProfileArgs struct { InstanceProfileName *string `pulumi:"instanceProfileName"` Path *string `pulumi:"path"` Roles []string `pulumi:"roles"` } // The set of arguments for constructing a InstanceProfile resource. type InstanceProfileArgs struct { InstanceProfileName pulumi.StringPtrInput Path pulumi.StringPtrInput Roles pulumi.StringArrayInput } func (InstanceProfileArgs) ElementType() reflect.Type { return reflect.TypeOf((*instanceProfileArgs)(nil)).Elem() } type InstanceProfileInput interface { pulumi.Input ToInstanceProfileOutput() InstanceProfileOutput ToInstanceProfileOutputWithContext(ctx context.Context) InstanceProfileOutput } func (*InstanceProfile) ElementType() reflect.Type { return reflect.TypeOf((*InstanceProfile)(nil)) } func (i *InstanceProfile) ToInstanceProfileOutput() InstanceProfileOutput { return i.ToInstanceProfileOutputWithContext(context.Background()) } func (i *InstanceProfile) ToInstanceProfileOutputWithContext(ctx context.Context) InstanceProfileOutput { return pulumi.ToOutputWithContext(ctx, i).(InstanceProfileOutput) } type InstanceProfileOutput struct{ *pulumi.OutputState } func (InstanceProfileOutput) ElementType() reflect.Type { return reflect.TypeOf((*InstanceProfile)(nil)) } func (o InstanceProfileOutput) ToInstanceProfileOutput() InstanceProfileOutput { return o } func (o InstanceProfileOutput) ToInstanceProfileOutputWithContext(ctx context.Context) InstanceProfileOutput { return o
} func init() { pulumi.RegisterInputType(reflect.TypeOf((*InstanceProfileInput)(nil)).Elem(), &InstanceProfile{}) pulumi.RegisterOutputType(InstanceProfileOutput{}) }
lib.rs
//! Core I/O traits and combinators when working with Tokio. //! //! A description of the high-level I/O combinators can be [found online] in //! addition to a description of the [low level details]. //! //! [found online]: https://tokio.rs/docs/getting-started/core/ //! [low level details]: https://tokio.rs/docs/going-deeper-tokio/core-low-level/ #![deny(missing_docs, missing_debug_implementations, warnings)] #![doc(html_root_url = "https://docs.rs/tokio-io/0.1.6")] #[macro_use] extern crate log; #[macro_use] extern crate futures; extern crate bytes; use std::io as std_io; use futures::{Future, Stream}; /// A convenience typedef around a `Future` whose error component is `io::Error` pub type IoFuture<T> = Box<Future<Item = T, Error = std_io::Error> + Send>; /// A convenience typedef around a `Stream` whose error component is `io::Error` pub type IoStream<T> = Box<Stream<Item = T, Error = std_io::Error> + Send>; /// A convenience macro for working with `io::Result<T>` from the `Read` and /// `Write` traits. /// /// This macro takes `io::Result<T>` as input, and returns `T` as the output. If /// the input type is of the `Err` variant, then `Poll::NotReady` is returned if /// it indicates `WouldBlock` or otherwise `Err` is returned. #[macro_export] macro_rules! try_nb { ($e:expr) => (match $e { Ok(t) => t, Err(ref e) if e.kind() == ::std::io::ErrorKind::WouldBlock => { return Ok(::futures::Async::NotReady) } Err(e) => return Err(e.into()), }) } pub mod io; pub mod codec; mod allow_std; mod async_read; mod async_write; mod framed; mod framed_read; mod framed_write; mod length_delimited; mod lines; mod split; mod window; pub use self::async_read::AsyncRead; pub use self::async_write::AsyncWrite; fn _assert_objects() { fn
<T>() {} _assert::<Box<AsyncRead>>(); _assert::<Box<AsyncWrite>>(); }
_assert
c08p01.rs
fn triple_step(steps: i32) -> i32 { if steps == 1 { 1 } else if steps == 2 { triple_step(steps - 1) + 1 } else if steps == 3 { triple_step(steps - 1) + triple_step(steps - 2) + 1 } else { triple_step(steps - 1) + triple_step(steps - 2) + triple_step(steps - 3) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_triple_step()
} fn main() { triple_step(1); }
{ assert_eq!(triple_step(1), 1); assert_eq!(triple_step(2), 2); assert_eq!(triple_step(3), 4); assert_eq!(triple_step(4), 7); assert_eq!(triple_step(5), 13); }
tiny_mce_src_1.js
// FILE IS GENERATED BY COMBINING THE SOURCES IN THE "classes" DIRECTORY SO DON'T MODIFY THIS FILE DIRECTLY (function(win) { var whiteSpaceRe = /^\s*|\s*$/g, undef, isRegExpBroken = 'B'.replace(/A(.)|B/, '$1') === '$1'; var tinymce = { majorVersion : '3', minorVersion : '5b3', releaseDate : '2012-03-29', _init : function() { var t = this, d = document, na = navigator, ua = na.userAgent, i, nl, n, base, p, v; t.isOpera = win.opera && opera.buildNumber; t.isWebKit = /WebKit/.test(ua); t.isIE = !t.isWebKit && !t.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName); t.isIE6 = t.isIE && /MSIE [56]/.test(ua); t.isIE7 = t.isIE && /MSIE [7]/.test(ua); t.isIE8 = t.isIE && /MSIE [8]/.test(ua); t.isIE9 = t.isIE && /MSIE [9]/.test(ua); t.isGecko = !t.isWebKit && /Gecko/.test(ua); t.isMac = ua.indexOf('Mac') != -1; t.isAir = /adobeair/i.test(ua); t.isIDevice = /(iPad|iPhone)/.test(ua); t.isIOS5 = t.isIDevice && ua.match(/AppleWebKit\/(\d*)/)[1]>=534; // TinyMCE .NET webcontrol might be setting the values for TinyMCE if (win.tinyMCEPreInit) { t.suffix = tinyMCEPreInit.suffix; t.baseURL = tinyMCEPreInit.base; t.query = tinyMCEPreInit.query; return; } // Get suffix and base t.suffix = ''; // If base element found, add that infront of baseURL nl = d.getElementsByTagName('base'); for (i=0; i<nl.length; i++) { v = nl[i].href; if (v) { // Host only value like http://site.com or http://site.com:8008 if (/^https?:\/\/[^\/]+$/.test(v)) v += '/'; base = v ? v.match(/.*\//)[0] : ''; // Get only directory } } function getBase(n) { if (n.src && /tiny_mce(|_gzip|_jquery|_prototype|_full)(_dev|_src)?.js/.test(n.src)) { if (/_(src|dev)\.js/g.test(n.src)) t.suffix = '_src'; if ((p = n.src.indexOf('?')) != -1) t.query = n.src.substring(p + 1); t.baseURL = n.src.substring(0, n.src.lastIndexOf('/')); // If path to script is relative and a base href was found add that one infront // the src property will always be an absolute one on non IE browsers and IE 8 // so this logic will basically only be executed on older IE versions if (base && t.baseURL.indexOf('://') == -1 && t.baseURL.indexOf('/') !== 0) t.baseURL = base + t.baseURL; return t.baseURL; } return null; }; // Check document nl = d.getElementsByTagName('script'); for (i=0; i<nl.length; i++) { if (getBase(nl[i])) return; } // Check head n = d.getElementsByTagName('head')[0]; if (n) { nl = n.getElementsByTagName('script'); for (i=0; i<nl.length; i++) { if (getBase(nl[i])) return; } } return; }, is : function(o, t) { if (!t) return o !== undef; if (t == 'array' && (o.hasOwnProperty && o instanceof Array)) return true; return typeof(o) == t; }, makeMap : function(items, delim, map) { var i; items = items || []; delim = delim || ','; if (typeof(items) == "string") items = items.split(delim); map = map || {}; i = items.length; while (i--) map[items[i]] = {}; return map; }, each : function(o, cb, s) { var n, l; if (!o) return 0; s = s || o; if (o.length !== undef) { // Indexed arrays, needed for Safari for (n=0, l = o.length; n < l; n++) { if (cb.call(s, o[n], n, o) === false) return 0; } } else { // Hashtables for (n in o) { if (o.hasOwnProperty(n)) { if (cb.call(s, o[n], n, o) === false) return 0; } } } return 1; }, map : function(a, f) { var o = []; tinymce.each(a, function(v) { o.push(f(v)); }); return o; }, grep : function(a, f) { var o = []; tinymce.each(a, function(v) { if (!f || f(v)) o.push(v); }); return o; }, inArray : function(a, v) { var i, l; if (a) { for (i = 0, l = a.length; i < l; i++) { if (a[i] === v) return i; } } return -1; }, extend : function(obj, ext) { var i, l, name, args = arguments, value; for (i = 1, l = args.length; i < l; i++) { ext = args[i]; for (name in ext) { if (ext.hasOwnProperty(name)) { value = ext[name]; if (value !== undef) { obj[name] = value; } } } } return obj; }, trim : function(s) { return (s ? '' + s : '').replace(whiteSpaceRe, ''); }, create : function(s, p, root) { var t = this, sp, ns, cn, scn, c, de = 0; // Parse : <prefix> <class>:<super class> s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s); cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name // Create namespace for new class ns = t.createNS(s[3].replace(/\.\w+$/, ''), root); // Class already exists if (ns[cn]) return; // Make pure static class if (s[2] == 'static') { ns[cn] = p; if (this.onCreate) this.onCreate(s[2], s[3], ns[cn]); return; } // Create default constructor if (!p[cn]) { p[cn] = function() {}; de = 1; } // Add constructor and methods ns[cn] = p[cn]; t.extend(ns[cn].prototype, p); // Extend if (s[5]) { sp = t.resolve(s[5]).prototype; scn = s[5].match(/\.(\w+)$/i)[1]; // Class name // Extend constructor c = ns[cn]; if (de) { // Add passthrough constructor ns[cn] = function() { return sp[scn].apply(this, arguments); }; } else { // Add inherit constructor ns[cn] = function() { this.parent = sp[scn]; return c.apply(this, arguments); }; } ns[cn].prototype[cn] = ns[cn]; // Add super methods t.each(sp, function(f, n) { ns[cn].prototype[n] = sp[n]; }); // Add overridden methods t.each(p, function(f, n) { // Extend methods if needed if (sp[n]) { ns[cn].prototype[n] = function() { this.parent = sp[n]; return f.apply(this, arguments); }; } else { if (n != cn) ns[cn].prototype[n] = f; } }); } // Add static methods t.each(p['static'], function(f, n) { ns[cn][n] = f; }); if (this.onCreate) this.onCreate(s[2], s[3], ns[cn].prototype); }, walk : function(o, f, n, s) { s = s || this; if (o) { if (n) o = o[n]; tinymce.each(o, function(o, i) { if (f.call(s, o, i, n) === false) return false; tinymce.walk(o, f, n, s); }); } }, createNS : function(n, o) { var i, v; o = o || win; n = n.split('.'); for (i=0; i<n.length; i++) { v = n[i]; if (!o[v]) o[v] = {}; o = o[v]; } return o; }, resolve : function(n, o) { var i, l; o = o || win; n = n.split('.'); for (i = 0, l = n.length; i < l; i++) { o = o[n[i]]; if (!o) break; } return o; }, addUnload : function(f, s) { var t = this, unload; unload = function() { var li = t.unloads, o, n; if (li) { // Call unload handlers for (n in li) { o = li[n]; if (o && o.func) o.func.call(o.scope, 1); // Send in one arg to distinct unload and user destroy } // Detach unload function if (win.detachEvent) { win.detachEvent('onbeforeunload', fakeUnload); win.detachEvent('onunload', unload); } else if (win.removeEventListener) win.removeEventListener('unload', unload, false); // Destroy references t.unloads = o = li = w = unload = 0; // Run garbarge collector on IE if (win.CollectGarbage) CollectGarbage(); } }; function fakeUnload() { var d = document; function stop() { // Prevent memory leak d.detachEvent('onstop', stop); // Call unload handler if (unload) unload(); d = 0; }; // Is there things still loading, then do some magic if (d.readyState == 'interactive') { // Fire unload when the currently loading page is stopped if (d) d.attachEvent('onstop', stop); // Remove onstop listener after a while to prevent the unload function // to execute if the user presses cancel in an onbeforeunload // confirm dialog and then presses the browser stop button win.setTimeout(function() { if (d) d.detachEvent('onstop', stop); }, 0); } }; f = {func : f, scope : s || this}; if (!t.unloads) { // Attach unload handler if (win.attachEvent) { win.attachEvent('onunload', unload); win.attachEvent('onbeforeunload', fakeUnload); } else if (win.addEventListener) win.addEventListener('unload', unload, false); // Setup initial unload handler array t.unloads = [f]; } else t.unloads.push(f); return f; }, removeUnload : function(f) { var u = this.unloads, r = null; tinymce.each(u, function(o, i) { if (o && o.func == f) { u.splice(i, 1); r = f; return false; } }); return r; }, explode : function(s, d) { if (!s || tinymce.is(s, 'array')) { return s; } return tinymce.map(s.split(d || ','), tinymce.trim); }, _addVer : function(u) { var v; if (!this.query) return u; v = (u.indexOf('?') == -1 ? '?' : '&') + this.query; if (u.indexOf('#') == -1) return u + v; return u.replace('#', v + '#'); }, // Fix function for IE 9 where regexps isn't working correctly // Todo: remove me once MS fixes the bug _replace : function(find, replace, str) { // On IE9 we have to fake $x replacement if (isRegExpBroken) { return str.replace(find, function() { var val = replace, args = arguments, i; for (i = 0; i < args.length - 2; i++) { if (args[i] === undef) { val = val.replace(new RegExp('\\$' + i, 'g'), ''); } else { val = val.replace(new RegExp('\\$' + i, 'g'), args[i]); } } return val; }); } return str.replace(find, replace); } }; // Initialize the API tinymce._init(); // Expose tinymce namespace to the global namespace (window) win.tinymce = win.tinyMCE = tinymce; // Describe the different namespaces })(window); tinymce.create('tinymce.util.Dispatcher', { scope : null, listeners : null, Dispatcher : function(s) { this.scope = s || this; this.listeners = []; }, add : function(cb, s) { this.listeners.push({cb : cb, scope : s || this.scope}); return cb; }, addToTop : function(cb, s) { this.listeners.unshift({cb : cb, scope : s || this.scope}); return cb; }, remove : function(cb) { var l = this.listeners, o = null; tinymce.each(l, function(c, i) { if (cb == c.cb) { o = cb; l.splice(i, 1); return false; } }); return o; }, dispatch : function() { var s, a = arguments, i, li = this.listeners, c; // Needs to be a real loop since the listener count might change while looping // And this is also more efficient for (i = 0; i<li.length; i++) { c = li[i]; s = c.cb.apply(c.scope, a.length > 0 ? a : [c.scope]); if (s === false) break; } return s; } }); (function() { var each = tinymce.each; tinymce.create('tinymce.util.URI', { URI : function(u, s) { var t = this, o, a, b, base_url; // Trim whitespace u = tinymce.trim(u); // Default settings s = t.settings = s || {}; // Strange app protocol that isn't http/https or local anchor // For example: mailto,skype,tel etc. if (/^([\w\-]+):([^\/]{2})/i.test(u) || /^\s*#/.test(u)) { t.source = u; return; } // Absolute path with no host, fake host and protocol if (u.indexOf('/') === 0 && u.indexOf('//') !== 0) u = (s.base_uri ? s.base_uri.protocol || 'http' : 'http') + '://mce_host' + u; // Relative path http:// or protocol relative //path if (!/^[\w\-]*:?\/\//.test(u)) { base_url = s.base_uri ? s.base_uri.path : new tinymce.util.URI(location.href).directory; u = ((s.base_uri && s.base_uri.protocol) || 'http') + '://mce_host' + t.toAbsPath(base_url, u); } // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) u = u.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something u = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(u); each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { var s = u[i]; // Zope 3 workaround, they use @@something if (s) s = s.replace(/\(mce_at\)/g, '@@'); t[v] = s; }); b = s.base_uri; if (b) { if (!t.protocol) t.protocol = b.protocol; if (!t.userInfo) t.userInfo = b.userInfo; if (!t.port && t.host === 'mce_host') t.port = b.port; if (!t.host || t.host === 'mce_host') t.host = b.host; t.source = ''; } //t.path = t.path || '/'; }, setPath : function(p) { var t = this; p = /^(.*?)\/?(\w+)?$/.exec(p); // Update path parts t.path = p[0]; t.directory = p[1]; t.file = p[2]; // Rebuild source t.source = ''; t.getURI(); }, toRelative : function(u) { var t = this, o; if (u === "./") return u; u = new tinymce.util.URI(u, {base_uri : t}); // Not on same domain/port or protocol if ((u.host != 'mce_host' && t.host != u.host && u.host) || t.port != u.port || t.protocol != u.protocol) return u.getURI(); var tu = t.getURI(), uu = u.getURI(); // Allow usage of the base_uri when relative_urls = true if(tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) return tu; o = t.toRelPath(t.path, u.path); // Add query if (u.query) o += '?' + u.query; // Add anchor if (u.anchor) o += '#' + u.anchor; return o; }, toAbsolute : function(u, nh) { u = new tinymce.util.URI(u, {base_uri : this}); return u.getURI(this.host == u.host && this.protocol == u.protocol ? nh : 0); }, toRelPath : function(base, path) { var items, bp = 0, out = '', i, l; // Split the paths base = base.substring(0, base.lastIndexOf('/')); base = base.split('/'); items = path.split('/'); if (base.length >= items.length) { for (i = 0, l = base.length; i < l; i++) { if (i >= items.length || base[i] != items[i]) { bp = i + 1; break; } } } if (base.length < items.length) { for (i = 0, l = items.length; i < l; i++) { if (i >= base.length || base[i] != items[i]) { bp = i + 1; break; } } } if (bp === 1) return path; for (i = 0, l = base.length - (bp - 1); i < l; i++) out += "../"; for (i = bp - 1, l = items.length; i < l; i++) { if (i != bp - 1) out += "/" + items[i]; else out += items[i]; } return out; }, toAbsPath : function(base, path) { var i, nb = 0, o = [], tr, outPath; // Split paths tr = /\/$/.test(path) ? '/' : ''; base = base.split('/'); path = path.split('/'); // Remove empty chunks each(base, function(k) { if (k) o.push(k); }); base = o; // Merge relURLParts chunks for (i = path.length - 1, o = []; i >= 0; i--) { // Ignore empty or . if (path[i].length === 0 || path[i] === ".") continue; // Is parent if (path[i] === '..') { nb++; continue; } // Move up if (nb > 0) { nb--; continue; } o.push(path[i]); } i = base.length - nb; // If /a/b/c or / if (i <= 0) outPath = o.reverse().join('/'); else outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); // Add front / if it's needed if (outPath.indexOf('/') !== 0) outPath = '/' + outPath; // Add traling / if it's needed if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) outPath += tr; return outPath; }, getURI : function(nh) { var s, t = this; // Rebuild source if (!t.source || nh) { s = ''; if (!nh) { if (t.protocol) s += t.protocol + '://'; if (t.userInfo) s += t.userInfo + '@'; if (t.host) s += t.host; if (t.port) s += ':' + t.port; } if (t.path) s += t.path; if (t.query) s += '?' + t.query; if (t.anchor) s += '#' + t.anchor; t.source = s; } return t.source; } }); })(); (function() { var each = tinymce.each; tinymce.create('static tinymce.util.Cookie', { getHash : function(n) { var v = this.get(n), h; if (v) { each(v.split('&'), function(v) { v = v.split('='); h = h || {}; h[unescape(v[0])] = unescape(v[1]); }); } return h; }, setHash : function(n, v, e, p, d, s) { var o = ''; each(v, function(v, k) { o += (!o ? '' : '&') + escape(k) + '=' + escape(v); }); this.set(n, o, e, p, d, s); }, get : function(n) { var c = document.cookie, e, p = n + "=", b; // Strict mode if (!c) return; b = c.indexOf("; " + p); if (b == -1) { b = c.indexOf(p); if (b !== 0) return null; } else b += 2; e = c.indexOf(";", b); if (e == -1) e = c.length; return unescape(c.substring(b + p.length, e)); }, set : function(n, v, e, p, d, s) { document.cookie = n + "=" + escape(v) + ((e) ? "; expires=" + e.toGMTString() : "") + ((p) ? "; path=" + escape(p) : "") + ((d) ? "; domain=" + d : "") + ((s) ? "; secure" : ""); }, remove : function(n, p) { var d = new Date(); d.setTime(d.getTime() - 1000); this.set(n, '', d, p, d); } }); })(); (function() { function serialize(o, quote) { var i, v, t, name; quote = quote || '"'; if (o == null) return 'null'; t = typeof o; if (t == 'string') { v = '\bb\tt\nn\ff\rr\""\'\'\\\\'; return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) { // Make sure single quotes never get encoded inside double quotes for JSON compatibility if (quote === '"' && a === "'") return a; i = v.indexOf(b); if (i + 1) return '\\' + v.charAt(i + 1); a = b.charCodeAt().toString(16); return '\\u' + '0000'.substring(a.length) + a; }) + quote; } if (t == 'object') { if (o.hasOwnProperty && o instanceof Array) { for (i=0, v = '['; i<o.length; i++) v += (i > 0 ? ',' : '') + serialize(o[i], quote); return v + ']'; } v = '{'; for (name in o) { if (o.hasOwnProperty(name)) { v += typeof o[name] != 'function' ? (v.length > 1 ? ',' + quote : quote) + name + quote +':' + serialize(o[name], quote) : ''; } } return v + '}'; } return '' + o; }; tinymce.util.JSON = { serialize: serialize, parse: function(s) { try { return eval('(' + s + ')'); } catch (ex) { // Ignore } } }; })(); tinymce.create('static tinymce.util.XHR', { send : function(o) { var x, t, w = window, c = 0; function ready() { if (!o.async || x.readyState == 4 || c++ > 10000) { if (o.success && c < 10000 && x.status == 200) o.success.call(o.success_scope, '' + x.responseText, x, o); else if (o.error) o.error.call(o.error_scope, c > 10000 ? 'TIMED_OUT' : 'GENERAL', x, o); x = null; } else w.setTimeout(ready, 10); }; // Default settings o.scope = o.scope || this; o.success_scope = o.success_scope || o.scope; o.error_scope = o.error_scope || o.scope; o.async = o.async === false ? false : true; o.data = o.data || ''; function get(s) { x = 0; try { x = new ActiveXObject(s); } catch (ex) { } return x; }; x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Microsoft.XMLHTTP') || get('Msxml2.XMLHTTP'); if (x) { if (x.overrideMimeType) x.overrideMimeType(o.content_type); x.open(o.type || (o.data ? 'POST' : 'GET'), o.url, o.async); if (o.content_type) x.setRequestHeader('Content-Type', o.content_type); x.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); x.send(o.data); // Syncronous request if (!o.async) return ready(); // Wait for response, onReadyStateChange can not be used since it leaks memory in IE t = w.setTimeout(ready, 10); } } }); (function() { var extend = tinymce.extend, JSON = tinymce.util.JSON, XHR = tinymce.util.XHR; tinymce.create('tinymce.util.JSONRequest', { JSONRequest : function(s) { this.settings = extend({ }, s); this.count = 0; }, send : function(o) { var ecb = o.error, scb = o.success; o = extend(this.settings, o); o.success = function(c, x) { c = JSON.parse(c); if (typeof(c) == 'undefined') { c = { error : 'JSON Parse error.' }; } if (c.error) ecb.call(o.error_scope || o.scope, c.error, x); else scb.call(o.success_scope || o.scope, c.result); }; o.error = function(ty, x) { if (ecb) ecb.call(o.error_scope || o.scope, ty, x); }; o.data = JSON.serialize({ id : o.id || 'c' + (this.count++), method : o.method, params : o.params }); // JSON content type for Ruby on rails. Bug: #1883287 o.content_type = 'application/json'; XHR.send(o); }, 'static' : { sendRPC : function(o) { return new tinymce.util.JSONRequest().send(o); } } }); }()); (function(tinymce){ tinymce.VK = { BACKSPACE: 8, DELETE: 46, DOWN: 40, ENTER: 13, LEFT: 37, RIGHT: 39, SPACEBAR: 32, TAB: 9, UP: 38, modifierPressed: function (e) { return e.shiftKey || e.ctrlKey || e.altKey; } }; })(tinymce); tinymce.util.Quirks = function(editor) { var VK = tinymce.VK, BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, settings = editor.settings; function setEditorCommandState(cmd, state) { try { editor.getDoc().execCommand(cmd, false, state); } catch (ex) { // Ignore } } function cleanupStylesWhenDeleting() { function removeMergedFormatSpans(isDelete) { var rng, blockElm, node, clonedSpan; rng = selection.getRng(); // Find root block blockElm = dom.getParent(rng.startContainer, dom.isBlock); // On delete clone the root span of the next block element if (isDelete) blockElm = dom.getNext(blockElm, dom.isBlock); // Locate root span element and clone it since it would otherwise get merged by the "apple-style-span" on delete/backspace if (blockElm) { node = blockElm.firstChild; // Ignore empty text nodes while (node && node.nodeType == 3 && node.nodeValue.length === 0) node = node.nextSibling; if (node && node.nodeName === 'SPAN') { clonedSpan = node.cloneNode(false); } } // Do the backspace/delete action editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); // Find all odd apple-style-spans blockElm = dom.getParent(rng.startContainer, dom.isBlock); tinymce.each(dom.select('span.Apple-style-span,font.Apple-style-span', blockElm), function(span) { var bm = selection.getBookmark(); if (clonedSpan) { dom.replace(clonedSpan.cloneNode(false), span, true); } else { dom.remove(span, true); } // Restore the selection selection.moveToBookmark(bm); }); }; editor.onKeyDown.add(function(editor, e) { var isDelete; if (e.isDefaultPrevented()) { return; } isDelete = e.keyCode == DELETE; if ((isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { e.preventDefault(); removeMergedFormatSpans(isDelete); } }); editor.addCommand('Delete', function() {removeMergedFormatSpans();}); }; function emptyEditorWhenDeleting() { function serializeRng(rng) { var body = dom.create("body"); var contents = rng.cloneContents(); body.appendChild(contents); return selection.serializer.serialize(body, {format: 'html'}); } function allContentsSelected(rng) { var selection = serializeRng(rng); var allRng = dom.createRng(); allRng.selectNode(editor.getBody()); var allSelection = serializeRng(allRng); return selection === allSelection; } editor.onKeyDown.addToTop(function(editor, e) { var keyCode = e.keyCode; if (keyCode == DELETE || keyCode == BACKSPACE) { var rng = selection.getRng(true); if (!rng.collapsed && allContentsSelected(rng)) { editor.setContent('', {format : 'raw'}); editor.nodeChanged(); e.preventDefault(); } } }); }; function inputMethodFocus() { dom.bind(editor.getBody(), 'focusin', function() { selection.setRng(selection.getRng()); }); }; function removeHrOnBackspace() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode === BACKSPACE) { if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { var node = selection.getNode(); var previousSibling = node.previousSibling; if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { dom.remove(previousSibling); tinymce.dom.Event.cancel(e); } } } }) } function focusBody() { // Fix for a focus bug in FF 3.x where the body element // wouldn't get proper focus if the user clicked on the HTML element if (!Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 editor.onMouseDown.add(function(editor, e) { if (e.target.nodeName === "HTML") { var body = editor.getBody(); // Blur the body it's focused but not correctly focused body.blur(); // Refocus the body after a little while setTimeout(function() { body.focus(); }, 0); } }); } }; function selectControlElements() { editor.onClick.add(function(editor, e) { e = e.target; // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 // WebKit can't even do simple things like selecting an image // Needs tobe the setBaseAndExtend or it will fail to select floated images if (/^(IMG|HR)$/.test(e.nodeName)) { selection.getSel().setBaseAndExtent(e, 0, e, 1); } if (e.nodeName == 'A' && dom.hasClass(e, 'mceItemAnchor')) { selection.select(e); } editor.nodeChanged(); }); }; function removeStylesWhenDeletingAccrossBlockElements() { function getAttributeApplyFunction() { var template = dom.getAttribs(selection.getStart().cloneNode(false)); return function() { var target = selection.getStart(); if (target !== editor.getBody()) { dom.setAttrib(target, "style", null); tinymce.each(template, function(attr) { target.setAttributeNode(attr.cloneNode(true)); }); } }; } function isSelectionAcrossElements() { return !selection.isCollapsed() && selection.getStart() != selection.getEnd(); } function blockEvent(editor, e) { e.preventDefault(); return false; } editor.onKeyPress.add(function(editor, e) { var applyAttributes; if ((e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { applyAttributes = getAttributeApplyFunction(); editor.getDoc().execCommand('delete', false, null); applyAttributes(); e.preventDefault(); return false; } }); dom.bind(editor.getDoc(), 'cut', function(e) { var applyAttributes; if (isSelectionAcrossElements()) { applyAttributes = getAttributeApplyFunction(); editor.onKeyUp.addToTop(blockEvent); setTimeout(function() { applyAttributes(); editor.onKeyUp.remove(blockEvent); }, 0); } }); } function selectionChangeNodeChanged() { var lastRng, selectionTimer; dom.bind(editor.getDoc(), 'selectionchange', function() { if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = 0; } selectionTimer = window.setTimeout(function() { var rng = selection.getRng(); // Compare the ranges to see if it was a real change or not if (!lastRng || !tinymce.dom.RangeUtils.compareRanges(rng, lastRng)) { editor.nodeChanged(); lastRng = rng; } }, 50); }); } function ensureBodyHasRoleApplication() { document.body.setAttribute("role", "application"); } function disableBackspaceIntoATable() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode === BACKSPACE) { if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { var previousSibling = selection.getNode().previousSibling; if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { return tinymce.dom.Event.cancel(e); } } } }) } function addNewLinesBeforeBrInPre() { var documentMode = editor.getDoc().documentMode; // IE8+ rendering mode does the right thing with BR in PRE if (documentMode && documentMode > 7) { return; } // Enable display: none in area and add a specific class that hides all BR elements in PRE to // avoid the caret from getting stuck at the BR elements while pressing the right arrow key setEditorCommandState('RespectVisibilityInDesign', true); dom.addClass(editor.getBody(), 'mceHideBrInPre'); // Adds a \n before all BR elements in PRE to get them visual editor.parser.addNodeFilter('pre', function(nodes, name) { var i = nodes.length, brNodes, j, brElm, sibling; while (i--) { brNodes = nodes[i].getAll('br'); j = brNodes.length; while (j--) { brElm = brNodes[j]; // Add \n before BR in PRE elements on older IE:s so the new lines get rendered sibling = brElm.prev; if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { sibling.value += '\n'; } else { brElm.parent.insert(new tinymce.html.Node('#text', 3), brElm, true).value = '\n'; } } } }); // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible editor.serializer.addNodeFilter('pre', function(nodes, name) { var i = nodes.length, brNodes, j, brElm, sibling; while (i--) { brNodes = nodes[i].getAll('br'); j = brNodes.length; while (j--) { brElm = brNodes[j]; sibling = brElm.prev; if (sibling && sibling.type == 3) { sibling.value = sibling.value.replace(/\r?\n$/, ''); } } } }); } function removePreSerializedStylesWhenSelectingControls() { dom.bind(editor.getBody(), 'mouseup', function(e) { var value, node = selection.getNode(); // Moved styles to attributes on IMG eements if (node.nodeName == 'IMG') { // Convert style width to width attribute if (value = dom.getStyle(node, 'width')) { dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); dom.setStyle(node, 'width', ''); } // Convert style height to height attribute if (value = dom.getStyle(node, 'height')) { dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); dom.setStyle(node, 'height', ''); } } }); } function keepInlineElementOnDeleteBackspace() { editor.onKeyDown.add(function(editor, e) { var isDelete, rng, container, offset, brElm, sibling, collapsed; if (e.isDefaultPrevented()) { return; } isDelete = e.keyCode == DELETE; if ((isDelete || e.keyCode == BACKSPACE) && !VK.modifierPressed(e)) { rng = selection.getRng(); container = rng.startContainer; offset = rng.startOffset; collapsed = rng.collapsed; // Override delete if the start container is a text node and is at the beginning of text or // just before/after the last character to be deleted in collapsed mode if (container.nodeType == 3 && container.nodeValue.length > 0 && ((offset === 0 && !collapsed) || (collapsed && offset === (isDelete ? 0 : 1)))) { nonEmptyElements = editor.schema.getNonEmptyElements(); // Prevent default logic since it's broken e.preventDefault(); // Insert a BR before the text node this will prevent the containing element from being deleted/converted brElm = dom.create('br', {id: '__tmp'}); container.parentNode.insertBefore(brElm, container); // Do the browser delete editor.getDoc().execCommand(isDelete ? 'ForwardDelete' : 'Delete', false, null); // Check if the previous sibling is empty after deleting for example: <p><b></b>|</p> container = selection.getRng().startContainer; sibling = container.previousSibling; if (sibling && sibling.nodeType == 1 && !dom.isBlock(sibling) && dom.isEmpty(sibling) && !nonEmptyElements[sibling.nodeName.toLowerCase()]) { dom.remove(sibling); } // Remove the temp element we inserted dom.remove('__tmp'); } } }); } function removeBlockQuoteOnBackSpace() { // Add block quote deletion handler editor.onKeyDown.add(function(editor, e) { var rng, container, offset, root, parent; if (e.keyCode != VK.BACKSPACE) { return; } rng = selection.getRng(); container = rng.startContainer; offset = rng.startOffset; root = dom.getRoot(); parent = container; if (!rng.collapsed || offset !== 0) { return; } while (parent && parent.parentNode.firstChild == parent && parent.parentNode != root) { parent = parent.parentNode; } // Is the cursor at the beginning of a blockquote? if (parent.tagName === 'BLOCKQUOTE') { // Remove the blockquote editor.formatter.toggle('blockquote', null, parent); // Move the caret to the beginning of container rng.setStart(container, 0); rng.setEnd(container, 0); selection.setRng(rng); selection.collapse(false); } }); }; function setGeckoEditingOptions() { function setOpts() { editor._refreshContentEditable(); setEditorCommandState("StyleWithCSS", false); setEditorCommandState("enableInlineTableEditing", false); if (!settings.object_resizing) { setEditorCommandState("enableObjectResizing", false); } }; if (!settings.readonly) { editor.onBeforeExecCommand.add(setOpts); editor.onMouseDown.add(setOpts); } }; function addBrAfterLastLinks() { function fixLinks(editor, o) { tinymce.each(dom.select('a'), function(node) { var parentNode = node.parentNode, root = dom.getRoot(); if (parentNode.lastChild === node) { while (parentNode && !dom.isBlock(parentNode)) { if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { return; } parentNode = parentNode.parentNode; } dom.add(parentNode, 'br', {'data-mce-bogus' : 1}); } }); }; editor.onExecCommand.add(function(editor, cmd) { if (cmd === 'CreateLink') { fixLinks(editor); } }); editor.onSetContent.add(selection.onSetContent.add(fixLinks)); }; function removeGhostSelection() { function repaint(sender, args) { if (!sender || !args.initial) { editor.execCommand('mceRepaint'); } }; editor.onUndo.add(repaint); editor.onRedo.add(repaint); editor.onSetContent.add(repaint); }; function deleteImageOnBackSpace() { editor.onKeyDown.add(function(editor, e) { if (e.keyCode == 8 && selection.getNode().nodeName == 'IMG') { e.preventDefault(); editor.undoManager.beforeChange(); dom.remove(selection.getNode()); editor.undoManager.add(); } }); }; // All browsers disableBackspaceIntoATable(); removeBlockQuoteOnBackSpace(); // WebKit if (tinymce.isWebKit) { keepInlineElementOnDeleteBackspace(); cleanupStylesWhenDeleting(); emptyEditorWhenDeleting(); inputMethodFocus(); selectControlElements(); // iOS if (tinymce.isIDevice) { selectionChangeNodeChanged(); } } // IE if (tinymce.isIE) { removeHrOnBackspace(); emptyEditorWhenDeleting(); ensureBodyHasRoleApplication(); addNewLinesBeforeBrInPre(); removePreSerializedStylesWhenSelectingControls(); deleteImageOnBackSpace(); } // Gecko if (tinymce.isGecko) { removeHrOnBackspace(); focusBody(); removeStylesWhenDeletingAccrossBlockElements(); setGeckoEditingOptions(); addBrAfterLastLinks(); removeGhostSelection(); } }; (function(tinymce) { var namedEntities, baseEntities, reverseEntities, attrsCharsRegExp = /[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, rawCharsRegExp = /[<>&\"\']/g, entityRegExp = /&(#x|#)?([\w]+);/g, asciiMap = { 128 : "\u20AC", 130 : "\u201A", 131 : "\u0192", 132 : "\u201E", 133 : "\u2026", 134 : "\u2020", 135 : "\u2021", 136 : "\u02C6", 137 : "\u2030", 138 : "\u0160", 139 : "\u2039", 140 : "\u0152", 142 : "\u017D", 145 : "\u2018", 146 : "\u2019", 147 : "\u201C", 148 : "\u201D", 149 : "\u2022", 150 : "\u2013", 151 : "\u2014", 152 : "\u02DC", 153 : "\u2122", 154 : "\u0161", 155 : "\u203A", 156 : "\u0153", 158 : "\u017E", 159 : "\u0178" }; // Raw entities baseEntities = { '\"' : '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code "'" : '&#39;', '<' : '&lt;', '>' : '&gt;', '&' : '&amp;' }; // Reverse lookup table for raw entities reverseEntities = { '&lt;' : '<', '&gt;' : '>', '&amp;' : '&', '&quot;' : '"', '&apos;' : "'" }; // Decodes text by using the browser function nativeDecode(text) { var elm; elm = document.createElement("div"); elm.innerHTML = text; return elm.textContent || elm.innerText || text; }; // Build a two way lookup table for the entities function buildEntitiesLookup(items, radix) { var i, chr, entity, lookup = {}; if (items) { items = items.split(','); radix = radix || 10; // Build entities lookup table for (i = 0; i < items.length; i += 2) { chr = String.fromCharCode(parseInt(items[i], radix)); // Only add non base entities if (!baseEntities[chr]) { entity = '&' + items[i + 1] + ';'; lookup[chr] = entity; lookup[entity] = chr; } } return lookup; } }; // Unpack entities lookup where the numbers are in radix 32 to reduce the size namedEntities = buildEntitiesLookup( '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32); tinymce.html = tinymce.html || {}; tinymce.html.Entities = { encodeRaw : function(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || chr; }); }, encodeAllRaw : function(text) { return ('' + text).replace(rawCharsRegExp, function(chr) { return baseEntities[chr] || chr; }); }, encodeNumeric : function(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { // Multi byte sequence convert it to a single entity if (chr.length > 1) return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';'; return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';'; }); }, encodeNamed : function(text, attr, entities) { entities = entities || namedEntities; return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || entities[chr] || chr; }); }, getEncodeFunc : function(name, entities) { var Entities = tinymce.html.Entities; entities = buildEntitiesLookup(entities) || namedEntities; function encodeNamedAndNumeric(text, attr) { return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr; }); }; function encodeCustomNamed(text, attr) { return Entities.encodeNamed(text, attr, entities); }; // Replace + with , to be compatible with previous TinyMCE versions name = tinymce.makeMap(name.replace(/\+/g, ',')); // Named and numeric encoder if (name.named && name.numeric) return encodeNamedAndNumeric; // Named encoder if (name.named) { // Custom names if (entities) return encodeCustomNamed; return Entities.encodeNamed; } // Numeric if (name.numeric) return Entities.encodeNumeric; // Raw encoder return Entities.encodeRaw; }, decode : function(text) { return text.replace(entityRegExp, function(all, numeric, value) { if (numeric) { value = parseInt(value, numeric.length === 2 ? 16 : 10); // Support upper UTF if (value > 0xFFFF) { value -= 0x10000; return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF)); } else return asciiMap[value] || String.fromCharCode(value); } return reverseEntities[all] || namedEntities[all] || nativeDecode(all); }); } }; })(tinymce); tinymce.html.Styles = function(settings, schema) { var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi, urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi, styleRegExp = /\s*([^:]+):\s*([^;]+);?/g, trimRightRegExp = /\s+$/, urlColorRegExp = /rgb/, undef, i, encodingLookup = {}, encodingItems; settings = settings || {}; encodingItems = '\\" \\\' \\; \\: ; : \uFEFF'.split(' '); for (i = 0; i < encodingItems.length; i++) { encodingLookup[encodingItems[i]] = '\uFEFF' + i; encodingLookup['\uFEFF' + i] = encodingItems[i]; } function toHex(match, r, g, b) { function hex(val) { val = parseInt(val).toString(16); return val.length > 1 ? val : '0' + val; // 0 -> 00 }; return '#' + hex(r) + hex(g) + hex(b); }; return { toHex : function(color) { return color.replace(rgbRegExp, toHex); }, parse : function(css) { var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope || this; function compress(prefix, suffix) { var top, right, bottom, left; // Get values and check it it needs compressing top = styles[prefix + '-top' + suffix]; if (!top) return; right = styles[prefix + '-right' + suffix]; if (top != right) return; bottom = styles[prefix + '-bottom' + suffix]; if (right != bottom) return; left = styles[prefix + '-left' + suffix]; if (bottom != left) return; // Compress styles[prefix + suffix] = left; delete styles[prefix + '-top' + suffix]; delete styles[prefix + '-right' + suffix]; delete styles[prefix + '-bottom' + suffix]; delete styles[prefix + '-left' + suffix]; }; function canCompress(key) { var value = styles[key], i; if (!value || value.indexOf(' ') < 0) return; value = value.split(' '); i = value.length; while (i--) { if (value[i] !== value[0]) return false; } styles[key] = value[0]; return true; }; function compress2(target, a, b, c) { if (!canCompress(a)) return; if (!canCompress(b)) return; if (!canCompress(c)) return; // Compress styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c]; delete styles[a]; delete styles[b]; delete styles[c]; }; // Encodes the specified string by replacing all \" \' ; : with _<num> function encode(str) { isEncoded = true; return encodingLookup[str]; }; // Decodes the specified string by replacing all _<num> with it's original value \" \' etc // It will also decode the \" \' if keep_slashes is set to fale or omitted function decode(str, keep_slashes) { if (isEncoded) { str = str.replace(/\uFEFF[0-9]/g, function(str) { return encodingLookup[str]; }); } if (!keep_slashes) str = str.replace(/\\([\'\";:])/g, "$1"); return str; }; function processUrl(match, url, url2, url3, str, str2) { str = str || str2; if (str) { str = decode(str); // Force strings into single quote format return "'" + str.replace(/\'/g, "\\'") + "'"; } url = decode(url || url2 || url3); // Convert the URL to relative/absolute depending on config if (urlConverter) url = urlConverter.call(urlConverterScope, url, 'style'); // Output new URL format return "url('" + url.replace(/\'/g, "\\'") + "')"; }; if (css) { // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) { return str.replace(/[;:]/g, encode); }); // Parse styles while (matches = styleRegExp.exec(css)) { name = matches[1].replace(trimRightRegExp, '').toLowerCase(); value = matches[2].replace(trimRightRegExp, ''); if (name && value.length > 0) { // Opera will produce 700 instead of bold in their style values if (name === 'font-weight' && value === '700') value = 'bold'; else if (name === 'color' || name === 'background-color') // Lowercase colors like RED value = value.toLowerCase(); // Convert RGB colors to HEX value = value.replace(rgbRegExp, toHex); // Convert URLs and force them into url('value') format value = value.replace(urlOrStrRegExp, processUrl); styles[name] = isEncoded ? decode(value, true) : value; } styleRegExp.lastIndex = matches.index + matches[0].length; } // Compress the styles to reduce it's size for example IE will expand styles compress("border", ""); compress("border", "-width"); compress("border", "-color"); compress("border", "-style"); compress("padding", ""); compress("margin", ""); compress2('border', 'border-width', 'border-style', 'border-color'); // Remove pointless border, IE produces these if (styles.border === 'medium none') delete styles.border; } return styles; }, serialize : function(styles, element_name) { var css = '', name, value; function serializeStyles(name) { var styleList, i, l, value; styleList = schema.styles[name]; if (styleList) { for (i = 0, l = styleList.length; i < l; i++) { name = styleList[i]; value = styles[name]; if (value !== undef && value.length > 0) css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'; } } }; // Serialize styles according to schema if (element_name && schema && schema.styles) { // Serialize global styles and element specific styles serializeStyles('*'); serializeStyles(element_name); } else { // Output the styles in the order they are inside the object for (name in styles) { value = styles[name]; if (value !== undef && value.length > 0) css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';'; } } return css; } }; }; (function(tinymce) { var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each; function split(str, delim) { return str.split(delim || ','); }; function unpack(lookup, data) { var key, elements = {}; function replace(value) { return value.replace(/[A-Z]+/g, function(key) { return replace(lookup[key]); }); }; // Unpack lookup for (key in lookup) { if (lookup.hasOwnProperty(key)) lookup[key] = replace(lookup[key]); } // Unpack and parse data into object map replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) { attributes = split(attributes, '|'); elements[name] = { attributes : makeMap(attributes), attributesOrder : attributes, children : makeMap(children, '|', {'#comment' : {}}) } }); return elements; }; function getHTML5() { var html5 = mapCache.html5; if (!html5) { html5 = mapCache.html5 = unpack({ A : 'id|accesskey|class|dir|draggable|item|hidden|itemprop|role|spellcheck|style|subject|title', B : '#|a|abbr|area|audio|b|bdo|br|button|canvas|cite|code|command|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|meta|meter|noscript|object|output|progress|q|ruby|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|var|video', C : '#|a|abbr|area|address|article|aside|audio|b|bdo|blockquote|br|button|canvas|cite|code|command|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|ul|var|video' }, 'html[A|manifest][body|head]' + 'head[A][base|command|link|meta|noscript|script|style|title]' + 'title[A][#]' + 'base[A|href|target][]' + 'link[A|href|rel|media|type|sizes][]' + 'meta[A|http-equiv|name|content|charset][]' + 'style[A|type|media|scoped][#]' + 'script[A|charset|type|src|defer|async][#]' + 'noscript[A][C]' + 'body[A][C]' + 'section[A][C]' + 'nav[A][C]' + 'article[A][C]' + 'aside[A][C]' + 'h1[A][B]' + 'h2[A][B]' + 'h3[A][B]' + 'h4[A][B]' + 'h5[A][B]' + 'h6[A][B]' + 'hgroup[A][h1|h2|h3|h4|h5|h6]' + 'header[A][C]' + 'footer[A][C]' + 'address[A][C]' + 'p[A][B]' + 'br[A][]' + 'pre[A][B]' + 'dialog[A][dd|dt]' + 'blockquote[A|cite][C]' + 'ol[A|start|reversed][li]' + 'ul[A][li]' + 'li[A|value][C]' + 'dl[A][dd|dt]' + 'dt[A][B]' + 'dd[A][C]' + 'a[A|href|target|ping|rel|media|type][C]' + 'em[A][B]' + 'strong[A][B]' + 'small[A][B]' + 'cite[A][B]' + 'q[A|cite][B]' + 'dfn[A][B]' + 'abbr[A][B]' + 'code[A][B]' + 'var[A][B]' + 'samp[A][B]' + 'kbd[A][B]' + 'sub[A][B]' + 'sup[A][B]' + 'i[A][B]' + 'b[A][B]' + 'mark[A][B]' + 'progress[A|value|max][B]' + 'meter[A|value|min|max|low|high|optimum][B]' + 'time[A|datetime][B]' + 'ruby[A][B|rt|rp]' + 'rt[A][B]' + 'rp[A][B]' + 'bdo[A][B]' + 'span[A][B]' + 'ins[A|cite|datetime][B]' + 'del[A|cite|datetime][B]' + 'figure[A][C|legend|figcaption]' + 'figcaption[A][C]' + 'img[A|alt|src|height|width|usemap|ismap][]' + 'iframe[A|name|src|height|width|sandbox|seamless][]' + 'embed[A|src|height|width|type][]' + 'object[A|data|type|height|width|usemap|name|form|classid][param]' + 'param[A|name|value][]' + 'details[A|open][C|legend]' + 'command[A|type|label|icon|disabled|checked|radiogroup][]' + 'menu[A|type|label][C|li]' + 'legend[A][C|B]' + 'div[A][C]' + 'source[A|src|type|media][]' + 'audio[A|src|autobuffer|autoplay|loop|controls][source]' + 'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster][source]' + 'hr[A][]' + 'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' + 'fieldset[A|disabled|form|name][C|legend]' + 'label[A|form|for][B]' + 'input[A|type|accept|alt|autocomplete|checked|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|list|max|maxlength|min|multiple|pattern|placeholder|readonly|required|size|src|step|width|files|value][]' + 'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|value|type][B]' + 'select[A|autofocus|disabled|form|multiple|name|size][option|optgroup]' + 'datalist[A][B|option]' + 'optgroup[A|disabled|label][option]' + 'option[A|disabled|selected|label|value][]' + 'textarea[A|autofocus|disabled|form|maxlength|name|placeholder|readonly|required|rows|cols|wrap][]' + 'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' + 'output[A|for|form|name][B]' + 'canvas[A|width|height][]' + 'map[A|name][B|C]' + 'area[A|shape|coords|href|alt|target|media|rel|ping|type][]' + 'mathml[A][]' + 'svg[A][]' + 'table[A|summary][caption|colgroup|thead|tfoot|tbody|tr]' + 'caption[A][C]' + 'colgroup[A|span][col]' + 'col[A|span][]' + 'thead[A][tr]' + 'tfoot[A][tr]' + 'tbody[A][tr]' + 'tr[A][th|td]' + 'th[A|headers|rowspan|colspan|scope][B]' + 'td[A|headers|rowspan|colspan][C]' ); } return html5; }; function getHTML4() { var html4 = mapCache.html4; if (!html4) { // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size html4 = mapCache.html4 = unpack({ Z : 'H|K|N|O|P', Y : 'X|form|R|Q', ZG : 'E|span|width|align|char|charoff|valign', X : 'p|T|div|U|W|isindex|fieldset|table', ZF : 'E|align|char|charoff|valign', W : 'pre|hr|blockquote|address|center|noframes', ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height', ZD : '[E][S]', U : 'ul|ol|dl|menu|dir', ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q', T : 'h1|h2|h3|h4|h5|h6', ZB : 'X|S|Q', S : 'R|P', ZA : 'a|G|J|M|O|P', R : 'a|H|K|N|O', Q : 'noscript|P', P : 'ins|del|script', O : 'input|select|textarea|label|button', N : 'M|L', M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym', L : 'sub|sup', K : 'J|I', J : 'tt|i|b|u|s|strike', I : 'big|small|font|basefont', H : 'G|F', G : 'br|span|bdo', F : 'object|applet|img|map|iframe', E : 'A|B|C', D : 'accesskey|tabindex|onfocus|onblur', C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : 'lang|xml:lang|dir', A : 'id|class|style|title' }, 'script[id|charset|type|language|src|defer|xml:space][]' + 'style[B|id|type|media|title|xml:space][]' + 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 'param[id|name|value|valuetype|type][]' + 'p[E|align][#|S]' + 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 'br[A|clear][]' + 'span[E][#|S]' + 'bdo[A|C|B][#|S]' + 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 'h1[E|align][#|S]' + 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 'map[B|C|A|name][X|form|Q|area]' + 'h2[E|align][#|S]' + 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 'h3[E|align][#|S]' + 'tt[E][#|S]' + 'i[E][#|S]' + 'b[E][#|S]' + 'u[E][#|S]' + 's[E][#|S]' + 'strike[E][#|S]' + 'big[E][#|S]' + 'small[E][#|S]' + 'font[A|B|size|color|face][#|S]' + 'basefont[id|size|color|face][]' + 'em[E][#|S]' + 'strong[E][#|S]' + 'dfn[E][#|S]' + 'code[E][#|S]' + 'q[E|cite][#|S]' + 'samp[E][#|S]' + 'kbd[E][#|S]' + 'var[E][#|S]' + 'cite[E][#|S]' + 'abbr[E][#|S]' + 'acronym[E][#|S]' + 'sub[E][#|S]' + 'sup[E][#|S]' + 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 'optgroup[E|disabled|label][option]' + 'option[E|selected|disabled|label|value][]' + 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 'label[E|for|accesskey|onfocus|onblur][#|S]' + 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 'h4[E|align][#|S]' + 'ins[E|cite|datetime][#|Y]' + 'h5[E|align][#|S]' + 'del[E|cite|datetime][#|Y]' + 'h6[E|align][#|S]' + 'div[E|align][#|Y]' + 'ul[E|type|compact][li]' + 'li[E|type|value][#|Y]' + 'ol[E|type|compact|start][li]' + 'dl[E|compact][dt|dd]' + 'dt[E][#|S]' + 'dd[E][#|Y]' + 'menu[E|compact][li]' + 'dir[E|compact][li]' + 'pre[E|width|xml:space][#|ZA]' + 'hr[E|align|noshade|size|width][]' + 'blockquote[E|cite][#|Y]' + 'address[E][#|S|p]' + 'center[E][#|Y]' + 'noframes[E][#|Y]' + 'isindex[A|B|prompt][]' + 'fieldset[E][#|legend|Y]' + 'legend[E|accesskey|align][#|S]' + 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 'caption[E|align][#|S]' + 'col[ZG][]' + 'colgroup[ZG][col]' + 'thead[ZF][tr]' + 'tr[ZF|bgcolor][th|td]' + 'th[E|ZE][#|Y]' + 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 'noscript[E][#|Y]' + 'td[E|ZE][#|Y]' + 'tfoot[ZF][tr]' + 'tbody[ZF][tr]' + 'area[E|D|shape|coords|href|nohref|alt|target][]' + 'base[id|href|target][]' + 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]' ); } return html4; }; tinymce.html.Schema = function(settings) { var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {}; // Creates an lookup table map object for the specified option or the default value function createLookupTable(option, default_value, extend) { var value = settings[option]; if (!value) { // Get cached default map or make it if needed value = mapCache[option]; if (!value) { value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' ')); value = tinymce.extend(value, extend); mapCache[option] = value; } } else { // Create custom map value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); } return value; }; settings = settings || {}; schemaItems = settings.schema == "html5" ? getHTML5() : getHTML4(); // Allow all elements and attributes if verify_html is set to false if (settings.verify_html === false) settings.valid_elements = '*[*]'; // Build styles list if (settings.valid_styles) { validStyles = {}; // Convert styles into a rule list each(settings.valid_styles, function(value, key) { validStyles[key] = tinymce.explode(value); }); } // Setup map objects whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script style textarea'); selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li options p td tfoot th thead tr'); shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source'); boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls'); nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); blockElementsMap = createLookupTable('block_elements', 'h1 h2 h3 h4 h5 h6 hr p div address pre form table tbody thead tfoot ' + 'th tr td li ol ul caption blockquote center dl dt dd dir fieldset ' + 'noscript menu isindex samp header footer article section hgroup aside nav figure'); // Converts a wildcard expression string to a regexp for example *a will become /.*a/. function patternToRegExp(str) { return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$'); }; // Parses the specified valid_elements string and adds to the current rules // This function is a bit hard to read since it's heavily optimized for speed function addValidElements(valid_elements) { var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value, elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/; if (valid_elements) { // Split valid elements into an array with rules valid_elements = split(valid_elements); if (elements['@']) { globalAttributes = elements['@'].attributes; globalAttributesOrder = elements['@'].attributesOrder; } // Loop all rules for (ei = 0, el = valid_elements.length; ei < el; ei++) { // Parse element rule matches = elementRuleRegExp.exec(valid_elements[ei]); if (matches) { // Setup local names for matches prefix = matches[1]; elementName = matches[2]; outputName = matches[3]; attrData = matches[4]; // Create new attributes and attributesOrder attributes = {}; attributesOrder = []; // Create the new element element = { attributes : attributes, attributesOrder : attributesOrder }; // Padd empty elements prefix if (prefix === '#') element.paddEmpty = true; // Remove empty elements prefix if (prefix === '-') element.removeEmpty = true; // Copy attributes from global rule into current rule if (globalAttributes) { for (key in globalAttributes) attributes[key] = globalAttributes[key]; attributesOrder.push.apply(attributesOrder, globalAttributesOrder); } // Attributes defined if (attrData) { attrData = split(attrData, '|'); for (ai = 0, al = attrData.length; ai < al; ai++) { matches = attrRuleRegExp.exec(attrData[ai]); if (matches) { attr = {}; attrType = matches[1]; attrName = matches[2].replace(/::/g, ':'); prefix = matches[3]; value = matches[4]; // Required if (attrType === '!') { element.attributesRequired = element.attributesRequired || []; element.attributesRequired.push(attrName); attr.required = true; } // Denied from global if (attrType === '-') { delete attributes[attrName]; attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1); continue; } // Default value if (prefix) { // Default value if (prefix === '=') { element.attributesDefault = element.attributesDefault || []; element.attributesDefault.push({name: attrName, value: value}); attr.defaultValue = value; } // Forced value if (prefix === ':') { element.attributesForced = element.attributesForced || []; element.attributesForced.push({name: attrName, value: value}); attr.forcedValue = value; } // Required values if (prefix === '<') attr.validValues = makeMap(value, '?'); } // Check for attribute patterns if (hasPatternsRegExp.test(attrName)) { element.attributePatterns = element.attributePatterns || []; attr.pattern = patternToRegExp(attrName); element.attributePatterns.push(attr); } else { // Add attribute to order list if it doesn't already exist if (!attributes[attrName]) attributesOrder.push(attrName); attributes[attrName] = attr; } } } } // Global rule, store away these for later usage if (!globalAttributes && elementName == '@') { globalAttributes = attributes; globalAttributesOrder = attributesOrder; } // Handle substitute elements such as b/strong if (outputName) { element.outputName = elementName; elements[outputName] = element; } // Add pattern or exact element if (hasPatternsRegExp.test(elementName)) { element.pattern = patternToRegExp(elementName); patternElements.push(element); } else elements[elementName] = element; } } } }; function setValidElements(valid_elements) { elements = {}; patternElements = []; addValidElements(valid_elements); each(schemaItems, function(element, name) { children[name] = element.children; }); }; // Adds custom non HTML elements to the schema function addCustomElements(custom_elements) { var customElementRegExp = /^(~)?(.+)$/; if (custom_elements) { each(split(custom_elements), function(rule) { var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2]; children[name] = children[cloneName]; customElementsMap[name] = cloneName; // If it's not marked as inline then add it to valid block elements if (!inline) blockElementsMap[name] = {}; // Add custom elements at span/div positions each(children, function(element, child) { if (element[cloneName]) element[name] = element[cloneName]; }); }); } }; // Adds valid children to the schema object function addValidChildren(valid_children) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; if (valid_children) { each(split(valid_children), function(rule) { var matches = childRuleRegExp.exec(rule), parent, prefix; if (matches) { prefix = matches[1]; // Add/remove items from default if (prefix) parent = children[matches[2]]; else parent = children[matches[2]] = {'#comment' : {}}; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { if (prefix === '-') delete parent[child]; else parent[child] = {}; }); } }); } }; function getElementRule(name) { var element = elements[name], i; // Exact match found if (element) return element; // No exact match then try the patterns i = patternElements.length; while (i--) { element = patternElements[i]; if (element.pattern.test(name)) return element; } }; if (!settings.valid_elements) { // No valid elements defined then clone the elements from the schema spec each(schemaItems, function(element, name) { elements[name] = { attributes : element.attributes, attributesOrder : element.attributesOrder }; children[name] = element.children; }); // Switch these on HTML4 if (settings.schema != "html5") { each(split('strong/b,em/i'), function(item) { item = split(item, '/'); elements[item[1]].outputName = item[0]; }); } // Add default alt attribute for images elements.img.attributesDefault = [{name: 'alt', value: ''}]; // Remove these if they are empty by default each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr,strong,em,b,i'), function(name) { if (elements[name]) { elements[name].removeEmpty = true; } }); // Padd these by default each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) { elements[name].paddEmpty = true; }); } else setValidElements(settings.valid_elements); addCustomElements(settings.custom_elements); addValidChildren(settings.valid_children); addValidElements(settings.extended_valid_elements); // Todo: Remove this when we fix list handling to be valid addValidChildren('+ol[ul|ol],+ul[ul|ol]'); // Delete invalid elements if (settings.invalid_elements) { tinymce.each(tinymce.explode(settings.invalid_elements), function(item) { if (elements[item]) delete elements[item]; }); } // If the user didn't allow span only allow internal spans if (!getElementRule('span')) addValidElements('span[!data-mce-type|*]'); self.children = children; self.styles = validStyles; self.getBoolAttrs = function() { return boolAttrMap; }; self.getBlockElements = function() { return blockElementsMap; }; self.getShortEndedElements = function() { return shortEndedElementsMap; }; self.getSelfClosingElements = function() { return selfClosingElementsMap; }; self.getNonEmptyElements = function() { return nonEmptyElementsMap; }; self.getWhiteSpaceElements = function() { return whiteSpaceElementsMap; }; self.isValidChild = function(name, child) { var parent = children[name]; return !!(parent && parent[child]); }; self.getElementRule = getElementRule; self.getCustomElements = function() { return customElementsMap; }; self.addValidElements = addValidElements; self.setValidElements = setValidElements; self.addCustomElements = addCustomElements; self.addValidChildren = addValidChildren; }; })(tinymce); (function(tinymce) { tinymce.html.SaxParser = function(settings, schema) { var self = this, noop = function() {}; settings = settings || {}; self.schema = schema = schema || new tinymce.html.Schema(); if (settings.fix_self_closing !== false) settings.fix_self_closing = true; // Add handler functions from settings and setup default handlers tinymce.each('comment cdata text start end pi doctype'.split(' '), function(name) { if (name) self[name] = settings[name] || noop; }); self.parse = function(html) { var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name, isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded, validate, elementRule, isValidElement, attr, attribsValue, invalidPrefixRegExp, validAttributesMap, validAttributePatterns, attributesRequired, attributesDefault, attributesForced, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0, decode = tinymce.html.Entities.decode, fixSelfClosing, isIE; function processEndTag(name) { var pos, i; // Find position of parent of the same type pos = stack.length; while (pos--) { if (stack[pos].name === name) break; } // Found parent if (pos >= 0) { // Close all the open elements for (i = stack.length - 1; i >= pos; i--) { name = stack[i]; if (name.valid) self.end(name.name); } // Remove the open elements from the stack stack.length = pos; } }; function parseAttribute(match, name, value, val2, val3) { var attrRule, i; name = name.toLowerCase(); value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute // Validate name and value if (validate && !isInternalElement && name.indexOf('data-') !== 0) { attrRule = validAttributesMap[name]; // Find rule by pattern matching if (!attrRule && validAttributePatterns) { i = validAttributePatterns.length; while (i--) { attrRule = validAttributePatterns[i]; if (attrRule.pattern.test(name)) break; } // No rule matched if (i === -1) attrRule = null; } // No attribute rule found if (!attrRule) return; // Validate value if (attrRule.validValues && !(value in attrRule.validValues)) return; } // Add attribute to list and map attrList.map[name] = value; attrList.push({ name: name, value: value }); }; // Precompile RegExps and map objects tokenRegExp = new RegExp('<(?:' + '(?:!--([\\w\\W]*?)-->)|' + // Comment '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI '(?:\\/([^>]+)>)|' + // End element '(?:([A-Za-z0-9\\-\\:]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + // Start element ')', 'g'); attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:\\.|[^\"])*)\")|(?:\'((?:\\.|[^\'])*)\')|([^>\s]+)))?/g; specialElements = { 'script' : /<\/script[^>]*>/gi, 'style' : /<\/style[^>]*>/gi, 'noscript' : /<\/noscript[^>]*>/gi }; // Setup lookup tables for empty elements and boolean attributes shortEndedElements = schema.getShortEndedElements(); selfClosing = schema.getSelfClosingElements(); fillAttrsMap = schema.getBoolAttrs(); validate = settings.validate; removeInternalElements = settings.remove_internals; fixSelfClosing = settings.fix_self_closing; isIE = tinymce.isIE; invalidPrefixRegExp = /^:/; while (matches = tokenRegExp.exec(html)) { // Text if (index < matches.index) self.text(decode(html.substr(index, matches.index - index))); if (value = matches[6]) { // End element value = value.toLowerCase(); // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements if (isIE && invalidPrefixRegExp.test(value)) value = value.substr(1); processEndTag(value); } else if (value = matches[7]) { // Start element value = value.toLowerCase(); // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements if (isIE && invalidPrefixRegExp.test(value)) value = value.substr(1); isShortEnded = value in shortEndedElements; // Is self closing tag for example an <li> after an open <li> if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) processEndTag(value); // Validate element if (!validate || (elementRule = schema.getElementRule(value))) { isValidElement = true; // Grab attributes map and patters when validation is enabled if (validate) { validAttributesMap = elementRule.attributes; validAttributePatterns = elementRule.attributePatterns; } // Parse attributes if (attribsValue = matches[8]) { isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element // If the element has internal attributes then remove it if we are told to do so if (isInternalElement && removeInternalElements) isValidElement = false; attrList = []; attrList.map = {}; attribsValue.replace(attrRegExp, parseAttribute); } else { attrList = []; attrList.map = {}; } // Process attributes if validation is enabled if (validate && !isInternalElement) { attributesRequired = elementRule.attributesRequired; attributesDefault = elementRule.attributesDefault; attributesForced = elementRule.attributesForced; // Handle forced attributes if (attributesForced) { i = attributesForced.length; while (i--) { attr = attributesForced[i]; name = attr.name; attrValue = attr.value; if (attrValue === '{$uid}') attrValue = 'mce_' + idCount++; attrList.map[name] = attrValue; attrList.push({name: name, value: attrValue}); } } // Handle default attributes if (attributesDefault) { i = attributesDefault.length; while (i--) { attr = attributesDefault[i]; name = attr.name; if (!(name in attrList.map)) { attrValue = attr.value; if (attrValue === '{$uid}') attrValue = 'mce_' + idCount++; attrList.map[name] = attrValue; attrList.push({name: name, value: attrValue}); } } } // Handle required attributes if (attributesRequired) { i = attributesRequired.length; while (i--) { if (attributesRequired[i] in attrList.map) break; } // None of the required attributes where found if (i === -1) isValidElement = false; } // Invalidate element if it's marked as bogus if (attrList.map['data-mce-bogus']) isValidElement = false; } if (isValidElement) self.start(value, attrList, isShortEnded); } else isValidElement = false; // Treat script, noscript and style a bit different since they may include code that looks like elements if (endRegExp = specialElements[value]) { endRegExp.lastIndex = index = matches.index + matches[0].length; if (matches = endRegExp.exec(html)) { if (isValidElement) text = html.substr(index, matches.index - index); index = matches.index + matches[0].length; } else { text = html.substr(index); index = html.length; } if (isValidElement && text.length > 0) self.text(text, true); if (isValidElement) self.end(value); tokenRegExp.lastIndex = index; continue; } // Push value on to stack if (!isShortEnded) { if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1) stack.push({name: value, valid: isValidElement}); else if (isValidElement) self.end(value); } } else if (value = matches[1]) { // Comment self.comment(value); } else if (value = matches[2]) { // CDATA self.cdata(value); } else if (value = matches[3]) { // DOCTYPE self.doctype(value); } else if (value = matches[4]) { // PI self.pi(value, matches[5]); } index = matches.index + matches[0].length; } // Text if (index < html.length) self.text(decode(html.substr(index))); // Close any open elements for (i = stack.length - 1; i >= 0; i--) { value = stack[i]; if (value.valid) self.end(value.name); } }; } })(tinymce); (function(tinymce) { var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { '#text' : 3, '#comment' : 8, '#cdata' : 4, '#pi' : 7, '#doctype' : 10, '#document-fragment' : 11 }; // Walks the tree left/right function walk(node, root_node, prev) { var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; // Walk into nodes if it has a start if (node[startName]) return node[startName]; // Return the sibling if it has one if (node !== root_node) { sibling = node[siblingName]; if (sibling) return sibling; // Walk up the parents to look for siblings for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { sibling = parent[siblingName]; if (sibling) return sibling; } } }; function Node(name, type) { this.name = name; this.type = type; if (type === 1) { this.attributes = []; this.attributes.map = {}; } } tinymce.extend(Node.prototype, { replace : function(node) { var self = this; if (node.parent) node.remove(); self.insert(node, self); self.remove(); return self; }, attr : function(name, value) { var self = this, attrs, i, undef; if (typeof name !== "string") { for (i in name) self.attr(i, name[i]); return self; } if (attrs = self.attributes) { if (value !== undef) { // Remove attribute if (value === null) { if (name in attrs.map) { delete attrs.map[name]; i = attrs.length; while (i--) { if (attrs[i].name === name) { attrs = attrs.splice(i, 1); return self; } } } return self; } // Set attribute if (name in attrs.map) { // Set attribute i = attrs.length; while (i--) { if (attrs[i].name === name) { attrs[i].value = value; break; } } } else attrs.push({name: name, value: value}); attrs.map[name] = value; return self; } else { return attrs.map[name]; } } }, clone : function() { var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; // Clone element attributes if (selfAttrs = self.attributes) { cloneAttrs = []; cloneAttrs.map = {}; for (i = 0, l = selfAttrs.length; i < l; i++) { selfAttr = selfAttrs[i]; // Clone everything except id if (selfAttr.name !== 'id') { cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; cloneAttrs.map[selfAttr.name] = selfAttr.value; } } clone.attributes = cloneAttrs; } clone.value = self.value; clone.shortEnded = self.shortEnded; return clone; }, wrap : function(wrapper) { var self = this; self.parent.insert(wrapper, self); wrapper.append(self); return self; }, unwrap : function() { var self = this, node, next; for (node = self.firstChild; node; ) { next = node.next; self.insert(node, self, true); node = next; } self.remove(); }, remove : function() { var self = this, parent = self.parent, next = self.next, prev = self.prev; if (parent) { if (parent.firstChild === self) { parent.firstChild = next; if (next) next.prev = null; } else { prev.next = next; } if (parent.lastChild === self) { parent.lastChild = prev; if (prev) prev.next = null; } else { next.prev = prev; } self.parent = self.next = self.prev = null; } return self; }, append : function(node) { var self = this, last; if (node.parent) node.remove(); last = self.lastChild; if (last) { last.next = node; node.prev = last; self.lastChild = node; } else self.lastChild = self.firstChild = node; node.parent = self; return node; }, insert : function(node, ref_node, before) { var parent; if (node.parent) node.remove(); parent = ref_node.parent || this; if (before) { if (ref_node === parent.firstChild) parent.firstChild = node; else ref_node.prev.next = node; node.prev = ref_node.prev; node.next = ref_node; ref_node.prev = node; } else { if (ref_node === parent.lastChild) parent.lastChild = node; else ref_node.next.prev = node; node.next = ref_node.next; node.prev = ref_node; ref_node.next = node; } node.parent = parent; return node; }, getAll : function(name) { var self = this, node, collection = []; for (node = self.firstChild; node; node = walk(node, self)) { if (node.name === name) collection.push(node); } return collection; }, empty : function() { var self = this, nodes, i, node; // Remove all children if (self.firstChild) { nodes = []; // Collect the children for (node = self.firstChild; node; node = walk(node, self)) nodes.push(node); // Remove the children i = nodes.length; while (i--) { node = nodes[i]; node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; } } self.firstChild = self.lastChild = null; return self; }, isEmpty : function(elements) { var self = this, node = self.firstChild, i, name; if (node) { do { if (node.type === 1) { // Ignore bogus elements if (node.attributes.map['data-mce-bogus']) continue; // Keep empty elements like <img /> if (elements[node.name]) return false; // Keep elements with data attributes or name attribute like <a name="1"></a> i = node.attributes.length; while (i--) { name = node.attributes[i].name; if (name === "name" || name.indexOf('data-') === 0) return false; } } // Keep comments if (node.type === 8) return false; // Keep non whitespace text nodes if ((node.type === 3 && !whiteSpaceRegExp.test(node.value))) return false; } while (node = walk(node, self)); } return true; }, walk : function(prev) { return walk(this, null, prev); } }); tinymce.extend(Node, { create : function(name, attrs) { var node, attrName; // Create node node = new Node(name, typeLookup[name] || 1); // Add attributes if needed if (attrs) { for (attrName in attrs) node.attr(attrName, attrs[attrName]); } return node; } }); tinymce.html.Node = Node; })(tinymce); (function(tinymce) { var Node = tinymce.html.Node; tinymce.html.DomParser = function(settings, schema) { var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {}; settings = settings || {}; settings.validate = "validate" in settings ? settings.validate : true; settings.root_name = settings.root_name || 'body'; self.schema = schema = schema || new tinymce.html.Schema(); function fixInvalidChildren(nodes) { var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i, childClone, nonEmptyElements, nonSplitableElements, sibling, nextNode; nonSplitableElements = tinymce.makeMap('tr,td,th,tbody,thead,tfoot,table'); nonEmptyElements = schema.getNonEmptyElements(); for (ni = 0; ni < nodes.length; ni++) { node = nodes[ni]; // Already removed if (!node.parent) continue; // Get list of all parent nodes until we find a valid parent to stick the child into parents = [node]; for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) && !nonSplitableElements[parent.name]; parent = parent.parent) parents.push(parent); // Found a suitable parent if (parent && parents.length > 1) { // Reverse the array since it makes looping easier parents.reverse(); // Clone the related parent and insert that after the moved node newParent = currentNode = self.filterNode(parents[0].clone()); // Start cloning and moving children on the left side of the target node for (i = 0; i < parents.length - 1; i++) { if (schema.isValidChild(currentNode.name, parents[i].name)) { tempNode = self.filterNode(parents[i].clone()); currentNode.append(tempNode); } else tempNode = currentNode; for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) { nextNode = childNode.next; tempNode.append(childNode); childNode = nextNode; } currentNode = tempNode; } if (!newParent.isEmpty(nonEmptyElements)) { parent.insert(newParent, parents[0], true); parent.insert(node, newParent); } else { parent.insert(node, parents[0], true); } // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p> parent = parents[0]; if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') { parent.empty().remove(); } } else if (node.parent) { // If it's an LI try to find a UL/OL for it or wrap it if (node.name === 'li') { sibling = node.prev; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.append(node); continue; } sibling = node.next; if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) { sibling.insert(node, sibling.firstChild, true); continue; } node.wrap(self.filterNode(new Node('ul', 1))); continue; } // Try wrapping the element in a DIV if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) { node.wrap(self.filterNode(new Node('div', 1))); } else { // We failed wrapping it, then remove or unwrap it if (node.name === 'style' || node.name === 'script') node.empty().remove(); else node.unwrap(); } } } }; self.filterNode = function(node) { var i, name, list; // Run element filters if (name in nodeFilters) { list = matchedNodes[name]; if (list) list.push(node); else matchedNodes[name] = [node]; } // Run attribute filters i = attributeFilters.length; while (i--) { name = attributeFilters[i].name; if (name in node.attributes.map) { list = matchedAttributes[name]; if (list) list.push(node); else matchedAttributes[name] = [node]; } } return node; }; self.addNodeFilter = function(name, callback) { tinymce.each(tinymce.explode(name), function(name) { var list = nodeFilters[name]; if (!list) nodeFilters[name] = list = []; list.push(callback); }); }; self.addAttributeFilter = function(name, callback) { tinymce.each(tinymce.explode(name), function(name) { var i; for (i = 0; i < attributeFilters.length; i++) { if (attributeFilters[i].name === name) { attributeFilters[i].callbacks.push(callback); return; } } attributeFilters.push({name: name, callbacks: [callback]}); }); }; self.parse = function(html, args) { var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate, blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement, endWhiteSpaceRegExp, allWhiteSpaceRegExp, whiteSpaceElements, children, nonEmptyElements, rootBlockName; args = args || {}; matchedNodes = {}; matchedAttributes = {}; blockElements = tinymce.extend(tinymce.makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements()); nonEmptyElements = schema.getNonEmptyElements(); children = schema.children; validate = settings.validate; rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block; whiteSpaceElements = schema.getWhiteSpaceElements(); startWhiteSpaceRegExp = /^[ \t\r\n]+/; endWhiteSpaceRegExp = /[ \t\r\n]+$/; allWhiteSpaceRegExp = /[ \t\r\n]+/g; function addRootBlocks() { var node = rootNode.firstChild, next, rootBlockNode; while (node) { next = node.next; if (node.type == 3 || (node.type == 1 && node.name !== 'p' && !blockElements[node.name] && !node.attr('data-mce-type'))) { if (!rootBlockNode) { // Create a new root block element rootBlockNode = createNode(rootBlockName, 1); rootNode.insert(rootBlockNode, node); rootBlockNode.append(node); } else rootBlockNode.append(node); } else { rootBlockNode = null; } node = next; }; }; function createNode(name, type) { var node = new Node(name, type), list; if (name in nodeFilters) { list = matchedNodes[name]; if (list) list.push(node); else matchedNodes[name] = [node]; } return node; }; function removeWhitespaceBefore(node) { var textNode, textVal, sibling; for (textNode = node.prev; textNode && textNode.type === 3; ) { textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); if (textVal.length > 0) { textNode.value = textVal; textNode = textNode.prev; } else { sibling = textNode.prev; textNode.remove(); textNode = sibling; } } }; parser = new tinymce.html.SaxParser({ validate : validate, fix_self_closing : !validate, // Let the DOM parser handle <li> in <li> or <p> in <p> for better results cdata: function(text) { node.append(createNode('#cdata', 4)).value = text; }, text: function(text, raw) { var textNode; // Trim all redundant whitespace on non white space elements if (!isInWhiteSpacePreservedElement) { text = text.replace(allWhiteSpaceRegExp, ' '); if (node.lastChild && blockElements[node.lastChild.name]) text = text.replace(startWhiteSpaceRegExp, ''); } // Do we need to create the node if (text.length !== 0) { textNode = createNode('#text', 3); textNode.raw = !!raw; node.append(textNode).value = text; } }, comment: function(text) { node.append(createNode('#comment', 8)).value = text; }, pi: function(name, text) { node.append(createNode(name, 7)).value = text; removeWhitespaceBefore(node); }, doctype: function(text) { var newNode; newNode = node.append(createNode('#doctype', 10)); newNode.value = text; removeWhitespaceBefore(node); }, start: function(name, attrs, empty) { var newNode, attrFiltersLen, elementRule, textNode, attrName, text, sibling, parent; elementRule = validate ? schema.getElementRule(name) : {}; if (elementRule) { newNode = createNode(elementRule.outputName || name, 1); newNode.attributes = attrs; newNode.shortEnded = empty; node.append(newNode); // Check if node is valid child of the parent node is the child is // unknown we don't collect it since it's probably a custom element parent = children[node.name]; if (parent && children[newNode.name] && !parent[newNode.name]) invalidChildren.push(newNode); attrFiltersLen = attributeFilters.length; while (attrFiltersLen--) { attrName = attributeFilters[attrFiltersLen].name; if (attrName in attrs.map) { list = matchedAttributes[attrName]; if (list) list.push(newNode); else matchedAttributes[attrName] = [newNode]; } } // Trim whitespace before block if (blockElements[name]) removeWhitespaceBefore(newNode); // Change current node if the element wasn't empty i.e not <br /> or <img /> if (!empty) node = newNode; // Check if we are inside a whitespace preserved element if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) { isInWhiteSpacePreservedElement = true; } } }, end: function(name) { var textNode, elementRule, text, sibling, tempNode; elementRule = validate ? schema.getElementRule(name) : {}; if (elementRule) { if (blockElements[name]) { if (!isInWhiteSpacePreservedElement) { // Trim whitespace at beginning of block for (textNode = node.firstChild; textNode && textNode.type === 3; ) { text = textNode.value.replace(startWhiteSpaceRegExp, ''); if (text.length > 0) { textNode.value = text; textNode = textNode.next; } else { sibling = textNode.next; textNode.remove(); textNode = sibling; } } // Trim whitespace at end of block for (textNode = node.lastChild; textNode && textNode.type === 3; ) { text = textNode.value.replace(endWhiteSpaceRegExp, ''); if (text.length > 0) { textNode.value = text; textNode = textNode.prev; } else { sibling = textNode.prev; textNode.remove(); textNode = sibling; } } } // Trim start white space textNode = node.prev; if (textNode && textNode.type === 3) { text = textNode.value.replace(startWhiteSpaceRegExp, ''); if (text.length > 0) textNode.value = text; else textNode.remove(); } } // Check if we exited a whitespace preserved element if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) { isInWhiteSpacePreservedElement = false; } // Handle empty nodes if (elementRule.removeEmpty || elementRule.paddEmpty) { if (node.isEmpty(nonEmptyElements)) { if (elementRule.paddEmpty) node.empty().append(new Node('#text', '3')).value = '\u00a0'; else { // Leave nodes that have a name like <a name="name"> if (!node.attributes.map.name) { tempNode = node.parent; node.empty().remove(); node = tempNode; return; } } } } node = node.parent; } } }, schema); rootNode = node = new Node(args.context || settings.root_name, 11); parser.parse(html); // Fix invalid children or report invalid children in a contextual parsing if (validate && invalidChildren.length) { if (!args.context) fixInvalidChildren(invalidChildren); else args.invalid = true; } // Wrap nodes in the root into block elements if the root is body if (rootBlockName && rootNode.name == 'body') addRootBlocks(); // Run filters only when the contents is valid if (!args.invalid) { // Run node filters for (name in matchedNodes) { list = nodeFilters[name]; nodes = matchedNodes[name]; // Remove already removed children fi = nodes.length; while (fi--) { if (!nodes[fi].parent) nodes.splice(fi, 1); } for (i = 0, l = list.length; i < l; i++) list[i](nodes, name, args); } // Run attribute filters for (i = 0, l = attributeFilters.length; i < l; i++) { list = attributeFilters[i]; if (list.name in matchedAttributes) { nodes = matchedAttributes[list.name]; // Remove already removed children fi = nodes.length; while (fi--) { if (!nodes[fi].parent) nodes.splice(fi, 1); } for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) list.callbacks[fi](nodes, list.name, args); } } } return rootNode; }; // Remove <br> at end of block elements Gecko and WebKit injects BR elements to // make it possible to place the caret inside empty blocks. This logic tries to remove // these elements and keep br elements that where intended to be there intact if (settings.remove_trailing_brs) { self.addNodeFilter('br', function(nodes, name) { var i, l = nodes.length, node, blockElements = tinymce.extend({}, schema.getBlockElements()), nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName; // Remove brs from body element as well blockElements.body = 1; // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p> for (i = 0; i < l; i++) { node = nodes[i]; parent = node.parent; if (blockElements[node.parent.name] && node === parent.lastChild) { // Loop all nodes to the left of the current node and check for other BR elements // excluding bookmarks since they are invisible prev = node.prev; while (prev) { prevName = prev.name; // Ignore bookmarks if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') { // Found a non BR element if (prevName !== "br") break; // Found another br it's a <br><br> structure then don't remove anything if (prevName === 'br') { node = null; break; } } prev = prev.prev; } if (node) { node.remove(); // Is the parent to be considered empty after we removed the BR if (parent.isEmpty(nonEmptyElements)) { elementRule = schema.getElementRule(parent.name); // Remove or padd the element depending on schema rule if (elementRule) { if (elementRule.removeEmpty) parent.remove(); else if (elementRule.paddEmpty) parent.empty().append(new tinymce.html.Node('#text', 3)).value = '\u00a0'; } } } } else { // Replaces BR elements inside inline elements like <p><b><i><br></i></b></p> so they become <p><b><i>&nbsp;</i></b></p> lastParent = node; while (parent.firstChild === lastParent && parent.lastChild === lastParent) { lastParent = parent; if (blockElements[parent.name]) { break; } parent = parent.parent; } if (lastParent === parent) { textNode = new tinymce.html.Node('#text', 3); textNode.value = '\u00a0'; node.replace(textNode); } } } }); } // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. if (!settings.allow_html_in_named_anchor) { self.addAttributeFilter('name', function(nodes, name) { var i = nodes.length, sibling, prevSibling, parent, node; while (i--) { node = nodes[i]; if (node.name === 'a' && node.firstChild) { parent = node.parent; // Move children after current node sibling = node.lastChild; do { prevSibling = sibling.prev; parent.insert(sibling, node); sibling = prevSibling; } while (sibling); } } }); } } })(tinymce); tinymce.html.Writer = function(settings) { var html = [], indent, indentBefore, indentAfter, encode, htmlOutput; settings = settings || {}; indent = settings.indent; indentBefore = tinymce.makeMap(settings.indent_before || ''); indentAfter = tinymce.makeMap(settings.indent_after || ''); encode = tinymce.html.Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities); htmlOutput = settings.element_format == "html"; return { start: function(name, attrs, empty) { var i, l, attr, value; if (indent && indentBefore[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } html.push('<', name); if (attrs) { for (i = 0, l = attrs.length; i < l; i++) { attr = attrs[i]; html.push(' ', attr.name, '="', encode(attr.value, true), '"'); } } if (!empty || htmlOutput) html[html.length] = '>'; else html[html.length] = ' />'; if (empty && indent && indentAfter[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } }, end: function(name) { var value; /*if (indent && indentBefore[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); }*/ html.push('</', name, '>'); if (indent && indentAfter[name] && html.length > 0) { value = html[html.length - 1]; if (value.length > 0 && value !== '\n') html.push('\n'); } }, text: function(text, raw) { if (text.length > 0) html[html.length] = raw ? text : encode(text); }, cdata: function(text) { html.push('<![CDATA[', text, ']]>'); }, comment: function(text) { html.push('<!--', text, '-->'); }, pi: function(name, text) { if (text) html.push('<?', name, ' ', text, '?>'); else html.push('<?', name, '?>'); if (indent) html.push('\n'); }, doctype: function(text) { html.push('<!DOCTYPE', text, '>', indent ? '\n' : ''); }, reset: function() { html.length = 0; }, getContent: function() { return html.join('').replace(/\n$/, ''); } }; }; (function(tinymce) { tinymce.html.Serializer = function(settings, schema) { var self = this, writer = new tinymce.html.Writer(settings); settings = settings || {}; settings.validate = "validate" in settings ? settings.validate : true; self.schema = schema = schema || new tinymce.html.Schema(); self.writer = writer; self.serialize = function(node) { var handlers, validate; validate = settings.validate; handlers = { // #text 3: function(node, raw) { writer.text(node.value, node.raw); }, // #comment 8: function(node) { writer.comment(node.value); }, // Processing instruction 7: function(node) { writer.pi(node.name, node.value); }, // Doctype 10: function(node) { writer.doctype(node.value); }, // CDATA 4: function(node) { writer.cdata(node.value); }, // Document fragment 11: function(node) { if ((node = node.firstChild)) { do { walk(node); } while (node = node.next); } } }; writer.reset(); function walk(node) { var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; if (!handler) { name = node.name; isEmpty = node.shortEnded; attrs = node.attributes; // Sort attributes if (validate && attrs && attrs.length > 1) { sortedAttrs = []; sortedAttrs.map = {}; elementRule = schema.getElementRule(node.name); for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { attrName = elementRule.attributesOrder[i]; if (attrName in attrs.map) { attrValue = attrs.map[attrName]; sortedAttrs.map[attrName] = attrValue; sortedAttrs.push({name: attrName, value: attrValue}); } } for (i = 0, l = attrs.length; i < l; i++) { attrName = attrs[i].name; if (!(attrName in sortedAttrs.map)) { attrValue = attrs.map[attrName]; sortedAttrs.map[attrName] = attrValue; sortedAttrs.push({name: attrName, value: attrValue}); } } attrs = sortedAttrs; } writer.start(node.name, attrs, isEmpty); if (!isEmpty) { if ((node = node.firstChild)) { do { walk(node); } while (node = node.next); } writer.end(name); } } else handler(node); } // Serialize element and treat all non elements as fragments if (node.type == 1 && !settings.inner) walk(node); else handlers[11](node); return writer.getContent(); }; } })(tinymce); // JSLint defined globals /*global tinymce:false, window:false */ tinymce.dom = {}; (function(namespace, expando) { var w3cEventModel = !!document.addEventListener; function addEvent(target, name, callback, capture) { if (target.addEventListener) { target.addEventListener(name, callback, capture || false); } else if (target.attachEvent) { target.attachEvent('on' + name, callback); } } function removeEvent(target, name, callback, capture) { if (target.removeEventListener) { target.removeEventListener(name, callback, capture || false); } else if (target.detachEvent) { target.detachEvent('on' + name, callback); } } function fix(original_event, data) { var name, event = data || {}; // Dummy function that gets replaced on the delegation state functions function returnFalse() { return false; } // Dummy function that gets replaced on the delegation state functions function returnTrue() { return true; } // Copy all properties from the original event for (name in original_event) { // layerX/layerY is deprecated in Chrome and produces a warning if (name !== "layerX" && name !== "layerY") { event[name] = original_event[name]; } } // Normalize target IE uses srcElement if (!event.target) { event.target = event.srcElement || document; } // Add preventDefault method event.preventDefault = function() { event.isDefaultPrevented = returnTrue; // Execute preventDefault on the original event object if (original_event) { if (original_event.preventDefault) { original_event.preventDefault(); } else { original_event.returnValue = false; // IE } } }; // Add stopPropagation event.stopPropagation = function() { event.isPropagationStopped = returnTrue; // Execute stopPropagation on the original event object if (original_event) { if (original_event.stopPropagation) { original_event.stopPropagation(); } else { original_event.cancelBubble = true; // IE } } }; // Add stopImmediatePropagation event.stopImmediatePropagation = function() { event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; // Add event delegation states if (!event.isDefaultPrevented) { event.isDefaultPrevented = returnFalse; event.isPropagationStopped = returnFalse; event.isImmediatePropagationStopped = returnFalse; } return event; } function bindOnReady(win, callback, event_utils) { var doc = win.document, event = {type: 'ready'}; // Gets called when the DOM is ready function readyHandler() { if (!event_utils.domLoaded) { event_utils.domLoaded = true; callback(event); } } // Use W3C method if (w3cEventModel) { addEvent(win, 'DOMContentLoaded', readyHandler); } else { // Use IE method addEvent(doc, "readystatechange", function() { if (doc.readyState === "complete") { removeEvent(doc, "readystatechange", arguments.callee); readyHandler(); } }); // Wait until we can scroll, when we can the DOM is initialized if (doc.documentElement.doScroll && win === win.top) { (function() { try { // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author. // http://javascript.nwbox.com/IEContentLoaded/ doc.documentElement.doScroll("left"); } catch (ex) { setTimeout(arguments.callee, 0); return; } readyHandler(); })(); } } // Fallback if any of the above methods should fail for some odd reason addEvent(win, 'load', readyHandler); } function EventUtils(proxy) { var self = this, events = {}, count, isFocusBlurBound, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; hasMouseEnterLeave = "onmouseenter" in document.documentElement; hasFocusIn = "onfocusin" in document.documentElement; mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'}; count = 1; // State if the DOMContentLoaded was executed or not self.domLoaded = false; self.events = events; function executeHandlers(evt, id) { var callbackList, i, l, callback; callbackList = events[id][evt.type]; if (callbackList) { for (i = 0, l = callbackList.length; i < l; i++) { callback = callbackList[i]; // Check if callback exists might be removed if a unbind is called inside the callback if (callback && callback.func.call(callback.scope, evt) === false) { evt.preventDefault(); } // Should we stop propagation to immediate listeners if (evt.isImmediatePropagationStopped()) { return; } } } } self.bind = function(target, names, callback, scope) { var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window; // Native event handler function patches the event and executes the callbacks for the expando function defaultNativeHandler(evt) { executeHandlers(fix(evt || win.event), id); } // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return; } // Create or get events id for the target if (!target[expando]) { id = count++; target[expando] = id; events[id] = {}; } else { id = target[expando]; if (!events[id]) { events[id] = {}; } } // Setup the specified scope or use the target as a default scope = scope || target; // Split names and bind each event, enables you to bind multiple events with one call names = names.split(' '); i = names.length; while (i--) { name = names[i]; nativeHandler = defaultNativeHandler; fakeName = capture = false; // Use ready instead of DOMContentLoaded if (name === "DOMContentLoaded") { name = "ready"; } // DOM is already ready if ((self.domLoaded || target.readyState == 'complete') && name === "ready") { self.domLoaded = true; callback.call(scope, fix({type: name})); continue; } // Handle mouseenter/mouseleaver if (!hasMouseEnterLeave) { fakeName = mouseEnterLeave[name]; if (fakeName) { nativeHandler = function(evt) { var current, related; current = evt.currentTarget; related = evt.relatedTarget; // Check if related is inside the current target if it's not then the event should be ignored since it's a mouseover/mouseout inside the element if (related && current.contains) { // Use contains for performance related = current.contains(related); } else { while (related && related !== current) { related = related.parentNode; } } // Fire fake event if (!related) { evt = fix(evt || win.event); evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter'; evt.target = current; executeHandlers(evt, id); } }; } } // Fake bubbeling of focusin/focusout if (!hasFocusIn && (name === "focusin" || name === "focusout")) { capture = true; fakeName = name === "focusin" ? "focus" : "blur"; nativeHandler = function(evt) { evt = fix(evt || win.event); evt.type = evt.type === 'focus' ? 'focusin' : 'focusout'; executeHandlers(evt, id); }; } // Setup callback list and bind native event callbackList = events[id][name]; if (!callbackList) { events[id][name] = callbackList = [{func: callback, scope: scope}]; callbackList.fakeName = fakeName; callbackList.capture = capture; // Add the nativeHandler to the callback list so that we can later unbind it callbackList.nativeHandler = nativeHandler; if (!w3cEventModel) { callbackList.proxyHandler = proxy(id); } // Check if the target has native events support if (name === "ready") { bindOnReady(target, nativeHandler, self); } else { addEvent(target, fakeName || name, w3cEventModel ? nativeHandler : callbackList.proxyHandler, capture); } } else { // If it already has an native handler then just push the callback callbackList.push({func: callback, scope: scope}); } } target = callbackList = 0; // Clean memory for IE return callback; }; self.unbind = function(target, names, callback) { var id, callbackList, i, ci, name, eventMap; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind event or events if the target has the expando id = target[expando]; if (id) { eventMap = events[id]; // Specific callback if (names) { names = names.split(' '); i = names.length; while (i--) { name = names[i]; callbackList = eventMap[name]; // Unbind the event if it exists in the map if (callbackList) { // Remove specified callback if (callback) { ci = callbackList.length; while (ci--) { if (callbackList[ci].func === callback) { callbackList.splice(ci, 1); } } } // Remove all callbacks if there isn't a specified callback or there is no callbacks left if (!callback || callbackList.length === 0) { delete eventMap[name]; removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture); } } } } else { // All events for a specific element for (name in eventMap) { callbackList = eventMap[name]; removeEvent(target, callbackList.fakeName || name, w3cEventModel ? callbackList.nativeHandler : callbackList.proxyHandler, callbackList.capture); } eventMap = {}; } // Check if object is empty, if it isn't then we won't remove the expando map for (name in eventMap) { return self; } // Delete event object delete events[id]; // Remove expando from target try { // IE will fail here since it can't delete properties from window delete target[expando]; } catch (ex) { // IE will set it to null target[expando] = null; } } return self; }; self.fire = function(target, name, args) { var id, event; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Build event object by patching the args event = fix(null, args); event.type = name; do { // Found an expando that means there is listeners to execute id = target[expando]; if (id) { executeHandlers(event, id); } // Walk up the DOM target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; } while (target && !event.isPropagationStopped()); return self; }; self.clean = function(target) { var i, children, unbind = self.unbind; // Don't bind to text nodes or comments if (!target || target.nodeType === 3 || target.nodeType === 8) { return self; } // Unbind any element on the specificed target if (target[expando]) { unbind(target); } // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children if (!target.getElementsByTagName) { target = target.document; } // Remove events from each child element if (target && target.getElementsByTagName) { unbind(target); children = target.getElementsByTagName('*'); i = children.length; while (i--) { target = children[i]; if (target[expando]) { unbind(target); } } } return self; }; self.callNativeHandler = function(id, evt) { if (events) { events[id][evt.type].nativeHandler(evt); } }; self.destory = function() { events = {}; }; // Legacy function calls self.add = function(target, events, func, scope) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } // Old API supported multiple targets if (target && target instanceof Array) { var i = target; while (i--) { self.add(target[i], events, func, scope); } return; } // Old API called ready init if (events === "init") { events = "ready"; } return self.bind(target, events instanceof Array ? events.join(' ') : events, func, scope); }; self.remove = function(target, events, func) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } // Old API supported multiple targets if (target instanceof Array) { var i = target; while (i--) { self.remove(target[i], events, func, scope); } return self; } return self.unbind(target, events instanceof Array ? events.join(' ') : events, func); }; self.clear = function(target) { // Old API supported direct ID assignment if (typeof(target) === "string") { target = document.getElementById(target); } return self.clean(target); }; self.cancel = function(e) { if (e) { self.prevent(e); self.stop(e); } return false; }; self.prevent = function(e) { e.preventDefault(); return false; }; self.stop = function(e) { e.stopPropagation(); return false; }; } namespace.EventUtils = EventUtils; namespace.Event = new EventUtils(function(id) { return function(evt) { tinymce.dom.Event.callNativeHandler(id, evt); }; }); // Bind ready event when tinymce script is loaded namespace.Event.bind(window, 'ready', function() {}); namespace = 0; })(tinymce.dom, 'data-mce-expando'); // Namespace and expando tinymce.dom.TreeWalker = function(start_node, root_node) { var node = start_node; function findSibling(node, start_name, sibling_name, shallow) { var sibling, parent; if (node) { // Walk into nodes if it has a start if (!shallow && node[start_name]) return node[start_name]; // Return the sibling if it has one if (node != root_node) { sibling = node[sibling_name]; if (sibling) return sibling; // Walk up the parents to look for siblings for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) { sibling = parent[sibling_name]; if (sibling) return sibling; } } } }; this.current = function() { return node; }; this.next = function(shallow) { return (node = findSibling(node, 'firstChild', 'nextSibling', shallow)); }; this.prev = function(shallow) { return (node = findSibling(node, 'lastChild', 'previousSibling', shallow)); }; }; (function(tinymce) { // Shorten names var each = tinymce.each, is = tinymce.is, isWebKit = tinymce.isWebKit, isIE = tinymce.isIE, Entities = tinymce.html.Entities, simpleSelectorRe = /^([a-z0-9],?)+$/i, whiteSpaceRegExp = /^[ \t\r\n]*$/; tinymce.create('tinymce.dom.DOMUtils', { doc : null, root : null, files : null, pixelStyles : /^(top|left|bottom|right|width|height|borderWidth)$/, props : { "for" : "htmlFor", "class" : "className", className : "className", checked : "checked", disabled : "disabled", maxlength : "maxLength", readonly : "readOnly", selected : "selected", value : "value", id : "id", name : "name", type : "type" }, DOMUtils : function(d, s) { var t = this, globalStyle, name, blockElementsMap; t.doc = d; t.win = window; t.files = {}; t.cssFlicker = false; t.counter = 0; t.stdMode = !tinymce.isIE || d.documentMode >= 8; t.boxModel = !tinymce.isIE || d.compatMode == "CSS1Compat" || t.stdMode; t.hasOuterHTML = "outerHTML" in d.createElement("a"); t.settings = s = tinymce.extend({ keep_values : false, hex_colors : 1 }, s); t.schema = s.schema; t.styles = new tinymce.html.Styles({ url_converter : s.url_converter, url_converter_scope : s.url_converter_scope }, s.schema); // Fix IE6SP2 flicker and check it failed for pre SP2 if (tinymce.isIE6) { try { d.execCommand('BackgroundImageCache', false, true); } catch (e) { t.cssFlicker = true; } } t.fixDoc(d); t.events = s.ownEvents ? new tinymce.dom.EventUtils(s.proxy) : tinymce.dom.Event; tinymce.addUnload(t.destroy, t); blockElementsMap = s.schema ? s.schema.getBlockElements() : {}; t.isBlock = function(node) { // This function is called in module pattern style since it might be executed with the wrong this scope var type = node.nodeType; // If it's a node then check the type and use the nodeName if (type) return !!(type === 1 && blockElementsMap[node.nodeName]); return !!blockElementsMap[node]; }; }, fixDoc: function(doc) { var settings = this.settings, name; if (isIE && settings.schema) { // Add missing HTML 4/5 elements to IE ('abbr article aside audio canvas ' + 'details figcaption figure footer ' + 'header hgroup mark menu meter nav ' + 'output progress section summary ' + 'time video').replace(/\w+/g, function(name) { doc.createElement(name); }); // Create all custom elements for (name in settings.schema.getCustomElements()) { doc.createElement(name); } } }, clone: function(node, deep) { var self = this, clone, doc; // TODO: Add feature detection here in the future if (!isIE || node.nodeType !== 1 || deep) { return node.cloneNode(deep); } doc = self.doc; // Make a HTML5 safe shallow copy if (!deep) { clone = doc.createElement(node.nodeName); // Copy attribs each(self.getAttribs(node), function(attr) { self.setAttrib(clone, attr.nodeName, self.getAttrib(node, attr.nodeName)); }); return clone; } /* // Setup HTML5 patched document fragment if (!self.frag) { self.frag = doc.createDocumentFragment(); self.fixDoc(self.frag); } // Make a deep copy by adding it to the document fragment then removing it this removed the :section clone = doc.createElement('div'); self.frag.appendChild(clone); clone.innerHTML = node.outerHTML; self.frag.removeChild(clone); */ return clone.firstChild; }, getRoot : function() { var t = this, s = t.settings; return (s && t.get(s.root_element)) || t.doc.body; }, getViewPort : function(w) { var d, b; w = !w ? this.win : w; d = w.document; b = this.boxModel ? d.documentElement : d.body; // Returns viewport size excluding scrollbars return { x : w.pageXOffset || b.scrollLeft, y : w.pageYOffset || b.scrollTop, w : w.innerWidth || b.clientWidth, h : w.innerHeight || b.clientHeight }; }, getRect : function(e) { var p, t = this, sr; e = t.get(e); p = t.getPos(e); sr = t.getSize(e); return { x : p.x, y : p.y, w : sr.w, h : sr.h }; }, getSize : function(e) { var t = this, w, h; e = t.get(e); w = t.getStyle(e, 'width'); h = t.getStyle(e, 'height'); // Non pixel value, then force offset/clientWidth if (w.indexOf('px') === -1) w = 0; // Non pixel value, then force offset/clientWidth if (h.indexOf('px') === -1) h = 0; return { w : parseInt(w, 10) || e.offsetWidth || e.clientWidth, h : parseInt(h, 10) || e.offsetHeight || e.clientHeight }; }, getParent : function(n, f, r) { return this.getParents(n, f, r, false); }, getParents : function(n, f, r, c) { var t = this, na, se = t.settings, o = []; n = t.get(n); c = c === undefined; if (se.strict_root) r = r || t.getRoot(); // Wrap node name as func if (is(f, 'string')) { na = f; if (f === '*') { f = function(n) {return n.nodeType == 1;}; } else { f = function(n) { return t.is(n, na); }; } } while (n) { if (n == r || !n.nodeType || n.nodeType === 9) break; if (!f || f(n)) { if (c) o.push(n); else return n; } n = n.parentNode; } return c ? o : null; }, get : function(e) { var n; if (e && this.doc && typeof(e) == 'string') { n = e; e = this.doc.getElementById(e); // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick if (e && e.id !== n) return this.doc.getElementsByName(n)[1]; } return e; }, getNext : function(node, selector) { return this._findSib(node, selector, 'nextSibling'); }, getPrev : function(node, selector) { return this._findSib(node, selector, 'previousSibling'); }, select : function(pa, s) { var t = this; return tinymce.dom.Sizzle(pa, t.get(s) || t.get(t.settings.root_element) || t.doc, []); }, is : function(n, selector) { var i; // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance if (n.length === undefined) { // Simple all selector if (selector === '*') return n.nodeType == 1; // Simple selector just elements if (simpleSelectorRe.test(selector)) { selector = selector.toLowerCase().split(/,/); n = n.nodeName.toLowerCase(); for (i = selector.length - 1; i >= 0; i--) { if (selector[i] == n) return true; } return false; } } return tinymce.dom.Sizzle.matches(selector, n.nodeType ? [n] : n).length > 0; }, add : function(p, n, a, h, c) { var t = this; return this.run(p, function(p) { var e, k; e = is(n, 'string') ? t.doc.createElement(n) : n; t.setAttribs(e, a); if (h) { if (h.nodeType) e.appendChild(h); else t.setHTML(e, h); } return !c ? p.appendChild(e) : e; }); }, create : function(n, a, h) { return this.add(this.doc.createElement(n), n, a, h, 1); }, createHTML : function(n, a, h) { var o = '', t = this, k; o += '<' + n; for (k in a) { if (a.hasOwnProperty(k)) o += ' ' + k + '="' + t.encode(a[k]) + '"'; } // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime if (typeof(h) != "undefined") return o + '>' + h + '</' + n + '>'; return o + ' />'; }, remove : function(node, keep_children) { return this.run(node, function(node) { var child, parent = node.parentNode; if (!parent) return null; if (keep_children) { while (child = node.firstChild) { // IE 8 will crash if you don't remove completely empty text nodes if (!tinymce.isIE || child.nodeType !== 3 || child.nodeValue) parent.insertBefore(child, node); else node.removeChild(child); } } return parent.removeChild(node); }); }, setStyle : function(n, na, v) { var t = this; return t.run(n, function(e) { var s, i; s = e.style; // Camelcase it, if needed na = na.replace(/-(\D)/g, function(a, b){ return b.toUpperCase(); }); // Default px suffix on these if (t.pixelStyles.test(na) && (tinymce.is(v, 'number') || /^[\-0-9\.]+$/.test(v))) v += 'px'; switch (na) { case 'opacity': // IE specific opacity if (isIE) { s.filter = v === '' ? '' : "alpha(opacity=" + (v * 100) + ")"; if (!n.currentStyle || !n.currentStyle.hasLayout) s.display = 'inline-block'; } // Fix for older browsers s[na] = s['-moz-opacity'] = s['-khtml-opacity'] = v || ''; break; case 'float': isIE ? s.styleFloat = v : s.cssFloat = v; break; default: s[na] = v || ''; } // Force update of the style data if (t.settings.update_styles) t.setAttrib(e, 'data-mce-style'); }); }, getStyle : function(n, na, c) { n = this.get(n); if (!n) return; // Gecko if (this.doc.defaultView && c) { // Remove camelcase na = na.replace(/[A-Z]/g, function(a){ return '-' + a; }); try { return this.doc.defaultView.getComputedStyle(n, null).getPropertyValue(na); } catch (ex) { // Old safari might fail return null; } } // Camelcase it, if needed na = na.replace(/-(\D)/g, function(a, b){ return b.toUpperCase(); }); if (na == 'float') na = isIE ? 'styleFloat' : 'cssFloat'; // IE & Opera if (n.currentStyle && c) return n.currentStyle[na]; return n.style ? n.style[na] : undefined; }, setStyles : function(e, o) { var t = this, s = t.settings, ol; ol = s.update_styles; s.update_styles = 0; each(o, function(v, n) { t.setStyle(e, n, v); }); // Update style info s.update_styles = ol; if (s.update_styles) t.setAttrib(e, s.cssText); }, removeAllAttribs: function(e) { return this.run(e, function(e) { var i, attrs = e.attributes; for (i = attrs.length - 1; i >= 0; i--) { e.removeAttributeNode(attrs.item(i)); } }); }, setAttrib : function(e, n, v) { var t = this; // Whats the point if (!e || !n) return; // Strict XML mode if (t.settings.strict) n = n.toLowerCase(); return this.run(e, function(e) { var s = t.settings; var originalValue = e.getAttribute(n); if (v !== null) { switch (n) { case "style": if (!is(v, 'string')) { each(v, function(v, n) { t.setStyle(e, n, v); }); return; } // No mce_style for elements with these since they might get resized by the user if (s.keep_values) { if (v && !t._isRes(v)) e.setAttribute('data-mce-style', v, 2); else e.removeAttribute('data-mce-style', 2); } e.style.cssText = v; break; case "class": e.className = v || ''; // Fix IE null bug break; case "src": case "href": if (s.keep_values) { if (s.url_converter) v = s.url_converter.call(s.url_converter_scope || t, v, n, e); t.setAttrib(e, 'data-mce-' + n, v, 2); } break; case "shape": e.setAttribute('data-mce-style', v); break; } } if (is(v) && v !== null && v.length !== 0) e.setAttribute(n, '' + v, 2); else e.removeAttribute(n, 2); // fire onChangeAttrib event for attributes that have changed if (tinyMCE.activeEditor && originalValue != v) { var ed = tinyMCE.activeEditor; ed.onSetAttrib.dispatch(ed, e, n, v); } }); }, setAttribs : function(e, o) { var t = this; return this.run(e, function(e) { each(o, function(v, n) { t.setAttrib(e, n, v); }); }); }, getAttrib : function(e, n, dv) { var v, t = this, undef; e = t.get(e); if (!e || e.nodeType !== 1) return dv === undef ? false : dv; if (!is(dv)) dv = ''; // Try the mce variant for these if (/^(src|href|style|coords|shape)$/.test(n)) { v = e.getAttribute("data-mce-" + n); if (v) return v; } if (isIE && t.props[n]) { v = e[t.props[n]]; v = v && v.nodeValue ? v.nodeValue : v; } if (!v) v = e.getAttribute(n, 2); // Check boolean attribs if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(n)) { if (e[t.props[n]] === true && v === '') return n; return v ? n : ''; } // Inner input elements will override attributes on form elements if (e.nodeName === "FORM" && e.getAttributeNode(n)) return e.getAttributeNode(n).nodeValue; if (n === 'style') { v = v || e.style.cssText; if (v) { v = t.serializeStyle(t.parseStyle(v), e.nodeName); if (t.settings.keep_values && !t._isRes(v)) e.setAttribute('data-mce-style', v); } } // Remove Apple and WebKit stuff if (isWebKit && n === "class" && v) v = v.replace(/(apple|webkit)\-[a-z\-]+/gi, ''); // Handle IE issues if (isIE) { switch (n) { case 'rowspan': case 'colspan': // IE returns 1 as default value if (v === 1) v = ''; break; case 'size': // IE returns +0 as default value for size if (v === '+0' || v === 20 || v === 0) v = ''; break; case 'width': case 'height': case 'vspace': case 'checked': case 'disabled': case 'readonly': if (v === 0) v = ''; break; case 'hspace': // IE returns -1 as default value if (v === -1) v = ''; break; case 'maxlength': case 'tabindex': // IE returns default value if (v === 32768 || v === 2147483647 || v === '32768') v = ''; break; case 'multiple': case 'compact': case 'noshade': case 'nowrap': if (v === 65535) return n; return dv; case 'shape': v = v.toLowerCase(); break; default: // IE has odd anonymous function for event attributes if (n.indexOf('on') === 0 && v) v = tinymce._replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1', '' + v); } } return (v !== undef && v !== null && v !== '') ? '' + v : dv; }, getPos : function(n, ro) { var t = this, x = 0, y = 0, e, d = t.doc, r; n = t.get(n); ro = ro || d.body; if (n) { // Use getBoundingClientRect if it exists since it's faster than looping offset nodes if (n.getBoundingClientRect) { n = n.getBoundingClientRect(); e = t.boxModel ? d.documentElement : d.body; // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position x = n.left + (d.documentElement.scrollLeft || d.body.scrollLeft) - e.clientTop; y = n.top + (d.documentElement.scrollTop || d.body.scrollTop) - e.clientLeft; return {x : x, y : y}; } r = n; while (r && r != ro && r.nodeType) { x += r.offsetLeft || 0; y += r.offsetTop || 0; r = r.offsetParent; } r = n.parentNode; while (r && r != ro && r.nodeType) { x -= r.scrollLeft || 0; y -= r.scrollTop || 0; r = r.parentNode; } } return {x : x, y : y}; }, parseStyle : function(st) { return this.styles.parse(st); }, serializeStyle : function(o, name) { return this.styles.serialize(o, name); }, loadCSS : function(u) { var t = this, d = t.doc, head; if (!u) u = ''; head = d.getElementsByTagName('head')[0]; each(u.split(','), function(u) { var link; if (t.files[u]) return; t.files[u] = true; link = t.create('link', {rel : 'stylesheet', href : tinymce._addVer(u)}); // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug // This fix seems to resolve that issue by realcing the document ones a stylesheet finishes loading // It's ugly but it seems to work fine. if (isIE && d.documentMode && d.recalc) { link.onload = function() { if (d.recalc) d.recalc(); link.onload = null; }; } head.appendChild(link); }); }, addClass : function(e, c) { return this.run(e, function(e) { var o; if (!c) return 0; if (this.hasClass(e, c)) return e.className; o = this.removeClass(e, c); return e.className = (o != '' ? (o + ' ') : '') + c; }); }, removeClass : function(e, c) { var t = this, re; return t.run(e, function(e) { var v; if (t.hasClass(e, c)) { if (!re) re = new RegExp("(^|\\s+)" + c + "(\\s+|$)", "g"); v = e.className.replace(re, ' '); v = tinymce.trim(v != ' ' ? v : ''); e.className = v; // Empty class attr if (!v) { e.removeAttribute('class'); e.removeAttribute('className'); } return v; } return e.className; }); }, hasClass : function(n, c) { n = this.get(n); if (!n || !c) return false; return (' ' + n.className + ' ').indexOf(' ' + c + ' ') !== -1; }, show : function(e) { return this.setStyle(e, 'display', 'block'); }, hide : function(e) { return this.setStyle(e, 'display', 'none'); }, isHidden : function(e) { e = this.get(e); return !e || e.style.display == 'none' || this.getStyle(e, 'display') == 'none'; }, uniqueId : function(p) { return (!p ? 'mce_' : p) + (this.counter++); }, setHTML : function(element, html) { var self = this; return self.run(element, function(element) { if (isIE) { // Remove all child nodes, IE keeps empty text nodes in DOM while (element.firstChild) element.removeChild(element.firstChild); try { // IE will remove comments from the beginning // unless you padd the contents with something element.innerHTML = '<br />' + html; element.removeChild(element.firstChild); } catch (ex) { // IE sometimes produces an unknown runtime error on innerHTML if it's an block element within a block element for example a div inside a p // This seems to fix this problem // Create new div with HTML contents and a BR infront to keep comments element = self.create('div'); element.innerHTML = '<br />' + html; // Add all children from div to target each (element.childNodes, function(node, i) { // Skip br element if (i) element.appendChild(node); }); } } else element.innerHTML = html; return html; }); }, getOuterHTML : function(elm) { var doc, self = this; elm = self.get(elm); if (!elm) return null; if (elm.nodeType === 1 && self.hasOuterHTML) return elm.outerHTML; doc = (elm.ownerDocument || self.doc).createElement("body"); doc.appendChild(elm.cloneNode(true)); return doc.innerHTML; }, setOuterHTML : function(e, h, d) { var t = this; function setHTML(e, h, d) { var n, tp; tp = d.createElement("body"); tp.innerHTML = h; n = tp.lastChild; while (n) { t.insertAfter(n.cloneNode(true), e); n = n.previousSibling; } t.remove(e); }; return this.run(e, function(e) { e = t.get(e); // Only set HTML on elements if (e.nodeType == 1) { d = d || e.ownerDocument || t.doc; if (isIE) { try { // Try outerHTML for IE it sometimes produces an unknown runtime error if (isIE && e.nodeType == 1) e.outerHTML = h; else setHTML(e, h, d); } catch (ex) { // Fix for unknown runtime error setHTML(e, h, d); } } else setHTML(e, h, d); } }); }, decode : Entities.decode, encode : Entities.encodeAllRaw, insertAfter : function(node, reference_node) { reference_node = this.get(reference_node); return this.run(node, function(node) { var parent, nextSibling; parent = reference_node.parentNode; nextSibling = reference_node.nextSibling; if (nextSibling) parent.insertBefore(node, nextSibling); else parent.appendChild(node); return node; }); }, replace : function(n, o, k) { var t = this; if (is(o, 'array')) n = n.cloneNode(true); return t.run(o, function(o) { if (k) { each(tinymce.grep(o.childNodes), function(c) { n.appendChild(c); }); } return o.parentNode.replaceChild(n, o); }); }, rename : function(elm, name) { var t = this, newElm; if (elm.nodeName != name.toUpperCase()) { // Rename block element newElm = t.create(name); // Copy attribs to new block each(t.getAttribs(elm), function(attr_node) { t.setAttrib(newElm, attr_node.nodeName, t.getAttrib(elm, attr_node.nodeName)); }); // Replace block t.replace(newElm, elm, 1); } return newElm || elm; }, findCommonAncestor : function(a, b) { var ps = a, pe; while (ps) { pe = b; while (pe && ps != pe) pe = pe.parentNode; if (ps == pe) break; ps = ps.parentNode; } if (!ps && a.ownerDocument) return a.ownerDocument.documentElement; return ps; }, toHex : function(s) { var c = /^\s*rgb\s*?\(\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?,\s*?([0-9]+)\s*?\)\s*$/i.exec(s); function hex(s) { s = parseInt(s, 10).toString(16); return s.length > 1 ? s : '0' + s; // 0 -> 00 }; if (c) { s = '#' + hex(c[1]) + hex(c[2]) + hex(c[3]); return s; } return s; }, getClasses : function() { var t = this, cl = [], i, lo = {}, f = t.settings.class_filter, ov; if (t.classes) return t.classes; function addClasses(s) { // IE style imports each(s.imports, function(r) { addClasses(r); }); each(s.cssRules || s.rules, function(r) { // Real type or fake it on IE switch (r.type || 1) { // Rule case 1: if (r.selectorText) { each(r.selectorText.split(','), function(v) { v = v.replace(/^\s*|\s*$|^\s\./g, ""); // Is internal or it doesn't contain a class if (/\.mce/.test(v) || !/\.[\w\-]+$/.test(v)) return; // Remove everything but class name ov = v; v = tinymce._replace(/.*\.([a-z0-9_\-]+).*/i, '$1', v); // Filter classes if (f && !(v = f(v, ov))) return; if (!lo[v]) { cl.push({'class' : v}); lo[v] = 1; } }); } break; // Import case 3: addClasses(r.styleSheet); break; } }); }; try { each(t.doc.styleSheets, addClasses); } catch (ex) { // Ignore } if (cl.length > 0) t.classes = cl; return cl; }, run : function(e, f, s) { var t = this, o; if (t.doc && typeof(e) === 'string') e = t.get(e); if (!e) return false; s = s || this; if (!e.nodeType && (e.length || e.length === 0)) { o = []; each(e, function(e, i) { if (e) { if (typeof(e) == 'string') e = t.doc.getElementById(e); o.push(f.call(s, e, i)); } }); return o; } return f.call(s, e); }, getAttribs : function(n) { var o; n = this.get(n); if (!n) return []; if (isIE) { o = []; // Object will throw exception in IE if (n.nodeName == 'OBJECT') return n.attributes; // IE doesn't keep the selected attribute if you clone option elements if (n.nodeName === 'OPTION' && this.getAttrib(n, 'selected')) o.push({specified : 1, nodeName : 'selected'}); // It's crazy that this is faster in IE but it's because it returns all attributes all the time n.cloneNode(false).outerHTML.replace(/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi, '').replace(/[\w:\-]+/gi, function(a) { o.push({specified : 1, nodeName : a}); }); return o; } return n.attributes; }, isEmpty : function(node, elements) { var self = this, i, attributes, type, walker, name, brCount = 0; node = node.firstChild; if (node) { walker = new tinymce.dom.TreeWalker(node, node.parentNode); elements = elements || self.schema ? self.schema.getNonEmptyElements() : null; do { type = node.nodeType; if (type === 1) { // Ignore bogus elements if (node.getAttribute('data-mce-bogus')) continue; // Keep empty elements like <img /> name = node.nodeName.toLowerCase(); if (elements && elements[name]) { // Ignore single BR elements in blocks like <p><br /></p> or <p><span><br /></span></p> if (name === 'br') { brCount++; continue; } return false; } // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a> attributes = self.getAttribs(node); i = node.attributes.length; while (i--) { name = node.attributes[i].nodeName; if (name === "name" || name === 'data-mce-bookmark') return false; } } // Keep comment nodes if (type == 8) return false; // Keep non whitespace text nodes if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue))) return false; } while (node = walker.next()); } return brCount <= 1; }, destroy : function(s) { var t = this; t.win = t.doc = t.root = t.events = t.frag = null; // Manual destroy then remove unload handler if (!s) tinymce.removeUnload(t.destroy); }, createRng : function() { var d = this.doc; return d.createRange ? d.createRange() : new tinymce.dom.Range(this); }, nodeIndex : function(node, normalized) { var idx = 0, lastNodeType, lastNode, nodeType; if (node) { for (lastNodeType = node.nodeType, node = node.previousSibling, lastNode = node; node; node = node.previousSibling) { nodeType = node.nodeType; // Normalize text nodes if (normalized && nodeType == 3) { if (nodeType == lastNodeType || !node.nodeValue.length) continue; } idx++; lastNodeType = nodeType; } } return idx; }, split : function(pe, e, re) { var t = this, r = t.createRng(), bef, aft, pa; // W3C valid browsers tend to leave empty nodes to the left/right side of the contents, this makes sense // but we don't want that in our code since it serves no purpose for the end user // For example if this is chopped: // <p>text 1<span><b>CHOP</b></span>text 2</p> // would produce: // <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p> // this function will then trim of empty edges and produce: // <p>text 1</p><b>CHOP</b><p>text 2</p> function trim(node) { var i, children = node.childNodes, type = node.nodeType; function surroundedBySpans(node) { var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; return previousIsSpan && nextIsSpan; } if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') return; for (i = children.length - 1; i >= 0; i--) trim(children[i]); if (type != 9) { // Keep non whitespace text nodes if (type == 3 && node.nodeValue.length > 0) { // If parent element isn't a block or there isn't any useful contents for example "<p> </p>" // Also keep text nodes with only spaces if surrounded by spans. // eg. "<p><span>a</span> <span>b</span></p>" should keep space between a and b var trimmedLength = tinymce.trim(node.nodeValue).length; if (!t.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) return; } else if (type == 1) { // If the only child is a bookmark then move it up children = node.childNodes; if (children.length == 1 && children[0] && children[0].nodeType == 1 && children[0].getAttribute('data-mce-type') == 'bookmark') node.parentNode.insertBefore(children[0], node); // Keep non empty elements or img, hr etc if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) return; } t.remove(node); } return node; }; if (pe && e) { // Get before chunk r.setStart(pe.parentNode, t.nodeIndex(pe)); r.setEnd(e.parentNode, t.nodeIndex(e)); bef = r.extractContents(); // Get after chunk r = t.createRng(); r.setStart(e.parentNode, t.nodeIndex(e) + 1); r.setEnd(pe.parentNode, t.nodeIndex(pe) + 1); aft = r.extractContents(); // Insert before chunk pa = pe.parentNode; pa.insertBefore(trim(bef), pe); // Insert middle chunk if (re) pa.replaceChild(re, e); else pa.insertBefore(e, pe); // Insert after chunk pa.insertBefore(trim(aft), pe); t.remove(pe); return re || e; } }, bind : function(target, name, func, scope) { return this.events.add(target, name, func, scope || this); }, unbind : function(target, name, func) { return this.events.remove(target, name, func); }, fire : function(target, name, evt) { return this.events.fire(target, name, evt); }, // Returns the content editable state of a node getContentEditable: function(node) { var contentEditable; // Check type if (node.nodeType != 1) { return null; } // Check for fake content editable contentEditable = node.getAttribute("data-mce-contenteditable"); if (contentEditable && contentEditable !== "inherit") { return contentEditable; } // Check for real content editable return node.contentEditable !== "inherit" ? node.contentEditable : null; }, _findSib : function(node, selector, name) { var t = this, f = selector; if (node) { // If expression make a function of it using is if (is(f, 'string')) { f = function(node) { return t.is(node, selector); }; } // Loop all siblings for (node = node[name]; node; node = node[name]) { if (f(node)) return node; } } return null; }, _isRes : function(c) { // Is live resizble element return /^(top|left|bottom|right|width|height)/i.test(c) || /;\s*(top|left|bottom|right|width|height)/i.test(c); } /* walk : function(n, f, s) { var d = this.doc, w; if (d.createTreeWalker) { w = d.createTreeWalker(n, NodeFilter.SHOW_TEXT, null, false); while ((n = w.nextNode()) != null) f.call(s || this, n); } else tinymce.walk(n, f, 'childNodes', s); } */ /* toRGB : function(s) { var c = /^\s*?#([0-9A-F]{2})([0-9A-F]{1,2})([0-9A-F]{2})?\s*?$/.exec(s); if (c) { // #FFF -> #FFFFFF if (!is(c[3])) c[3] = c[2] = c[1]; return "rgb(" + parseInt(c[1], 16) + "," + parseInt(c[2], 16) + "," + parseInt(c[3], 16) + ")"; } return s; } */ }); tinymce.DOM = new tinymce.dom.DOMUtils(document, {process_html : 0}); })(tinymce); (function(ns) { // Range constructor function Range(dom) { var t = this, doc = dom.doc, EXTRACT = 0, CLONE = 1, DELETE = 2, TRUE = true, FALSE = false, START_OFFSET = 'startOffset', START_CONTAINER = 'startContainer', END_CONTAINER = 'endContainer', END_OFFSET = 'endOffset', extend = tinymce.extend, nodeIndex = dom.nodeIndex; extend(t, { // Inital states startContainer : doc, startOffset : 0, endContainer : doc, endOffset : 0, collapsed : TRUE, commonAncestorContainer : doc, // Range constants START_TO_START : 0, START_TO_END : 1, END_TO_END : 2, END_TO_START : 3, // Public methods setStart : setStart, setEnd : setEnd, setStartBefore : setStartBefore, setStartAfter : setStartAfter, setEndBefore : setEndBefore, setEndAfter : setEndAfter, collapse : collapse, selectNode : selectNode, selectNodeContents : selectNodeContents, compareBoundaryPoints : compareBoundaryPoints, deleteContents : deleteContents, extractContents : extractContents, cloneContents : cloneContents, insertNode : insertNode, surroundContents : surroundContents, cloneRange : cloneRange }); function createDocumentFragment() { return doc.createDocumentFragment(); }; function setStart(n, o) { _setEndPoint(TRUE, n, o); }; function setEnd(n, o) { _setEndPoint(FALSE, n, o); }; function setStartBefore(n) { setStart(n.parentNode, nodeIndex(n)); }; function setStartAfter(n) { setStart(n.parentNode, nodeIndex(n) + 1); }; function setEndBefore(n) { setEnd(n.parentNode, nodeIndex(n)); }; function setEndAfter(n) { setEnd(n.parentNode, nodeIndex(n) + 1); }; function collapse(ts) { if (ts) { t[END_CONTAINER] = t[START_CONTAINER]; t[END_OFFSET] = t[START_OFFSET]; } else { t[START_CONTAINER] = t[END_CONTAINER]; t[START_OFFSET] = t[END_OFFSET]; } t.collapsed = TRUE; }; function selectNode(n) { setStartBefore(n); setEndAfter(n); }; function selectNodeContents(n) { setStart(n, 0); setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length); }; function compareBoundaryPoints(h, r) { var sc = t[START_CONTAINER], so = t[START_OFFSET], ec = t[END_CONTAINER], eo = t[END_OFFSET], rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset; // Check START_TO_START if (h === 0) return _compareBoundaryPoints(sc, so, rsc, rso); // Check START_TO_END if (h === 1) return _compareBoundaryPoints(ec, eo, rsc, rso); // Check END_TO_END if (h === 2) return _compareBoundaryPoints(ec, eo, rec, reo); // Check END_TO_START if (h === 3) return _compareBoundaryPoints(sc, so, rec, reo); }; function deleteContents() { _traverse(DELETE); }; function extractContents() { return _traverse(EXTRACT); }; function cloneContents() { return _traverse(CLONE); }; function insertNode(n) { var startContainer = this[START_CONTAINER], startOffset = this[START_OFFSET], nn, o; // Node is TEXT_NODE or CDATA if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) { if (!startOffset) { // At the start of text startContainer.parentNode.insertBefore(n, startContainer); } else if (startOffset >= startContainer.nodeValue.length) { // At the end of text dom.insertAfter(n, startContainer); } else { // Middle, need to split nn = startContainer.splitText(startOffset); startContainer.parentNode.insertBefore(n, nn); } } else { // Insert element node if (startContainer.childNodes.length > 0) o = startContainer.childNodes[startOffset]; if (o) startContainer.insertBefore(n, o); else startContainer.appendChild(n); } }; function surroundContents(n) { var f = t.extractContents(); t.insertNode(n); n.appendChild(f); t.selectNode(n); }; function cloneRange() { return extend(new Range(dom), { startContainer : t[START_CONTAINER], startOffset : t[START_OFFSET], endContainer : t[END_CONTAINER], endOffset : t[END_OFFSET], collapsed : t.collapsed, commonAncestorContainer : t.commonAncestorContainer }); }; // Private methods function _getSelectedNode(container, offset) { var child; if (container.nodeType == 3 /* TEXT_NODE */) return container; if (offset < 0) return container; child = container.firstChild; while (child && offset > 0) { --offset; child = child.nextSibling; } if (child) return child; return container; }; function _isCollapsed() { return (t[START_CONTAINER] == t[END_CONTAINER] && t[START_OFFSET] == t[END_OFFSET]); }; function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) { var c, offsetC, n, cmnRoot, childA, childB; // In the first case the boundary-points have the same container. A is before B // if its offset is less than the offset of B, A is equal to B if its offset is // equal to the offset of B, and A is after B if its offset is greater than the // offset of B. if (containerA == containerB) { if (offsetA == offsetB) return 0; // equal if (offsetA < offsetB) return -1; // before return 1; // after } // In the second case a child node C of the container of A is an ancestor // container of B. In this case, A is before B if the offset of A is less than or // equal to the index of the child node C and A is after B otherwise. c = containerB; while (c && c.parentNode != containerA) c = c.parentNode; if (c) { offsetC = 0; n = containerA.firstChild; while (n != c && offsetC < offsetA) { offsetC++; n = n.nextSibling; } if (offsetA <= offsetC) return -1; // before return 1; // after } // In the third case a child node C of the container of B is an ancestor container // of A. In this case, A is before B if the index of the child node C is less than // the offset of B and A is after B otherwise. c = containerA; while (c && c.parentNode != containerB) { c = c.parentNode; } if (c) { offsetC = 0; n = containerB.firstChild; while (n != c && offsetC < offsetB) { offsetC++; n = n.nextSibling; } if (offsetC < offsetB) return -1; // before return 1; // after } // In the fourth case, none of three other cases hold: the containers of A and B // are siblings or descendants of sibling nodes. In this case, A is before B if // the container of A is before the container of B in a pre-order traversal of the // Ranges' context tree and A is after B otherwise. cmnRoot = dom.findCommonAncestor(containerA, containerB); childA = containerA; while (childA && childA.parentNode != cmnRoot) childA = childA.parentNode; if (!childA) childA = cmnRoot; childB = containerB; while (childB && childB.parentNode != cmnRoot) childB = childB.parentNode; if (!childB) childB = cmnRoot; if (childA == childB) return 0; // equal n = cmnRoot.firstChild; while (n) { if (n == childA) return -1; // before if (n == childB) return 1; // after n = n.nextSibling; } }; function _setEndPoint(st, n, o) { var ec, sc; if (st) { t[START_CONTAINER] = n; t[START_OFFSET] = o; } else { t[END_CONTAINER] = n; t[END_OFFSET] = o; } // If one boundary-point of a Range is set to have a root container // other than the current one for the Range, the Range is collapsed to // the new position. This enforces the restriction that both boundary- // points of a Range must have the same root container. ec = t[END_CONTAINER]; while (ec.parentNode) ec = ec.parentNode; sc = t[START_CONTAINER]; while (sc.parentNode) sc = sc.parentNode; if (sc == ec) { // The start position of a Range is guaranteed to never be after the // end position. To enforce this restriction, if the start is set to // be at a position after the end, the Range is collapsed to that // position. if (_compareBoundaryPoints(t[START_CONTAINER], t[START_OFFSET], t[END_CONTAINER], t[END_OFFSET]) > 0) t.collapse(st); } else t.collapse(st); t.collapsed = _isCollapsed(); t.commonAncestorContainer = dom.findCommonAncestor(t[START_CONTAINER], t[END_CONTAINER]); }; function _traverse(how) { var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep; if (t[START_CONTAINER] == t[END_CONTAINER]) return _traverseSameContainer(how); for (c = t[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { if (p == t[START_CONTAINER]) return _traverseCommonStartContainer(c, how); ++endContainerDepth; } for (c = t[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { if (p == t[END_CONTAINER]) return _traverseCommonEndContainer(c, how); ++startContainerDepth; } depthDiff = startContainerDepth - endContainerDepth; startNode = t[START_CONTAINER]; while (depthDiff > 0) { startNode = startNode.parentNode; depthDiff--; } endNode = t[END_CONTAINER]; while (depthDiff < 0) { endNode = endNode.parentNode; depthDiff++; } // ascend the ancestor hierarchy until we have a common parent. for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) { startNode = sp; endNode = ep; } return _traverseCommonAncestors(startNode, endNode, how); }; function _traverseSameContainer(how) { var frag, s, sub, n, cnt, sibling, xferNode, start, len; if (how != DELETE) frag = createDocumentFragment(); // If selection is empty, just return the fragment if (t[START_OFFSET] == t[END_OFFSET]) return frag; // Text node needs special case handling if (t[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) { // get the substring s = t[START_CONTAINER].nodeValue; sub = s.substring(t[START_OFFSET], t[END_OFFSET]); // set the original text node to its new value if (how != CLONE) { n = t[START_CONTAINER]; start = t[START_OFFSET]; len = t[END_OFFSET] - t[START_OFFSET]; if (start === 0 && len >= n.nodeValue.length - 1) { n.parentNode.removeChild(n); } else { n.deleteData(start, len); } // Nothing is partially selected, so collapse to start point t.collapse(TRUE); } if (how == DELETE) return; if (sub.length > 0) { frag.appendChild(doc.createTextNode(sub)); } return frag; } // Copy nodes between the start/end offsets. n = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]); cnt = t[END_OFFSET] - t[START_OFFSET]; while (n && cnt > 0) { sibling = n.nextSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.appendChild( xferNode ); --cnt; n = sibling; } // Nothing is partially selected, so collapse to start point if (how != CLONE) t.collapse(TRUE); return frag; }; function _traverseCommonStartContainer(endAncestor, how) { var frag, n, endIdx, cnt, sibling, xferNode; if (how != DELETE) frag = createDocumentFragment(); n = _traverseRightBoundary(endAncestor, how); if (frag) frag.appendChild(n); endIdx = nodeIndex(endAncestor); cnt = endIdx - t[START_OFFSET]; if (cnt <= 0) { // Collapse to just before the endAncestor, which // is partially selected. if (how != CLONE) { t.setEndBefore(endAncestor); t.collapse(FALSE); } return frag; } n = endAncestor.previousSibling; while (cnt > 0) { sibling = n.previousSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.insertBefore(xferNode, frag.firstChild); --cnt; n = sibling; } // Collapse to just before the endAncestor, which // is partially selected. if (how != CLONE) { t.setEndBefore(endAncestor); t.collapse(FALSE); } return frag; }; function _traverseCommonEndContainer(startAncestor, how) { var frag, startIdx, n, cnt, sibling, xferNode; if (how != DELETE) frag = createDocumentFragment(); n = _traverseLeftBoundary(startAncestor, how); if (frag) frag.appendChild(n); startIdx = nodeIndex(startAncestor); ++startIdx; // Because we already traversed it cnt = t[END_OFFSET] - startIdx; n = startAncestor.nextSibling; while (n && cnt > 0) { sibling = n.nextSibling; xferNode = _traverseFullySelected(n, how); if (frag) frag.appendChild(xferNode); --cnt; n = sibling; } if (how != CLONE) { t.setStartAfter(startAncestor); t.collapse(TRUE); } return frag; }; function _traverseCommonAncestors(startAncestor, endAncestor, how) { var n, frag, commonParent, startOffset, endOffset, cnt, sibling, nextSibling; if (how != DELETE) frag = createDocumentFragment(); n = _traverseLeftBoundary(startAncestor, how); if (frag) frag.appendChild(n); commonParent = startAncestor.parentNode; startOffset = nodeIndex(startAncestor); endOffset = nodeIndex(endAncestor); ++startOffset; cnt = endOffset - startOffset; sibling = startAncestor.nextSibling; while (cnt > 0) { nextSibling = sibling.nextSibling; n = _traverseFullySelected(sibling, how); if (frag) frag.appendChild(n); sibling = nextSibling; --cnt; } n = _traverseRightBoundary(endAncestor, how); if (frag) frag.appendChild(n); if (how != CLONE) { t.setStartAfter(startAncestor); t.collapse(TRUE); } return frag; }; function _traverseRightBoundary(root, how) { var next = _getSelectedNode(t[END_CONTAINER], t[END_OFFSET] - 1), parent, clonedParent, prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != t[END_CONTAINER]; if (next == root) return _traverseNode(next, isFullySelected, FALSE, how); parent = next.parentNode; clonedParent = _traverseNode(parent, FALSE, FALSE, how); while (parent) { while (next) { prevSibling = next.previousSibling; clonedChild = _traverseNode(next, isFullySelected, FALSE, how); if (how != DELETE) clonedParent.insertBefore(clonedChild, clonedParent.firstChild); isFullySelected = TRUE; next = prevSibling; } if (parent == root) return clonedParent; next = parent.previousSibling; parent = parent.parentNode; clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how); if (how != DELETE) clonedGrandParent.appendChild(clonedParent); clonedParent = clonedGrandParent; } }; function _traverseLeftBoundary(root, how) { var next = _getSelectedNode(t[START_CONTAINER], t[START_OFFSET]), isFullySelected = next != t[START_CONTAINER], parent, clonedParent, nextSibling, clonedChild, clonedGrandParent; if (next == root) return _traverseNode(next, isFullySelected, TRUE, how); parent = next.parentNode; clonedParent = _traverseNode(parent, FALSE, TRUE, how); while (parent) { while (next) { nextSibling = next.nextSibling; clonedChild = _traverseNode(next, isFullySelected, TRUE, how); if (how != DELETE) clonedParent.appendChild(clonedChild); isFullySelected = TRUE; next = nextSibling; } if (parent == root) return clonedParent; next = parent.nextSibling; parent = parent.parentNode; clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how); if (how != DELETE) clonedGrandParent.appendChild(clonedParent); clonedParent = clonedGrandParent; } }; function _traverseNode(n, isFullySelected, isLeft, how) { var txtValue, newNodeValue, oldNodeValue, offset, newNode; if (isFullySelected) return _traverseFullySelected(n, how); if (n.nodeType == 3 /* TEXT_NODE */) { txtValue = n.nodeValue; if (isLeft) { offset = t[START_OFFSET]; newNodeValue = txtValue.substring(offset); oldNodeValue = txtValue.substring(0, offset); } else { offset = t[END_OFFSET]; newNodeValue = txtValue.substring(0, offset); oldNodeValue = txtValue.substring(offset); } if (how != CLONE) n.nodeValue = oldNodeValue; if (how == DELETE) return; newNode = dom.clone(n, FALSE); newNode.nodeValue = newNodeValue; return newNode; } if (how == DELETE) return; return dom.clone(n, FALSE); }; function _traverseFullySelected(n, how) { if (how != DELETE) return how == CLONE ? dom.clone(n, TRUE) : n; n.parentNode.removeChild(n); }; }; ns.Range = Range; })(tinymce.dom); (function() { function Selection(selection) { var self = this, dom = selection.dom, TRUE = true, FALSE = false; function getPosition(rng, start) { var checkRng, startIndex = 0, endIndex, inside, children, child, offset, index, position = -1, parent; // Setup test range, collapse it and get the parent checkRng = rng.duplicate(); checkRng.collapse(start); parent = checkRng.parentElement(); // Check if the selection is within the right document if (parent.ownerDocument !== selection.dom.doc) return; // IE will report non editable elements as it's parent so look for an editable one while (parent.contentEditable === "false") { parent = parent.parentNode; } // If parent doesn't have any children then return that we are inside the element if (!parent.hasChildNodes()) { return {node : parent, inside : 1}; } // Setup node list and endIndex children = parent.children; endIndex = children.length - 1; // Perform a binary search for the position while (startIndex <= endIndex) { index = Math.floor((startIndex + endIndex) / 2); // Move selection to node and compare the ranges child = children[index]; checkRng.moveToElementText(child); position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); // Before/after or an exact match if (position > 0) { endIndex = index - 1; } else if (position < 0) { startIndex = index + 1; } else { return {node : child}; } } // Check if child position is before or we didn't find a position if (position < 0) { // No element child was found use the parent element and the offset inside that if (!child) { checkRng.moveToElementText(parent); checkRng.collapse(true); child = parent; inside = true; } else checkRng.collapse(false); // Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one // We need to walk char by char since rng.text or rng.htmlText will trim line endings offset = 0; while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { break; } offset++; } } else { // Child position is after the selection endpoint checkRng.collapse(true); // Walk character by character in text node until we hit the selected range endpoint, hit the end of document or parent isn't the right one offset = 0; while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { break; } offset++; } } return {node : child, position : position, offset : offset, inside : inside}; }; // Returns a W3C DOM compatible range object by using the IE Range API function getRange() { var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark, fail; // If selection is outside the current document just return an empty range element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); if (element.ownerDocument != dom.doc) return domRange; collapsed = selection.isCollapsed(); // Handle control selection if (ieRange.item) { domRange.setStart(element.parentNode, dom.nodeIndex(element)); domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); return domRange; } function findEndPoint(start) { var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; container = endPoint.node; offset = endPoint.offset; if (endPoint.inside && !container.hasChildNodes()) { domRange[start ? 'setStart' : 'setEnd'](container, 0); return; } if (offset === undef) { domRange[start ? 'setStartBefore' : 'setEndAfter'](container); return; } if (endPoint.position < 0) { sibling = endPoint.inside ? container.firstChild : container.nextSibling; if (!sibling) { domRange[start ? 'setStartAfter' : 'setEndAfter'](container); return; } if (!offset) { if (sibling.nodeType == 3) domRange[start ? 'setStart' : 'setEnd'](sibling, 0); else domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); return; } // Find the text node and offset while (sibling) { nodeValue = sibling.nodeValue; textNodeOffset += nodeValue.length; // We are at or passed the position we where looking for if (textNodeOffset >= offset) { container = sibling; textNodeOffset -= offset; textNodeOffset = nodeValue.length - textNodeOffset; break; } sibling = sibling.nextSibling; } } else { // Find the text node and offset sibling = container.previousSibling; if (!sibling) return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); // If there isn't any text to loop then use the first position if (!offset) { if (container.nodeType == 3) domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); else domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); return; } while (sibling) { textNodeOffset += sibling.nodeValue.length; // We are at or passed the position we where looking for if (textNodeOffset >= offset) { container = sibling; textNodeOffset -= offset; break; } sibling = sibling.previousSibling; } } domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); }; try { // Find start point findEndPoint(true); // Find end point if needed if (!collapsed) findEndPoint(); } catch (ex) { // IE has a nasty bug where text nodes might throw "invalid argument" when you // access the nodeValue or other properties of text nodes. This seems to happend when // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. if (ex.number == -2147024809) { // Get the current selection bookmark = self.getBookmark(2); // Get start element tmpRange = ieRange.duplicate(); tmpRange.collapse(true); element = tmpRange.parentElement(); // Get end element if (!collapsed) { tmpRange = ieRange.duplicate(); tmpRange.collapse(false); element2 = tmpRange.parentElement(); element2.innerHTML = element2.innerHTML; } // Remove the broken elements element.innerHTML = element.innerHTML; // Restore the selection self.moveToBookmark(bookmark); // Since the range has moved we need to re-get it ieRange = selection.getRng(); // Find start point findEndPoint(true); // Find end point if needed if (!collapsed) findEndPoint(); } else throw ex; // Throw other errors } return domRange; }; this.getBookmark = function(type) { var rng = selection.getRng(), start, end, bookmark = {}; function getIndexes(node) { var parent, root, children, i, indexes = []; parent = node.parentNode; root = dom.getRoot().parentNode; while (parent != root && parent.nodeType !== 9) { children = parent.children; i = children.length; while (i--) { if (node === children[i]) { indexes.push(i); break; } } node = parent; parent = parent.parentNode; } return indexes; }; function getBookmarkEndPoint(start) { var position; position = getPosition(rng, start); if (position) { return { position : position.position, offset : position.offset, indexes : getIndexes(position.node), inside : position.inside }; } }; // Non ubstructive bookmark if (type === 2) { // Handle text selection if (!rng.item) { bookmark.start = getBookmarkEndPoint(true); if (!selection.isCollapsed()) bookmark.end = getBookmarkEndPoint(); } else bookmark.start = {ctrl : true, indexes : getIndexes(rng.item(0))}; } return bookmark; }; this.moveToBookmark = function(bookmark) { var rng, body = dom.doc.body; function resolveIndexes(indexes) { var node, i, idx, children; node = dom.getRoot(); for (i = indexes.length - 1; i >= 0; i--) { children = node.children; idx = indexes[i]; if (idx <= children.length - 1) { node = children[idx]; } } return node; }; function setBookmarkEndPoint(start) { var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef; if (endPoint) { moveLeft = endPoint.position > 0; moveRng = body.createTextRange(); moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); offset = endPoint.offset; if (offset !== undef) { moveRng.collapse(endPoint.inside || moveLeft); moveRng.moveStart('character', moveLeft ? -offset : offset); } else moveRng.collapse(start); rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); if (start) rng.collapse(true); } }; if (bookmark.start) { if (bookmark.start.ctrl) { rng = body.createControlRange(); rng.addElement(resolveIndexes(bookmark.start.indexes)); rng.select(); } else { rng = body.createTextRange(); setBookmarkEndPoint(true); setBookmarkEndPoint(); rng.select(); } } }; this.addRange = function(rng) { var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, doc = selection.dom.doc, body = doc.body; function setEndPoint(start) { var container, offset, marker, tmpRng, nodes; marker = dom.create('a'); container = start ? startContainer : endContainer; offset = start ? startOffset : endOffset; tmpRng = ieRng.duplicate(); if (container == doc || container == doc.documentElement) { container = body; offset = 0; } if (container.nodeType == 3) { container.parentNode.insertBefore(marker, container); tmpRng.moveToElementText(marker); tmpRng.moveStart('character', offset); dom.remove(marker); ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); } else { nodes = container.childNodes; if (nodes.length) { if (offset >= nodes.length) { dom.insertAfter(marker, nodes[nodes.length - 1]); } else { container.insertBefore(marker, nodes[offset]); } tmpRng.moveToElementText(marker); } else if (container.canHaveHTML) { // Empty node selection for example <div>|</div> // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open container.innerHTML = '<span>\uFEFF</span>'; marker = container.firstChild; tmpRng.moveToElementText(marker); tmpRng.collapse(FALSE); // Collapse false works better than true for some odd reason } ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); dom.remove(marker); } } // Setup some shorter versions startContainer = rng.startContainer; startOffset = rng.startOffset; endContainer = rng.endContainer; endOffset = rng.endOffset; ieRng = body.createTextRange(); // If single element selection then try making a control selection out of it if (startContainer == endContainer && startContainer.nodeType == 1) { // Trick to place the caret inside an empty block element like <p></p> if (startOffset == endOffset && !startContainer.hasChildNodes()) { if (startContainer.canHaveHTML) { startContainer.innerHTML = '<span>\uFEFF</span><span>\uFEFF</span>'; ieRng.moveToElementText(startContainer.lastChild); ieRng.select(); dom.doc.selection.clear(); startContainer.innerHTML = ''; return; } else { startOffset = dom.nodeIndex(startContainer); startContainer = startContainer.parentNode; } } if (startOffset == endOffset - 1) { try { ctrlRng = body.createControlRange(); ctrlRng.addElement(startContainer.childNodes[startOffset]); ctrlRng.select(); return; } catch (ex) { // Ignore } } } // Set start/end point of selection setEndPoint(true); setEndPoint(); // Select the new range and scroll it into view ieRng.select(); }; // Expose range method this.getRangeAt = getRange; }; // Expose the selection object tinymce.dom.TridentSelection = Selection; })(); /* * Sizzle CSS Selector Engine * Copyright, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, expando = "sizcache", done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context, seed ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set, seed ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { filter = Expr.filter[ type ]; left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); pass = not ^ found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; var Expr = Sizzle.selectors = { order: [ "ID", "NAME", "TAG" ], match: { ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ }, leftMatch: {}, attrMap: { "class": "className", "for": "htmlFor" }, attrHandle: { href: function( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, selected: function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, parent: function( elem ) { return !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var first, last, doneName, parent, cache, count, diff, type = match[1], node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Sizzle.attr ? Sizzle.attr( elem, name ) : Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : !type && Sizzle.attr ? result != null : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id === match[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || !disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function
( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context, seed ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE window.tinymce.dom.Sizzle = Sizzle; })(); (function(tinymce) { tinymce.dom.Element = function(id, settings) { var t = this, dom, el; t.settings = settings = settings || {}; t.id = id; t.dom = dom = settings.dom || tinymce.DOM; // Only IE leaks DOM references, this is a lot faster if (!tinymce.isIE) el = dom.get(t.id); tinymce.each( ('getPos,getRect,getParent,add,setStyle,getStyle,setStyles,' + 'setAttrib,setAttribs,getAttrib,addClass,removeClass,' + 'hasClass,getOuterHTML,setOuterHTML,remove,show,hide,' + 'isHidden,setHTML,get').split(/,/), function(k) { t[k] = function() { var a = [id], i; for (i = 0; i < arguments.length; i++) a.push(arguments[i]); a = dom[k].apply(dom, a); t.update(k); return a; }; } ); tinymce.extend(t, { on : function(n, f, s) { return tinymce.dom.Event.add(t.id, n, f, s); }, getXY : function() { return { x : parseInt(t.getStyle('left')), y : parseInt(t.getStyle('top')) }; }, getSize : function() { var n = dom.get(t.id); return { w : parseInt(t.getStyle('width') || n.clientWidth), h : parseInt(t.getStyle('height') || n.clientHeight) }; }, moveTo : function(x, y) { t.setStyles({left : x, top : y}); }, moveBy : function(x, y) { var p = t.getXY(); t.moveTo(p.x + x, p.y + y); }, resizeTo : function(w, h) { t.setStyles({width : w, height : h}); }, resizeBy : function(w, h) { var s = t.getSize(); t.resizeTo(s.w + w, s.h + h); }, update : function(k) { var b; if (tinymce.isIE6 && settings.blocker) { k = k || ''; // Ignore getters if (k.indexOf('get') === 0 || k.indexOf('has') === 0 || k.indexOf('is') === 0) return; // Remove blocker on remove if (k == 'remove') { dom.remove(t.blocker); return; } if (!t.blocker) { t.blocker = dom.uniqueId(); b = dom.add(settings.container || dom.getRoot(), 'iframe', {id : t.blocker, style : 'position:absolute;', frameBorder : 0, src : 'javascript:""'}); dom.setStyle(b, 'opacity', 0); } else b = dom.get(t.blocker); dom.setStyles(b, { left : t.getStyle('left', 1), top : t.getStyle('top', 1), width : t.getStyle('width', 1), height : t.getStyle('height', 1), display : t.getStyle('display', 1), zIndex : parseInt(t.getStyle('zIndex', 1) || 0) - 1 }); } } }); }; })(tinymce); (function(tinymce) { function trimNl(s) { return s.replace(/[\n\r]+/g, ''); }; // Shorten names var is = tinymce.is, isIE = tinymce.isIE, each = tinymce.each, TreeWalker = tinymce.dom.TreeWalker; tinymce.create('tinymce.dom.Selection', { Selection : function(dom, win, serializer) { var t = this; t.dom = dom; t.win = win; t.serializer = serializer; // Add events each([ 'onBeforeSetContent', 'onBeforeGetContent', 'onSetContent', 'onGetContent' ], function(e) { t[e] = new tinymce.util.Dispatcher(t); }); // No W3C Range support if (!t.win.getSelection) t.tridentSel = new tinymce.dom.TridentSelection(t); if (tinymce.isIE && dom.boxModel) this._fixIESelection(); // Prevent leaks tinymce.addUnload(t.destroy, t); }, setCursorLocation: function(node, offset) { var t = this; var r = t.dom.createRng(); r.setStart(node, offset); r.setEnd(node, offset); t.setRng(r); t.collapse(false); }, getContent : function(s) { var t = this, r = t.getRng(), e = t.dom.create("body"), se = t.getSel(), wb, wa, n; s = s || {}; wb = wa = ''; s.get = true; s.format = s.format || 'html'; s.forced_root_block = ''; t.onBeforeGetContent.dispatch(t, s); if (s.format == 'text') return t.isCollapsed() ? '' : (r.text || (se.toString ? se.toString() : '')); if (r.cloneContents) { n = r.cloneContents(); if (n) e.appendChild(n); } else if (is(r.item) || is(r.htmlText)) { // IE will produce invalid markup if elements are present that // it doesn't understand like custom elements or HTML5 elements. // Adding a BR in front of the contents and then remoiving it seems to fix it though. e.innerHTML = '<br>' + (r.item ? r.item(0).outerHTML : r.htmlText); e.removeChild(e.firstChild); } else e.innerHTML = r.toString(); // Keep whitespace before and after if (/^\s/.test(e.innerHTML)) wb = ' '; if (/\s+$/.test(e.innerHTML)) wa = ' '; s.getInner = true; s.content = t.isCollapsed() ? '' : wb + t.serializer.serialize(e, s) + wa; t.onGetContent.dispatch(t, s); return s.content; }, setContent : function(content, args) { var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp; args = args || {format : 'html'}; args.set = true; content = args.content = content; // Dispatch before set content event if (!args.no_events) self.onBeforeSetContent.dispatch(self, args); content = args.content; if (rng.insertNode) { // Make caret marker since insertNode places the caret in the beginning of text after insert content += '<span id="__caret">_</span>'; // Delete and insert new node if (rng.startContainer == doc && rng.endContainer == doc) { // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents doc.body.innerHTML = content; } else { rng.deleteContents(); if (doc.body.childNodes.length === 0) { doc.body.innerHTML = content; } else { // createContextualFragment doesn't exists in IE 9 DOMRanges if (rng.createContextualFragment) { rng.insertNode(rng.createContextualFragment(content)); } else { // Fake createContextualFragment call in IE 9 frag = doc.createDocumentFragment(); temp = doc.createElement('div'); frag.appendChild(temp); temp.outerHTML = content; rng.insertNode(frag); } } } // Move to caret marker caretNode = self.dom.get('__caret'); // Make sure we wrap it compleatly, Opera fails with a simple select call rng = doc.createRange(); rng.setStartBefore(caretNode); rng.setEndBefore(caretNode); self.setRng(rng); // Remove the caret position self.dom.remove('__caret'); try { self.setRng(rng); } catch (ex) { // Might fail on Opera for some odd reason } } else { if (rng.item) { // Delete content and get caret text selection doc.execCommand('Delete', false, null); rng = self.getRng(); } // Explorer removes spaces from the beginning of pasted contents if (/^\s+/.test(content)) { rng.pasteHTML('<span id="__mce_tmp">_</span>' + content); self.dom.remove('__mce_tmp'); } else rng.pasteHTML(content); } // Dispatch set content event if (!args.no_events) self.onSetContent.dispatch(self, args); }, getStart : function() { var rng = this.getRng(), startElement, parentElement, checkRng, node; if (rng.duplicate || rng.item) { // Control selection, return first item if (rng.item) return rng.item(0); // Get start element checkRng = rng.duplicate(); checkRng.collapse(1); startElement = checkRng.parentElement(); // Check if range parent is inside the start element, then return the inner parent element // This will fix issues when a single element is selected, IE would otherwise return the wrong start element parentElement = node = rng.parentElement(); while (node = node.parentNode) { if (node == startElement) { startElement = parentElement; break; } } return startElement; } else { startElement = rng.startContainer; if (startElement.nodeType == 1 && startElement.hasChildNodes()) startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)]; if (startElement && startElement.nodeType == 3) return startElement.parentNode; return startElement; } }, getEnd : function() { var t = this, r = t.getRng(), e, eo; if (r.duplicate || r.item) { if (r.item) return r.item(0); r = r.duplicate(); r.collapse(0); e = r.parentElement(); if (e && e.nodeName == 'BODY') return e.lastChild || e; return e; } else { e = r.endContainer; eo = r.endOffset; if (e.nodeType == 1 && e.hasChildNodes()) e = e.childNodes[eo > 0 ? eo - 1 : eo]; if (e && e.nodeType == 3) return e.parentNode; return e; } }, getBookmark : function(type, normalized) { var t = this, dom = t.dom, rng, rng2, id, collapsed, name, element, index, chr = '\uFEFF', styles; function findIndex(name, element) { var index = 0; each(dom.select(name), function(node, i) { if (node == element) index = i; }); return index; }; function getLocation() { var rng = t.getRng(true), root = dom.getRoot(), bookmark = {}; function getPoint(rng, start) { var container = rng[start ? 'startContainer' : 'endContainer'], offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0; if (container.nodeType == 3) { if (normalized) { for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling) offset += node.nodeValue.length; } point.push(offset); } else { childNodes = container.childNodes; if (offset >= childNodes.length && childNodes.length) { after = 1; offset = Math.max(0, childNodes.length - 1); } point.push(t.dom.nodeIndex(childNodes[offset], normalized) + after); } for (; container && container != root; container = container.parentNode) point.push(t.dom.nodeIndex(container, normalized)); return point; }; bookmark.start = getPoint(rng, true); if (!t.isCollapsed()) bookmark.end = getPoint(rng); return bookmark; }; if (type == 2) { if (t.tridentSel) return t.tridentSel.getBookmark(type); return getLocation(); } // Handle simple range if (type) return {rng : t.getRng()}; rng = t.getRng(); id = dom.uniqueId(); collapsed = tinyMCE.activeEditor.selection.isCollapsed(); styles = 'overflow:hidden;line-height:0px'; // Explorer method if (rng.duplicate || rng.item) { // Text selection if (!rng.item) { rng2 = rng.duplicate(); try { // Insert start marker rng.collapse(); rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>'); // Insert end marker if (!collapsed) { rng2.collapse(false); // Detect the empty space after block elements in IE and move the end back one character <p></p>] becomes <p>]</p> rng.moveToElementText(rng2.parentElement()); if (rng.compareEndPoints('StartToEnd', rng2) === 0) rng2.move('character', -1); rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>'); } } catch (ex) { // IE might throw unspecified error so lets ignore it return null; } } else { // Control selection element = rng.item(0); name = element.nodeName; return {name : name, index : findIndex(name, element)}; } } else { element = t.getNode(); name = element.nodeName; if (name == 'IMG') return {name : name, index : findIndex(name, element)}; // Can't insert a node into the root of document WebKit defaults to document if (rng.startContainer.nodeType == 9) { return; } // W3C method rng2 = rng.cloneRange(); // Insert end marker if (!collapsed) { rng2.collapse(false); rng2.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_end', style : styles}, chr)); } rng.collapse(true); rng.insertNode(dom.create('span', {'data-mce-type' : "bookmark", id : id + '_start', style : styles}, chr)); } t.moveToBookmark({id : id, keep : 1}); return {id : id}; }, moveToBookmark : function(bookmark) { var t = this, dom = t.dom, marker1, marker2, rng, root, startContainer, endContainer, startOffset, endOffset; function setEndPoint(start) { var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; if (point) { offset = point[0]; // Find container node for (node = root, i = point.length - 1; i >= 1; i--) { children = node.childNodes; if (point[i] > children.length - 1) return; node = children[point[i]]; } // Move text offset to best suitable location if (node.nodeType === 3) offset = Math.min(point[0], node.nodeValue.length); // Move element offset to best suitable location if (node.nodeType === 1) offset = Math.min(point[0], node.childNodes.length); // Set offset within container node if (start) rng.setStart(node, offset); else rng.setEnd(node, offset); } return true; }; function restoreEndPoint(suffix) { var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; if (marker) { node = marker.parentNode; if (suffix == 'start') { if (!keep) { idx = dom.nodeIndex(marker); } else { node = marker.firstChild; idx = 1; } startContainer = endContainer = node; startOffset = endOffset = idx; } else { if (!keep) { idx = dom.nodeIndex(marker); } else { node = marker.firstChild; idx = 1; } endContainer = node; endOffset = idx; } if (!keep) { prev = marker.previousSibling; next = marker.nextSibling; // Remove all marker text nodes each(tinymce.grep(marker.childNodes), function(node) { if (node.nodeType == 3) node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); }); // Remove marker but keep children if for example contents where inserted into the marker // Also remove duplicated instances of the marker for example by a split operation or by WebKit auto split on paste feature while (marker = dom.get(bookmark.id + '_' + suffix)) dom.remove(marker, 1); // If siblings are text nodes then merge them unless it's Opera since it some how removes the node // and we are sniffing since adding a lot of detection code for a browser with 3% of the market isn't worth the effort. Sorry, Opera but it's just a fact if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !tinymce.isOpera) { idx = prev.nodeValue.length; prev.appendData(next.nodeValue); dom.remove(next); if (suffix == 'start') { startContainer = endContainer = prev; startOffset = endOffset = idx; } else { endContainer = prev; endOffset = idx; } } } } }; function addBogus(node) { // Adds a bogus BR element for empty block elements if (dom.isBlock(node) && !node.innerHTML && !isIE) node.innerHTML = '<br data-mce-bogus="1" />'; return node; }; if (bookmark) { if (bookmark.start) { rng = dom.createRng(); root = dom.getRoot(); if (t.tridentSel) return t.tridentSel.moveToBookmark(bookmark); if (setEndPoint(true) && setEndPoint()) { t.setRng(rng); } } else if (bookmark.id) { // Restore start/end points restoreEndPoint('start'); restoreEndPoint('end'); if (startContainer) { rng = dom.createRng(); rng.setStart(addBogus(startContainer), startOffset); rng.setEnd(addBogus(endContainer), endOffset); t.setRng(rng); } } else if (bookmark.name) { t.select(dom.select(bookmark.name)[bookmark.index]); } else if (bookmark.rng) t.setRng(bookmark.rng); } }, select : function(node, content) { var t = this, dom = t.dom, rng = dom.createRng(), idx; function setPoint(node, start) { var walker = new TreeWalker(node, node); do { // Text node if (node.nodeType == 3 && tinymce.trim(node.nodeValue).length !== 0) { if (start) rng.setStart(node, 0); else rng.setEnd(node, node.nodeValue.length); return; } // BR element if (node.nodeName == 'BR') { if (start) rng.setStartBefore(node); else rng.setEndBefore(node); return; } } while (node = (start ? walker.next() : walker.prev())); }; if (node) { idx = dom.nodeIndex(node); rng.setStart(node.parentNode, idx); rng.setEnd(node.parentNode, idx + 1); // Find first/last text node or BR element if (content) { setPoint(node, 1); setPoint(node); } t.setRng(rng); } return node; }, isCollapsed : function() { var t = this, r = t.getRng(), s = t.getSel(); if (!r || r.item) return false; if (r.compareEndPoints) return r.compareEndPoints('StartToEnd', r) === 0; return !s || r.collapsed; }, collapse : function(to_start) { var self = this, rng = self.getRng(), node; // Control range on IE if (rng.item) { node = rng.item(0); rng = self.win.document.body.createTextRange(); rng.moveToElementText(node); } rng.collapse(!!to_start); self.setRng(rng); }, getSel : function() { var t = this, w = this.win; return w.getSelection ? w.getSelection() : w.document.selection; }, getRng : function(w3c) { var t = this, s, r, elm, doc = t.win.document; // Found tridentSel object then we need to use that one if (w3c && t.tridentSel) return t.tridentSel.getRangeAt(0); try { if (s = t.getSel()) r = s.rangeCount > 0 ? s.getRangeAt(0) : (s.createRange ? s.createRange() : doc.createRange()); } catch (ex) { // IE throws unspecified error here if TinyMCE is placed in a frame/iframe } // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet if (tinymce.isIE && r && r.setStart && doc.selection.createRange().item) { elm = doc.selection.createRange().item(0); r = doc.createRange(); r.setStartBefore(elm); r.setEndAfter(elm); } // No range found then create an empty one // This can occur when the editor is placed in a hidden container element on Gecko // Or on IE when there was an exception if (!r) r = doc.createRange ? doc.createRange() : doc.body.createTextRange(); if (t.selectedRange && t.explicitRange) { if (r.compareBoundaryPoints(r.START_TO_START, t.selectedRange) === 0 && r.compareBoundaryPoints(r.END_TO_END, t.selectedRange) === 0) { // Safari, Opera and Chrome only ever select text which causes the range to change. // This lets us use the originally set range if the selection hasn't been changed by the user. r = t.explicitRange; } else { t.selectedRange = null; t.explicitRange = null; } } return r; }, setRng : function(r) { var s, t = this; if (!t.tridentSel) { s = t.getSel(); if (s) { t.explicitRange = r; try { s.removeAllRanges(); } catch (ex) { // IE9 might throw errors here don't know why } s.addRange(r); // adding range isn't always successful so we need to check range count otherwise an exception can occur t.selectedRange = s.rangeCount > 0 ? s.getRangeAt(0) : null; } } else { // Is W3C Range if (r.cloneRange) { try { t.tridentSel.addRange(r); return; } catch (ex) { //IE9 throws an error here if called before selection is placed in the editor } } // Is IE specific range try { r.select(); } catch (ex) { // Needed for some odd IE bug #1843306 } } }, setNode : function(n) { var t = this; t.setContent(t.dom.getOuterHTML(n)); return n; }, getNode : function() { var t = this, rng = t.getRng(), sel = t.getSel(), elm, start = rng.startContainer, end = rng.endContainer; function skipEmptyTextNodes(n, forwards) { var orig = n; while (n && n.nodeType === 3 && n.length === 0) { n = forwards ? n.nextSibling : n.previousSibling; } return n || orig; }; // Range maybe lost after the editor is made visible again if (!rng) return t.dom.getRoot(); if (rng.setStart) { elm = rng.commonAncestorContainer; // Handle selection a image or other control like element such as anchors if (!rng.collapsed) { if (rng.startContainer == rng.endContainer) { if (rng.endOffset - rng.startOffset < 2) { if (rng.startContainer.hasChildNodes()) elm = rng.startContainer.childNodes[rng.startOffset]; } } // If the anchor node is a element instead of a text node then return this element //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1) // return sel.anchorNode.childNodes[sel.anchorOffset]; // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent. // This happens when you double click an underlined word in FireFox. if (start.nodeType === 3 && end.nodeType === 3) { if (start.length === rng.startOffset) { start = skipEmptyTextNodes(start.nextSibling, true); } else { start = start.parentNode; } if (rng.endOffset === 0) { end = skipEmptyTextNodes(end.previousSibling, false); } else { end = end.parentNode; } if (start && start === end) return start; } } if (elm && elm.nodeType == 3) return elm.parentNode; return elm; } return rng.item ? rng.item(0) : rng.parentElement(); }, getSelectedBlocks : function(st, en) { var t = this, dom = t.dom, sb, eb, n, bl = []; sb = dom.getParent(st || t.getStart(), dom.isBlock); eb = dom.getParent(en || t.getEnd(), dom.isBlock); if (sb) bl.push(sb); if (sb && eb && sb != eb) { n = sb; var walker = new TreeWalker(sb, dom.getRoot()); while ((n = walker.next()) && n != eb) { if (dom.isBlock(n)) bl.push(n); } } if (eb && sb != eb) bl.push(eb); return bl; }, normalize : function() { var self = this, rng, normalized, collapsed; function normalizeEndPoint(start) { var container, offset, walker, dom = self.dom, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; // Walks the dom left/right to find a suitable text node to move the endpoint into // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG function findTextNodeRelative(left, startNode) { var walker, lastInlineElement; startNode = startNode || container; walker = new TreeWalker(startNode, dom.getParent(startNode.parentNode, dom.isBlock) || body); // Walk left until we hit a text node we can move to or a block/br/img while (node = walker[left ? 'prev' : 'next']()) { // Found text node that has a length if (node.nodeType === 3 && node.nodeValue.length > 0) { container = node; offset = left ? node.nodeValue.length : 0; normalized = true; return; } // Break if we find a block or a BR/IMG/INPUT etc if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) { return; } lastInlineElement = node; } // Only fetch the last inline element when in caret mode for now if (collapsed && lastInlineElement) { container = lastInlineElement; normalized = true; offset = 0; } }; container = rng[(start ? 'start' : 'end') + 'Container']; offset = rng[(start ? 'start' : 'end') + 'Offset']; nonEmptyElementsMap = dom.schema.getNonEmptyElements(); // If the container is a document move it to the body element if (container.nodeType === 9) { container = container.body; offset = 0; } // If the container is body try move it into the closest text node or position if (container === body) { // If start is before/after a image, table etc if (start) { node = container.childNodes[offset > 0 ? offset - 1 : 0]; if (node) { nodeName = node.nodeName.toLowerCase(); if (nonEmptyElementsMap[node.nodeName] || node.nodeName == "TABLE") { return; } } } // Resolve the index if (container.hasChildNodes()) { container = container.childNodes[Math.min(!start && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1)]; offset = 0; // Don't walk into elements that doesn't have any child nodes like a IMG if (container.hasChildNodes()) { // Walk the DOM to find a text node to place the caret at or a BR node = container; walker = new TreeWalker(container, body); do { // Found a text node use that position if (node.nodeType === 3 && node.nodeValue.length > 0) { offset = start ? 0 : node.nodeValue.length; container = node; normalized = true; break; } // Found a BR/IMG element that we can place the caret before if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) { offset = dom.nodeIndex(node); container = node.parentNode; // Put caret after image when moving the end point if (node.nodeName == "IMG" && !start) { offset++; } normalized = true; break; } } while (node = (start ? walker.next() : walker.prev())); } } } // Lean the caret to the left if possible if (collapsed) { // So this: <b>x</b><i>|x</i> // Becomes: <b>x|</b><i>x</i> // Seems that only gecko has issues with this if (container.nodeType === 3 && offset === 0) { findTextNodeRelative(true); } // Lean left into empty inline elements when the caret is before a BR // So this: <i><b></b><i>|<br></i> // Becomes: <i><b>|</b><i><br></i> // Seems that only gecko has issues with this if (container.nodeType === 1 && container.childNodes[offset] && container.childNodes[offset].nodeName === 'BR') { findTextNodeRelative(true, container.childNodes[offset]); } } // Lean the start of the selection right if possible // So this: x[<b>x]</b> // Becomes: x<b>[x]</b> if (start && !collapsed && container.nodeType === 3 && offset === container.nodeValue.length) { findTextNodeRelative(false); } // Set endpoint if it was normalized if (normalized) rng['set' + (start ? 'Start' : 'End')](container, offset); }; // TODO: // Retain selection direction. // Normalize only on non IE browsers for now if (tinymce.isIE) return; rng = self.getRng(); collapsed = rng.collapsed; // Normalize the end points normalizeEndPoint(true); if (!collapsed) normalizeEndPoint(); // Set the selection if it was normalized if (normalized) { // If it was collapsed then make sure it still is if (collapsed) { rng.collapse(true); } //console.log(self.dom.dumpRng(rng)); self.setRng(rng); } }, destroy : function(s) { var t = this; t.win = null; // Manual destroy then remove unload handler if (!s) tinymce.removeUnload(t.destroy); }, // IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode _fixIESelection : function() { var dom = this.dom, doc = dom.doc, body = doc.body, started, startRng, htmlElm; // Return range from point or null if it failed function rngFromPoint(x, y) { var rng = body.createTextRange(); try { rng.moveToPoint(x, y); } catch (ex) { // IE sometimes throws and exception, so lets just ignore it rng = null; } return rng; }; // Fires while the selection is changing function selectionChange(e) { var pointRng; // Check if the button is down or not if (e.button) { // Create range from mouse position pointRng = rngFromPoint(e.x, e.y); if (pointRng) { // Check if pointRange is before/after selection then change the endPoint if (pointRng.compareEndPoints('StartToStart', startRng) > 0) pointRng.setEndPoint('StartToStart', startRng); else pointRng.setEndPoint('EndToEnd', startRng); pointRng.select(); } } else endSelection(); } // Removes listeners function endSelection() { var rng = doc.selection.createRange(); // If the range is collapsed then use the last start range if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) startRng.select(); dom.unbind(doc, 'mouseup', endSelection); dom.unbind(doc, 'mousemove', selectionChange); startRng = started = 0; }; // Make HTML element unselectable since we are going to handle selection by hand doc.documentElement.unselectable = true; // Detect when user selects outside BODY dom.bind(doc, ['mousedown', 'contextmenu'], function(e) { if (e.target.nodeName === 'HTML') { if (started) endSelection(); // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML htmlElm = doc.documentElement; if (htmlElm.scrollHeight > htmlElm.clientHeight) return; started = 1; // Setup start position startRng = rngFromPoint(e.x, e.y); if (startRng) { // Listen for selection change events dom.bind(doc, 'mouseup', endSelection); dom.bind(doc, 'mousemove', selectionChange); dom.win.focus(); startRng.select(); } } }); } }); })(tinymce); (function(tinymce) { tinymce.dom.Serializer = function(settings, dom, schema) { var onPreProcess, onPostProcess, isIE = tinymce.isIE, each = tinymce.each, htmlParser; // Support the old apply_source_formatting option if (!settings.apply_source_formatting) settings.indent = false; // Default DOM and Schema if they are undefined dom = dom || tinymce.DOM; schema = schema || new tinymce.html.Schema(settings); settings.entity_encoding = settings.entity_encoding || 'named'; settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; onPreProcess = new tinymce.util.Dispatcher(self); onPostProcess = new tinymce.util.Dispatcher(self); htmlParser = new tinymce.html.DomParser(settings, schema); // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { var i = nodes.length, node, value, internalName = 'data-mce-' + name, urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; while (i--) { node = nodes[i]; value = node.attributes.map[internalName]; if (value !== undef) { // Set external name to internal value and remove internal node.attr(name, value.length > 0 ? value : null); node.attr(internalName, null); } else { // No internal attribute found then convert the value we have in the DOM value = node.attributes.map[name]; if (name === "style") value = dom.serializeStyle(dom.parseStyle(value), node.name); else if (urlConverter) value = urlConverter.call(urlConverterScope, value, name, node.name); node.attr(name, value.length > 0 ? value : null); } } }); // Remove internal classes mceItem<..> htmlParser.addAttributeFilter('class', function(nodes, name) { var i = nodes.length, node, value; while (i--) { node = nodes[i]; value = node.attr('class').replace(/\s*mce(Item\w+|Selected)\s*/g, ''); node.attr('class', value.length > 0 ? value : null); } }); // Remove bookmark elements htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) node.remove(); } }); // Remove expando attributes htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name, args) { var i = nodes.length; while (i--) { nodes[i].attr(name, null); } }); // Force script into CDATA sections and remove the mce- prefix also add comments around styles htmlParser.addNodeFilter('script,style', function(nodes, name) { var i = nodes.length, node, value; function trim(value) { return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n') .replace(/^[\r\n]*|[\r\n]*$/g, '') .replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '') .replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); }; while (i--) { node = nodes[i]; value = node.firstChild ? node.firstChild.value : ''; if (name === "script") { // Remove mce- prefix from script elements node.attr('type', (node.attr('type') || 'text/javascript').replace(/^mce\-/, '')); if (value.length > 0) node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>'; } else { if (value.length > 0) node.firstChild.value = '<!--\n' + trim(value) + '\n-->'; } } }); // Convert comments to cdata and handle protected comments htmlParser.addNodeFilter('#comment', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.value.indexOf('[CDATA[') === 0) { node.name = '#cdata'; node.type = 4; node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); } else if (node.value.indexOf('mce:protected ') === 0) { node.name = "#text"; node.type = 3; node.raw = true; node.value = unescape(node.value).substr(14); } } }); htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; if (node.type === 7) node.remove(); else if (node.type === 1) { if (name === "input" && !("type" in node.attributes.map)) node.attr('type', 'text'); } } }); // Fix list elements, TODO: Replace this later if (settings.fix_list_elements) { htmlParser.addNodeFilter('ul,ol', function(nodes, name) { var i = nodes.length, node, parentNode; while (i--) { node = nodes[i]; parentNode = node.parent; if (parentNode.name === 'ul' || parentNode.name === 'ol') { if (node.prev && node.prev.name === 'li') { node.prev.append(node); } } } }); } // Remove internal data attributes htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style', function(nodes, name) { var i = nodes.length; while (i--) { nodes[i].attr(name, null); } }); // Return public methods return { schema : schema, addNodeFilter : htmlParser.addNodeFilter, addAttributeFilter : htmlParser.addAttributeFilter, onPreProcess : onPreProcess, onPostProcess : onPostProcess, serialize : function(node, args) { var impl, doc, oldDoc, htmlSerializer, content; // Explorer won't clone contents of script and style and the // selected index of select elements are cleared on a clone operation. if (isIE && dom.select('script,style,select,map').length > 0) { content = node.innerHTML; node = node.cloneNode(false); dom.setHTML(node, content); } else node = node.cloneNode(true); // Nodes needs to be attached to something in WebKit/Opera // Older builds of Opera crashes if you attach the node to an document created dynamically // and since we can't feature detect a crash we need to sniff the acutal build number // This fix will make DOM ranges and make Sizzle happy! impl = node.ownerDocument.implementation; if (impl.createHTMLDocument) { // Create an empty HTML document doc = impl.createHTMLDocument(""); // Add the element or it's children if it's a body element to the new document each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { doc.body.appendChild(doc.importNode(node, true)); }); // Grab first child or body element for serialization if (node.nodeName != 'BODY') node = doc.body.firstChild; else node = doc.body; // set the new document in DOMUtils so createElement etc works oldDoc = dom.doc; dom.doc = doc; } args = args || {}; args.format = args.format || 'html'; // Pre process if (!args.no_events) { args.node = node; onPreProcess.dispatch(self, args); } // Setup serializer htmlSerializer = new tinymce.html.Serializer(settings, schema); // Parse and serialize HTML args.content = htmlSerializer.serialize( htmlParser.parse(tinymce.trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) ); // Replace all BOM characters for now until we can find a better solution if (!args.cleanup) args.content = args.content.replace(/\uFEFF|\u200B/g, ''); // Post process if (!args.no_events) onPostProcess.dispatch(self, args); // Restore the old document if it was changed if (oldDoc) dom.doc = oldDoc; args.node = null; return args.content; }, addRules : function(rules) { schema.addValidElements(rules); }, setRules : function(rules) { schema.setValidElements(rules); } }; }; })(tinymce); (function(tinymce) { tinymce.dom.ScriptLoader = function(settings) { var QUEUED = 0, LOADING = 1, LOADED = 2, states = {}, queue = [], scriptLoadedCallbacks = {}, queueLoadedCallbacks = [], loading = 0, undef; function loadScript(url, callback) { var t = this, dom = tinymce.DOM, elm, uri, loc, id; // Execute callback when script is loaded function done() { dom.remove(id); if (elm) elm.onreadystatechange = elm.onload = elm = null; callback(); }; function error() { // Report the error so it's easier for people to spot loading errors if (typeof(console) !== "undefined" && console.log) console.log("Failed to load: " + url); // We can't mark it as done if there is a load error since // A) We don't want to produce 404 errors on the server and // B) the onerror event won't fire on all browsers. // done(); }; id = dom.uniqueId(); if (tinymce.isIE6) { uri = new tinymce.util.URI(url); loc = location; // If script is from same domain and we // use IE 6 then use XHR since it's more reliable if (uri.host == loc.hostname && uri.port == loc.port && (uri.protocol + ':') == loc.protocol && uri.protocol.toLowerCase() != 'file') { tinymce.util.XHR.send({ url : tinymce._addVer(uri.getURI()), success : function(content) { // Create new temp script element var script = dom.create('script', { type : 'text/javascript' }); // Evaluate script in global scope script.text = content; document.getElementsByTagName('head')[0].appendChild(script); dom.remove(script); done(); }, error : error }); return; } } // Create new script element elm = dom.create('script', { id : id, type : 'text/javascript', src : tinymce._addVer(url) }); // Add onload listener for non IE browsers since IE9 // fires onload event before the script is parsed and executed if (!tinymce.isIE) elm.onload = done; // Add onerror event will get fired on some browsers but not all of them elm.onerror = error; // Opera 9.60 doesn't seem to fire the onreadystate event at correctly if (!tinymce.isOpera) { elm.onreadystatechange = function() { var state = elm.readyState; // Loaded state is passed on IE 6 however there // are known issues with this method but we can't use // XHR in a cross domain loading if (state == 'complete' || state == 'loaded') done(); }; } // Most browsers support this feature so we report errors // for those at least to help users track their missing plugins etc // todo: Removed since it produced error if the document is unloaded by navigating away, re-add it as an option /*elm.onerror = function() { alert('Failed to load: ' + url); };*/ // Add script to document (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); }; this.isDone = function(url) { return states[url] == LOADED; }; this.markDone = function(url) { states[url] = LOADED; }; this.add = this.load = function(url, callback, scope) { var item, state = states[url]; // Add url to load queue if (state == undef) { queue.push(url); states[url] = QUEUED; } if (callback) { // Store away callback for later execution if (!scriptLoadedCallbacks[url]) scriptLoadedCallbacks[url] = []; scriptLoadedCallbacks[url].push({ func : callback, scope : scope || this }); } }; this.loadQueue = function(callback, scope) { this.loadScripts(queue, callback, scope); }; this.loadScripts = function(scripts, callback, scope) { var loadScripts; function execScriptLoadedCallbacks(url) { // Execute URL callback functions tinymce.each(scriptLoadedCallbacks[url], function(callback) { callback.func.call(callback.scope); }); scriptLoadedCallbacks[url] = undef; }; queueLoadedCallbacks.push({ func : callback, scope : scope || this }); loadScripts = function() { var loadingScripts = tinymce.grep(scripts); // Current scripts has been handled scripts.length = 0; // Load scripts that needs to be loaded tinymce.each(loadingScripts, function(url) { // Script is already loaded then execute script callbacks directly if (states[url] == LOADED) { execScriptLoadedCallbacks(url); return; } // Is script not loading then start loading it if (states[url] != LOADING) { states[url] = LOADING; loading++; loadScript(url, function() { states[url] = LOADED; loading--; execScriptLoadedCallbacks(url); // Load more scripts if they where added by the recently loaded script loadScripts(); }); } }); // No scripts are currently loading then execute all pending queue loaded callbacks if (!loading) { tinymce.each(queueLoadedCallbacks, function(callback) { callback.func.call(callback.scope); }); queueLoadedCallbacks.length = 0; } }; loadScripts(); }; }; // Global script loader tinymce.ScriptLoader = new tinymce.dom.ScriptLoader(); })(tinymce); (function(tinymce) { tinymce.dom.RangeUtils = function(dom) { var INVISIBLE_CHAR = '\uFEFF'; this.walk = function(rng, callback) { var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset, ancestor, startPoint, endPoint, node, parent, siblings, nodes; // Handle table cell selection the table plugin enables // you to fake select table cells and perform formatting actions on them nodes = dom.select('td.mceSelected,th.mceSelected'); if (nodes.length > 0) { tinymce.each(nodes, function(node) { callback([node]); }); return; } function exclude(nodes) { var node; // First node is excluded node = nodes[0]; if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { nodes.splice(0, 1); } // Last node is excluded node = nodes[nodes.length - 1]; if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { nodes.splice(nodes.length - 1, 1); } return nodes; }; function collectSiblings(node, name, end_node) { var siblings = []; for (; node && node != end_node; node = node[name]) siblings.push(node); return siblings; }; function findEndPoint(node, root) { do { if (node.parentNode == root) return node; node = node.parentNode; } while(node); }; function walkBoundary(start_node, end_node, next) { var siblingName = next ? 'nextSibling' : 'previousSibling'; for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { parent = node.parentNode; siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); if (siblings.length) { if (!next) siblings.reverse(); callback(exclude(siblings)); } } }; // If index based start position then resolve it if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) startContainer = startContainer.childNodes[startOffset]; // If index based end position then resolve it if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; // Same container if (startContainer == endContainer) return callback(exclude([startContainer])); // Find common ancestor and end points ancestor = dom.findCommonAncestor(startContainer, endContainer); // Process left side for (node = startContainer; node; node = node.parentNode) { if (node === endContainer) return walkBoundary(startContainer, ancestor, true); if (node === ancestor) break; } // Process right side for (node = endContainer; node; node = node.parentNode) { if (node === startContainer) return walkBoundary(endContainer, ancestor); if (node === ancestor) break; } // Find start/end point startPoint = findEndPoint(startContainer, ancestor) || startContainer; endPoint = findEndPoint(endContainer, ancestor) || endContainer; // Walk left leaf walkBoundary(startContainer, startPoint, true); // Walk the middle from start to end point siblings = collectSiblings( startPoint == startContainer ? startPoint : startPoint.nextSibling, 'nextSibling', endPoint == endContainer ? endPoint.nextSibling : endPoint ); if (siblings.length) callback(exclude(siblings)); // Walk right leaf walkBoundary(endContainer, endPoint); }; this.split = function(rng) { var startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset; function splitText(node, offset) { return node.splitText(offset); }; // Handle single text node if (startContainer == endContainer && startContainer.nodeType == 3) { if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { endContainer = splitText(startContainer, startOffset); startContainer = endContainer.previousSibling; if (endOffset > startOffset) { endOffset = endOffset - startOffset; startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; endOffset = endContainer.nodeValue.length; startOffset = 0; } else { endOffset = 0; } } } else { // Split startContainer text node if needed if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { startContainer = splitText(startContainer, startOffset); startOffset = 0; } // Split endContainer text node if needed if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { endContainer = splitText(endContainer, endOffset).previousSibling; endOffset = endContainer.nodeValue.length; } } return { startContainer : startContainer, startOffset : startOffset, endContainer : endContainer, endOffset : endOffset }; }; }; tinymce.dom.RangeUtils.compareRanges = function(rng1, rng2) { if (rng1 && rng2) { // Compare native IE ranges if (rng1.item || rng1.duplicate) { // Both are control ranges and the selected element matches if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0)) return true; // Both are text ranges and the range matches if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1)) return true; } else { // Compare w3c ranges return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset; } } return false; }; })(tinymce); (function(tinymce) { var Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.KeyboardNavigation', { KeyboardNavigation: function(settings, dom) { var t = this, root = settings.root, items = settings.items, enableUpDown = settings.enableUpDown, enableLeftRight = settings.enableLeftRight || !settings.enableUpDown, excludeFromTabOrder = settings.excludeFromTabOrder, itemFocussed, itemBlurred, rootKeydown, rootFocussed, focussedId; dom = dom || tinymce.DOM; itemFocussed = function(evt) { focussedId = evt.target.id; }; itemBlurred = function(evt) { dom.setAttrib(evt.target.id, 'tabindex', '-1'); }; rootFocussed = function(evt) { var item = dom.get(focussedId); dom.setAttrib(item, 'tabindex', '0'); item.focus(); }; t.focus = function() { dom.get(focussedId).focus(); }; t.destroy = function() { each(items, function(item) { dom.unbind(dom.get(item.id), 'focus', itemFocussed); dom.unbind(dom.get(item.id), 'blur', itemBlurred); }); dom.unbind(dom.get(root), 'focus', rootFocussed); dom.unbind(dom.get(root), 'keydown', rootKeydown); items = dom = root = t.focus = itemFocussed = itemBlurred = rootKeydown = rootFocussed = null; t.destroy = function() {}; }; t.moveFocus = function(dir, evt) { var idx = -1, controls = t.controls, newFocus; if (!focussedId) return; each(items, function(item, index) { if (item.id === focussedId) { idx = index; return false; } }); idx += dir; if (idx < 0) { idx = items.length - 1; } else if (idx >= items.length) { idx = 0; } newFocus = items[idx]; dom.setAttrib(focussedId, 'tabindex', '-1'); dom.setAttrib(newFocus.id, 'tabindex', '0'); dom.get(newFocus.id).focus(); if (settings.actOnFocus) { settings.onAction(newFocus.id); } if (evt) Event.cancel(evt); }; rootKeydown = function(evt) { var DOM_VK_LEFT = 37, DOM_VK_RIGHT = 39, DOM_VK_UP = 38, DOM_VK_DOWN = 40, DOM_VK_ESCAPE = 27, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_SPACE = 32; switch (evt.keyCode) { case DOM_VK_LEFT: if (enableLeftRight) t.moveFocus(-1); break; case DOM_VK_RIGHT: if (enableLeftRight) t.moveFocus(1); break; case DOM_VK_UP: if (enableUpDown) t.moveFocus(-1); break; case DOM_VK_DOWN: if (enableUpDown) t.moveFocus(1); break; case DOM_VK_ESCAPE: if (settings.onCancel) { settings.onCancel(); Event.cancel(evt); } break; case DOM_VK_ENTER: case DOM_VK_RETURN: case DOM_VK_SPACE: if (settings.onAction) { settings.onAction(focussedId); Event.cancel(evt); } break; } }; // Set up state and listeners for each item. each(items, function(item, idx) { var tabindex; if (!item.id) { item.id = dom.uniqueId('_mce_item_'); } if (excludeFromTabOrder) { dom.bind(item.id, 'blur', itemBlurred); tabindex = '-1'; } else { tabindex = (idx === 0 ? '0' : '-1'); } dom.setAttrib(item.id, 'tabindex', tabindex); dom.bind(dom.get(item.id), 'focus', itemFocussed); }); // Setup initial state for root element. if (items[0]){ focussedId = items[0].id; } dom.setAttrib(root, 'tabindex', '-1'); // Setup listeners for root element. dom.bind(dom.get(root), 'focus', rootFocussed); dom.bind(dom.get(root), 'keydown', rootKeydown); } }); })(tinymce); (function(tinymce) { // Shorten class names var DOM = tinymce.DOM, is = tinymce.is; tinymce.create('tinymce.ui.Control', { Control : function(id, s, editor) { this.id = id; this.settings = s = s || {}; this.rendered = false; this.onRender = new tinymce.util.Dispatcher(this); this.classPrefix = ''; this.scope = s.scope || this; this.disabled = 0; this.active = 0; this.editor = editor; }, setAriaProperty : function(property, value) { var element = DOM.get(this.id + '_aria') || DOM.get(this.id); if (element) { DOM.setAttrib(element, 'aria-' + property, !!value); } }, focus : function() { DOM.get(this.id).focus(); }, setDisabled : function(s) { if (s != this.disabled) { this.setAriaProperty('disabled', s); this.setState('Disabled', s); this.setState('Enabled', !s); this.disabled = s; } }, isDisabled : function() { return this.disabled; }, setActive : function(s) { if (s != this.active) { this.setState('Active', s); this.active = s; this.setAriaProperty('pressed', s); } }, isActive : function() { return this.active; }, setState : function(c, s) { var n = DOM.get(this.id); c = this.classPrefix + c; if (s) DOM.addClass(n, c); else DOM.removeClass(n, c); }, isRendered : function() { return this.rendered; }, renderHTML : function() { }, renderTo : function(n) { DOM.setHTML(n, this.renderHTML()); }, postRender : function() { var t = this, b; // Set pending states if (is(t.disabled)) { b = t.disabled; t.disabled = -1; t.setDisabled(b); } if (is(t.active)) { b = t.active; t.active = -1; t.setActive(b); } }, remove : function() { DOM.remove(this.id); this.destroy(); }, destroy : function() { tinymce.dom.Event.clear(this.id); } }); })(tinymce); tinymce.create('tinymce.ui.Container:tinymce.ui.Control', { Container : function(id, s, editor) { this.parent(id, s, editor); this.controls = []; this.lookup = {}; }, add : function(c) { this.lookup[c.id] = c; this.controls.push(c); return c; }, get : function(n) { return this.lookup[n]; } }); tinymce.create('tinymce.ui.Separator:tinymce.ui.Control', { Separator : function(id, s) { this.parent(id, s); this.classPrefix = 'mceSeparator'; this.setDisabled(true); }, renderHTML : function() { return tinymce.DOM.createHTML('span', {'class' : this.classPrefix, role : 'separator', 'aria-orientation' : 'vertical', tabindex : '-1'}); } }); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk; tinymce.create('tinymce.ui.MenuItem:tinymce.ui.Control', { MenuItem : function(id, s) { this.parent(id, s); this.classPrefix = 'mceMenuItem'; }, setSelected : function(s) { this.setState('Selected', s); this.setAriaProperty('checked', !!s); this.selected = s; }, isSelected : function() { return this.selected; }, postRender : function() { var t = this; t.parent(); // Set pending state if (is(t.selected)) t.setSelected(t.selected); } }); })(tinymce); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, walk = tinymce.walk; tinymce.create('tinymce.ui.Menu:tinymce.ui.MenuItem', { Menu : function(id, s) { var t = this; t.parent(id, s); t.items = {}; t.collapsed = false; t.menuCount = 0; t.onAddItem = new tinymce.util.Dispatcher(this); }, expand : function(d) { var t = this; if (d) { walk(t, function(o) { if (o.expand) o.expand(); }, 'items', t); } t.collapsed = false; }, collapse : function(d) { var t = this; if (d) { walk(t, function(o) { if (o.collapse) o.collapse(); }, 'items', t); } t.collapsed = true; }, isCollapsed : function() { return this.collapsed; }, add : function(o) { if (!o.settings) o = new tinymce.ui.MenuItem(o.id || DOM.uniqueId(), o); this.onAddItem.dispatch(this, o); return this.items[o.id] = o; }, addSeparator : function() { return this.add({separator : true}); }, addMenu : function(o) { if (!o.collapse) o = this.createMenu(o); this.menuCount++; return this.add(o); }, hasMenus : function() { return this.menuCount !== 0; }, remove : function(o) { delete this.items[o.id]; }, removeAll : function() { var t = this; walk(t, function(o) { if (o.removeAll) o.removeAll(); else o.remove(); o.destroy(); }, 'items', t); t.items = {}; }, createMenu : function(o) { var m = new tinymce.ui.Menu(o.id || DOM.uniqueId(), o); m.onAddItem.add(this.onAddItem.dispatch, this.onAddItem); return m; } }); })(tinymce); (function(tinymce) { var is = tinymce.is, DOM = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event, Element = tinymce.dom.Element; tinymce.create('tinymce.ui.DropMenu:tinymce.ui.Menu', { DropMenu : function(id, s) { s = s || {}; s.container = s.container || DOM.doc.body; s.offset_x = s.offset_x || 0; s.offset_y = s.offset_y || 0; s.vp_offset_x = s.vp_offset_x || 0; s.vp_offset_y = s.vp_offset_y || 0; if (is(s.icons) && !s.icons) s['class'] += ' mceNoIcons'; this.parent(id, s); this.onShowMenu = new tinymce.util.Dispatcher(this); this.onHideMenu = new tinymce.util.Dispatcher(this); this.classPrefix = 'mceMenu'; }, createMenu : function(s) { var t = this, cs = t.settings, m; s.container = s.container || cs.container; s.parent = t; s.constrain = s.constrain || cs.constrain; s['class'] = s['class'] || cs['class']; s.vp_offset_x = s.vp_offset_x || cs.vp_offset_x; s.vp_offset_y = s.vp_offset_y || cs.vp_offset_y; s.keyboard_focus = cs.keyboard_focus; m = new tinymce.ui.DropMenu(s.id || DOM.uniqueId(), s); m.onAddItem.add(t.onAddItem.dispatch, t.onAddItem); return m; }, focus : function() { var t = this; if (t.keyboardNav) { t.keyboardNav.focus(); } }, update : function() { var t = this, s = t.settings, tb = DOM.get('menu_' + t.id + '_tbl'), co = DOM.get('menu_' + t.id + '_co'), tw, th; tw = s.max_width ? Math.min(tb.clientWidth, s.max_width) : tb.clientWidth; th = s.max_height ? Math.min(tb.clientHeight, s.max_height) : tb.clientHeight; if (!DOM.boxModel) t.element.setStyles({width : tw + 2, height : th + 2}); else t.element.setStyles({width : tw, height : th}); if (s.max_width) DOM.setStyle(co, 'width', tw); if (s.max_height) { DOM.setStyle(co, 'height', th); if (tb.clientHeight < s.max_height) DOM.setStyle(co, 'overflow', 'hidden'); } }, showMenu : function(x, y, px) { var t = this, s = t.settings, co, vp = DOM.getViewPort(), w, h, mx, my, ot = 2, dm, tb, cp = t.classPrefix; t.collapse(1); if (t.isMenuVisible) return; if (!t.rendered) { co = DOM.add(t.settings.container, t.renderNode()); each(t.items, function(o) { o.postRender(); }); t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container}); } else co = DOM.get('menu_' + t.id); // Move layer out of sight unless it's Opera since it scrolls to top of page due to an bug if (!tinymce.isOpera) DOM.setStyles(co, {left : -0xFFFF , top : -0xFFFF}); DOM.show(co); t.update(); x += s.offset_x || 0; y += s.offset_y || 0; vp.w -= 4; vp.h -= 4; // Move inside viewport if not submenu if (s.constrain) { w = co.clientWidth - ot; h = co.clientHeight - ot; mx = vp.x + vp.w; my = vp.y + vp.h; if ((x + s.vp_offset_x + w) > mx) x = px ? px - w : Math.max(0, (mx - s.vp_offset_x) - w); if ((y + s.vp_offset_y + h) > my) y = Math.max(0, (my - s.vp_offset_y) - h); } DOM.setStyles(co, {left : x , top : y}); t.element.update(); t.isMenuVisible = 1; t.mouseClickFunc = Event.add(co, 'click', function(e) { var m; e = e.target; if (e && (e = DOM.getParent(e, 'tr')) && !DOM.hasClass(e, cp + 'ItemSub')) { m = t.items[e.id]; if (m.isDisabled()) return; dm = t; while (dm) { if (dm.hideMenu) dm.hideMenu(); dm = dm.settings.parent; } if (m.settings.onclick) m.settings.onclick(e); return false; // Cancel to fix onbeforeunload problem } }); if (t.hasMenus()) { t.mouseOverFunc = Event.add(co, 'mouseover', function(e) { var m, r, mi; e = e.target; if (e && (e = DOM.getParent(e, 'tr'))) { m = t.items[e.id]; if (t.lastMenu) t.lastMenu.collapse(1); if (m.isDisabled()) return; if (e && DOM.hasClass(e, cp + 'ItemSub')) { //p = DOM.getPos(s.container); r = DOM.getRect(e); m.showMenu((r.x + r.w - ot), r.y - ot, r.x); t.lastMenu = m; DOM.addClass(DOM.get(m.id).firstChild, cp + 'ItemActive'); } } }); } Event.add(co, 'keydown', t._keyHandler, t); t.onShowMenu.dispatch(t); if (s.keyboard_focus) { t._setupKeyboardNav(); } }, hideMenu : function(c) { var t = this, co = DOM.get('menu_' + t.id), e; if (!t.isMenuVisible) return; if (t.keyboardNav) t.keyboardNav.destroy(); Event.remove(co, 'mouseover', t.mouseOverFunc); Event.remove(co, 'click', t.mouseClickFunc); Event.remove(co, 'keydown', t._keyHandler); DOM.hide(co); t.isMenuVisible = 0; if (!c) t.collapse(1); if (t.element) t.element.hide(); if (e = DOM.get(t.id)) DOM.removeClass(e.firstChild, t.classPrefix + 'ItemActive'); t.onHideMenu.dispatch(t); }, add : function(o) { var t = this, co; o = t.parent(o); if (t.isRendered && (co = DOM.get('menu_' + t.id))) t._add(DOM.select('tbody', co)[0], o); return o; }, collapse : function(d) { this.parent(d); this.hideMenu(1); }, remove : function(o) { DOM.remove(o.id); this.destroy(); return this.parent(o); }, destroy : function() { var t = this, co = DOM.get('menu_' + t.id); if (t.keyboardNav) t.keyboardNav.destroy(); Event.remove(co, 'mouseover', t.mouseOverFunc); Event.remove(DOM.select('a', co), 'focus', t.mouseOverFunc); Event.remove(co, 'click', t.mouseClickFunc); Event.remove(co, 'keydown', t._keyHandler); if (t.element) t.element.remove(); DOM.remove(co); }, renderNode : function() { var t = this, s = t.settings, n, tb, co, w; w = DOM.create('div', {role: 'listbox', id : 'menu_' + t.id, 'class' : s['class'], 'style' : 'position:absolute;left:0;top:0;z-index:200000;outline:0'}); if (t.settings.parent) { DOM.setAttrib(w, 'aria-parent', 'menu_' + t.settings.parent.id); } co = DOM.add(w, 'div', {role: 'presentation', id : 'menu_' + t.id + '_co', 'class' : t.classPrefix + (s['class'] ? ' ' + s['class'] : '')}); t.element = new Element('menu_' + t.id, {blocker : 1, container : s.container}); if (s.menu_line) DOM.add(co, 'span', {'class' : t.classPrefix + 'Line'}); // n = DOM.add(co, 'div', {id : 'menu_' + t.id + '_co', 'class' : 'mceMenuContainer'}); n = DOM.add(co, 'table', {role: 'presentation', id : 'menu_' + t.id + '_tbl', border : 0, cellPadding : 0, cellSpacing : 0}); tb = DOM.add(n, 'tbody'); each(t.items, function(o) { t._add(tb, o); }); t.rendered = true; return w; }, // Internal functions _setupKeyboardNav : function(){ var contextMenu, menuItems, t=this; contextMenu = DOM.get('menu_' + t.id); menuItems = DOM.select('a[role=option]', 'menu_' + t.id); menuItems.splice(0,0,contextMenu); t.keyboardNav = new tinymce.ui.KeyboardNavigation({ root: 'menu_' + t.id, items: menuItems, onCancel: function() { t.hideMenu(); }, enableUpDown: true }); contextMenu.focus(); }, _keyHandler : function(evt) { var t = this, e; switch (evt.keyCode) { case 37: // Left if (t.settings.parent) { t.hideMenu(); t.settings.parent.focus(); Event.cancel(evt); } break; case 39: // Right if (t.mouseOverFunc) t.mouseOverFunc(evt); break; } }, _add : function(tb, o) { var n, s = o.settings, a, ro, it, cp = this.classPrefix, ic; if (s.separator) { ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'ItemSeparator'}); DOM.add(ro, 'td', {'class' : cp + 'ItemSeparator'}); if (n = ro.previousSibling) DOM.addClass(n, 'mceLast'); return; } n = ro = DOM.add(tb, 'tr', {id : o.id, 'class' : cp + 'Item ' + cp + 'ItemEnabled'}); n = it = DOM.add(n, s.titleItem ? 'th' : 'td'); n = a = DOM.add(n, 'a', {id: o.id + '_aria', role: s.titleItem ? 'presentation' : 'option', href : 'javascript:;', onclick : "return false;", onmousedown : 'return false;'}); if (s.parent) { DOM.setAttrib(a, 'aria-haspopup', 'true'); DOM.setAttrib(a, 'aria-owns', 'menu_' + o.id); } DOM.addClass(it, s['class']); // n = DOM.add(n, 'span', {'class' : 'item'}); ic = DOM.add(n, 'span', {'class' : 'mceIcon' + (s.icon ? ' mce_' + s.icon : '')}); if (s.icon_src) DOM.add(ic, 'img', {src : s.icon_src}); n = DOM.add(n, s.element || 'span', {'class' : 'mceText', title : o.settings.title}, o.settings.title); if (o.settings.style) { if (typeof o.settings.style == "function") o.settings.style = o.settings.style(); DOM.setAttrib(n, 'style', o.settings.style); } if (tb.childNodes.length == 1) DOM.addClass(ro, 'mceFirst'); if ((n = ro.previousSibling) && DOM.hasClass(n, cp + 'ItemSeparator')) DOM.addClass(ro, 'mceFirst'); if (o.collapse) DOM.addClass(ro, cp + 'ItemSub'); if (n = ro.previousSibling) DOM.removeClass(n, 'mceLast'); DOM.addClass(ro, 'mceLast'); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM; tinymce.create('tinymce.ui.Button:tinymce.ui.Control', { Button : function(id, s, ed) { this.parent(id, s, ed); this.classPrefix = 'mceButton'; }, renderHTML : function() { var cp = this.classPrefix, s = this.settings, h, l; l = DOM.encode(s.label || ''); h = '<a role="button" id="' + this.id + '" href="javascript:;" class="' + cp + ' ' + cp + 'Enabled ' + s['class'] + (l ? ' ' + cp + 'Labeled' : '') +'" onmousedown="return false;" onclick="return false;" aria-labelledby="' + this.id + '_voice" title="' + DOM.encode(s.title) + '">'; if (s.image && !(this.editor &&this.editor.forcedHighContrastMode) ) h += '<img class="mceIcon" src="' + s.image + '" alt="' + DOM.encode(s.title) + '" />' + l; else h += '<span class="mceIcon ' + s['class'] + '"></span>' + (l ? '<span class="' + cp + 'Label">' + l + '</span>' : ''); h += '<span class="mceVoiceLabel mceIconOnly" style="display: none;" id="' + this.id + '_voice">' + s.title + '</span>'; h += '</a>'; return h; }, postRender : function() { var t = this, s = t.settings, imgBookmark; // In IE a large image that occupies the entire editor area will be deselected when a button is clicked, so // need to keep the selection in case the selection is lost if (tinymce.isIE && t.editor) { tinymce.dom.Event.add(t.id, 'mousedown', function(e) { var nodeName = t.editor.selection.getNode().nodeName; imgBookmark = nodeName === 'IMG' ? t.editor.selection.getBookmark() : null; }); } tinymce.dom.Event.add(t.id, 'click', function(e) { if (!t.isDisabled()) { // restore the selection in case the selection is lost in IE if (tinymce.isIE && t.editor && imgBookmark !== null) { t.editor.selection.moveToBookmark(imgBookmark); } return s.onclick.call(s.scope, e); } }); tinymce.dom.Event.add(t.id, 'keyup', function(e) { if (!t.isDisabled() && e.keyCode==tinymce.VK.SPACEBAR) return s.onclick.call(s.scope, e); }); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef; tinymce.create('tinymce.ui.ListBox:tinymce.ui.Control', { ListBox : function(id, s, ed) { var t = this; t.parent(id, s, ed); t.items = []; t.onChange = new Dispatcher(t); t.onPostRender = new Dispatcher(t); t.onAdd = new Dispatcher(t); t.onRenderMenu = new tinymce.util.Dispatcher(this); t.classPrefix = 'mceListBox'; t.marked = {}; }, select : function(va) { var t = this, fv, f; t.marked = {}; if (va == undef) return t.selectByIndex(-1); // Is string or number make function selector if (va && typeof(va)=="function") f = va; else { f = function(v) { return v == va; }; } // Do we need to do something? if (va != t.selectedValue) { // Find item each(t.items, function(o, i) { if (f(o.value)) { fv = 1; t.selectByIndex(i); return false; } }); if (!fv) t.selectByIndex(-1); } }, selectByIndex : function(idx) { var t = this, e, o, label; t.marked = {}; if (idx != t.selectedIndex) { e = DOM.get(t.id + '_text'); label = DOM.get(t.id + '_voiceDesc'); o = t.items[idx]; if (o) { t.selectedValue = o.value; t.selectedIndex = idx; DOM.setHTML(e, DOM.encode(o.title)); DOM.setHTML(label, t.settings.title + " - " + o.title); DOM.removeClass(e, 'mceTitle'); DOM.setAttrib(t.id, 'aria-valuenow', o.title); } else { DOM.setHTML(e, DOM.encode(t.settings.title)); DOM.setHTML(label, DOM.encode(t.settings.title)); DOM.addClass(e, 'mceTitle'); t.selectedValue = t.selectedIndex = null; DOM.setAttrib(t.id, 'aria-valuenow', t.settings.title); } e = 0; } }, mark : function(value) { this.marked[value] = true; }, add : function(n, v, o) { var t = this; o = o || {}; o = tinymce.extend(o, { title : n, value : v }); t.items.push(o); t.onAdd.dispatch(t, o); }, getLength : function() { return this.items.length; }, renderHTML : function() { var h = '', t = this, s = t.settings, cp = t.classPrefix; h = '<span role="listbox" aria-haspopup="true" aria-labelledby="' + t.id +'_voiceDesc" aria-describedby="' + t.id + '_voiceDesc"><table role="presentation" tabindex="0" id="' + t.id + '" cellpadding="0" cellspacing="0" class="' + cp + ' ' + cp + 'Enabled' + (s['class'] ? (' ' + s['class']) : '') + '"><tbody><tr>'; h += '<td>' + DOM.createHTML('span', {id: t.id + '_voiceDesc', 'class': 'voiceLabel', style:'display:none;'}, t.settings.title); h += DOM.createHTML('a', {id : t.id + '_text', tabindex : -1, href : 'javascript:;', 'class' : 'mceText', onclick : "return false;", onmousedown : 'return false;'}, DOM.encode(t.settings.title)) + '</td>'; h += '<td>' + DOM.createHTML('a', {id : t.id + '_open', tabindex : -1, href : 'javascript:;', 'class' : 'mceOpen', onclick : "return false;", onmousedown : 'return false;'}, '<span><span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span></span>') + '</td>'; h += '</tr></tbody></table></span>'; return h; }, showMenu : function() { var t = this, p2, e = DOM.get(this.id), m; if (t.isDisabled() || t.items.length === 0) return; if (t.menu && t.menu.isMenuVisible) return t.hideMenu(); if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } p2 = DOM.getPos(e); m = t.menu; m.settings.offset_x = p2.x; m.settings.offset_y = p2.y; m.settings.keyboard_focus = !tinymce.isOpera; // Opera is buggy when it comes to auto focus // Select in menu each(t.items, function(o) { if (m.items[o.id]) { m.items[o.id].setSelected(0); } }); each(t.items, function(o) { if (m.items[o.id] && t.marked[o.value]) { m.items[o.id].setSelected(1); } if (o.value === t.selectedValue) { m.items[o.id].setSelected(1); } }); m.showMenu(0, e.clientHeight); Event.add(DOM.doc, 'mousedown', t.hideMenu, t); DOM.addClass(t.id, t.classPrefix + 'Selected'); //DOM.get(t.id + '_text').focus(); }, hideMenu : function(e) { var t = this; if (t.menu && t.menu.isMenuVisible) { DOM.removeClass(t.id, t.classPrefix + 'Selected'); // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && (e.target.id == t.id + '_text' || e.target.id == t.id + '_open')) return; if (!e || !DOM.getParent(e.target, '.mceMenu')) { DOM.removeClass(t.id, t.classPrefix + 'Selected'); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); t.menu.hideMenu(); } } }, renderMenu : function() { var t = this, m; m = t.settings.control_manager.createDropMenu(t.id + '_menu', { menu_line : 1, 'class' : t.classPrefix + 'Menu mceNoIcons', max_width : 150, max_height : 150 }); m.onHideMenu.add(function() { t.hideMenu(); t.focus(); }); m.add({ title : t.settings.title, 'class' : 'mceMenuItemTitle', onclick : function() { if (t.settings.onselect('') !== false) t.select(''); // Must be runned after } }); each(t.items, function(o) { // No value then treat it as a title if (o.value === undef) { m.add({ title : o.title, role : "option", 'class' : 'mceMenuItemTitle', onclick : function() { if (t.settings.onselect('') !== false) t.select(''); // Must be runned after } }); } else { o.id = DOM.uniqueId(); o.role= "option"; o.onclick = function() { if (t.settings.onselect(o.value) !== false) t.select(o.value); // Must be runned after }; m.add(o); } }); t.onRenderMenu.dispatch(t, m); t.menu = m; }, postRender : function() { var t = this, cp = t.classPrefix; Event.add(t.id, 'click', t.showMenu, t); Event.add(t.id, 'keydown', function(evt) { if (evt.keyCode == 32) { // Space t.showMenu(evt); Event.cancel(evt); } }); Event.add(t.id, 'focus', function() { if (!t._focused) { t.keyDownHandler = Event.add(t.id, 'keydown', function(e) { if (e.keyCode == 40) { t.showMenu(); Event.cancel(e); } }); t.keyPressHandler = Event.add(t.id, 'keypress', function(e) { var v; if (e.keyCode == 13) { // Fake select on enter v = t.selectedValue; t.selectedValue = null; // Needs to be null to fake change Event.cancel(e); t.settings.onselect(v); } }); } t._focused = 1; }); Event.add(t.id, 'blur', function() { Event.remove(t.id, 'keydown', t.keyDownHandler); Event.remove(t.id, 'keypress', t.keyPressHandler); t._focused = 0; }); // Old IE doesn't have hover on all elements if (tinymce.isIE6 || !DOM.boxModel) { Event.add(t.id, 'mouseover', function() { if (!DOM.hasClass(t.id, cp + 'Disabled')) DOM.addClass(t.id, cp + 'Hover'); }); Event.add(t.id, 'mouseout', function() { if (!DOM.hasClass(t.id, cp + 'Disabled')) DOM.removeClass(t.id, cp + 'Hover'); }); } t.onPostRender.dispatch(t, DOM.get(t.id)); }, destroy : function() { this.parent(); Event.clear(this.id + '_text'); Event.clear(this.id + '_open'); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, Dispatcher = tinymce.util.Dispatcher, undef; tinymce.create('tinymce.ui.NativeListBox:tinymce.ui.ListBox', { NativeListBox : function(id, s) { this.parent(id, s); this.classPrefix = 'mceNativeListBox'; }, setDisabled : function(s) { DOM.get(this.id).disabled = s; this.setAriaProperty('disabled', s); }, isDisabled : function() { return DOM.get(this.id).disabled; }, select : function(va) { var t = this, fv, f; if (va == undef) return t.selectByIndex(-1); // Is string or number make function selector if (va && typeof(va)=="function") f = va; else { f = function(v) { return v == va; }; } // Do we need to do something? if (va != t.selectedValue) { // Find item each(t.items, function(o, i) { if (f(o.value)) { fv = 1; t.selectByIndex(i); return false; } }); if (!fv) t.selectByIndex(-1); } }, selectByIndex : function(idx) { DOM.get(this.id).selectedIndex = idx + 1; this.selectedValue = this.items[idx] ? this.items[idx].value : null; }, add : function(n, v, a) { var o, t = this; a = a || {}; a.value = v; if (t.isRendered()) DOM.add(DOM.get(this.id), 'option', a, n); o = { title : n, value : v, attribs : a }; t.items.push(o); t.onAdd.dispatch(t, o); }, getLength : function() { return this.items.length; }, renderHTML : function() { var h, t = this; h = DOM.createHTML('option', {value : ''}, '-- ' + t.settings.title + ' --'); each(t.items, function(it) { h += DOM.createHTML('option', {value : it.value}, it.title); }); h = DOM.createHTML('select', {id : t.id, 'class' : 'mceNativeListBox', 'aria-labelledby': t.id + '_aria'}, h); h += DOM.createHTML('span', {id : t.id + '_aria', 'style': 'display: none'}, t.settings.title); return h; }, postRender : function() { var t = this, ch, changeListenerAdded = true; t.rendered = true; function onChange(e) { var v = t.items[e.target.selectedIndex - 1]; if (v && (v = v.value)) { t.onChange.dispatch(t, v); if (t.settings.onselect) t.settings.onselect(v); } }; Event.add(t.id, 'change', onChange); // Accessibility keyhandler Event.add(t.id, 'keydown', function(e) { var bf; Event.remove(t.id, 'change', ch); changeListenerAdded = false; bf = Event.add(t.id, 'blur', function() { if (changeListenerAdded) return; changeListenerAdded = true; Event.add(t.id, 'change', onChange); Event.remove(t.id, 'blur', bf); }); //prevent default left and right keys on chrome - so that the keyboard navigation is used. if (tinymce.isWebKit && (e.keyCode==37 ||e.keyCode==39)) { return Event.prevent(e); } if (e.keyCode == 13 || e.keyCode == 32) { onChange(e); return Event.cancel(e); } }); t.onPostRender.dispatch(t, DOM.get(t.id)); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.MenuButton:tinymce.ui.Button', { MenuButton : function(id, s, ed) { this.parent(id, s, ed); this.onRenderMenu = new tinymce.util.Dispatcher(this); s.menu_container = s.menu_container || DOM.doc.body; }, showMenu : function() { var t = this, p1, p2, e = DOM.get(t.id), m; if (t.isDisabled()) return; if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } if (t.isMenuVisible) return t.hideMenu(); p1 = DOM.getPos(t.settings.menu_container); p2 = DOM.getPos(e); m = t.menu; m.settings.offset_x = p2.x; m.settings.offset_y = p2.y; m.settings.vp_offset_x = p2.x; m.settings.vp_offset_y = p2.y; m.settings.keyboard_focus = t._focused; m.showMenu(0, e.firstChild.clientHeight); Event.add(DOM.doc, 'mousedown', t.hideMenu, t); t.setState('Selected', 1); t.isMenuVisible = 1; }, renderMenu : function() { var t = this, m; m = t.settings.control_manager.createDropMenu(t.id + '_menu', { menu_line : 1, 'class' : this.classPrefix + 'Menu', icons : t.settings.icons }); m.onHideMenu.add(function() { t.hideMenu(); t.focus(); }); t.onRenderMenu.dispatch(t, m); t.menu = m; }, hideMenu : function(e) { var t = this; // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id || e.id === t.id + '_open';})) return; if (!e || !DOM.getParent(e.target, '.mceMenu')) { t.setState('Selected', 0); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); if (t.menu) t.menu.hideMenu(); } t.isMenuVisible = 0; }, postRender : function() { var t = this, s = t.settings; Event.add(t.id, 'click', function() { if (!t.isDisabled()) { if (s.onclick) s.onclick(t.value); t.showMenu(); } }); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each; tinymce.create('tinymce.ui.SplitButton:tinymce.ui.MenuButton', { SplitButton : function(id, s, ed) { this.parent(id, s, ed); this.classPrefix = 'mceSplitButton'; }, renderHTML : function() { var h, t = this, s = t.settings, h1; h = '<tbody><tr>'; if (s.image) h1 = DOM.createHTML('img ', {src : s.image, role: 'presentation', 'class' : 'mceAction ' + s['class']}); else h1 = DOM.createHTML('span', {'class' : 'mceAction ' + s['class']}, ''); h1 += DOM.createHTML('span', {'class': 'mceVoiceLabel mceIconOnly', id: t.id + '_voice', style: 'display:none;'}, s.title); h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_action', tabindex: '-1', href : 'javascript:;', 'class' : 'mceAction ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>'; h1 = DOM.createHTML('span', {'class' : 'mceOpen ' + s['class']}, '<span style="display:none;" class="mceIconOnly" aria-hidden="true">\u25BC</span>'); h += '<td >' + DOM.createHTML('a', {role: 'button', id : t.id + '_open', tabindex: '-1', href : 'javascript:;', 'class' : 'mceOpen ' + s['class'], onclick : "return false;", onmousedown : 'return false;', title : s.title}, h1) + '</td>'; h += '</tr></tbody>'; h = DOM.createHTML('table', { role: 'presentation', 'class' : 'mceSplitButton mceSplitButtonEnabled ' + s['class'], cellpadding : '0', cellspacing : '0', title : s.title}, h); return DOM.createHTML('div', {id : t.id, role: 'button', tabindex: '0', 'aria-labelledby': t.id + '_voice', 'aria-haspopup': 'true'}, h); }, postRender : function() { var t = this, s = t.settings, activate; if (s.onclick) { activate = function(evt) { if (!t.isDisabled()) { s.onclick(t.value); Event.cancel(evt); } }; Event.add(t.id + '_action', 'click', activate); Event.add(t.id, ['click', 'keydown'], function(evt) { var DOM_VK_SPACE = 32, DOM_VK_ENTER = 14, DOM_VK_RETURN = 13, DOM_VK_UP = 38, DOM_VK_DOWN = 40; if ((evt.keyCode === 32 || evt.keyCode === 13 || evt.keyCode === 14) && !evt.altKey && !evt.ctrlKey && !evt.metaKey) { activate(); Event.cancel(evt); } else if (evt.type === 'click' || evt.keyCode === DOM_VK_DOWN) { t.showMenu(); Event.cancel(evt); } }); } Event.add(t.id + '_open', 'click', function (evt) { t.showMenu(); Event.cancel(evt); }); Event.add([t.id, t.id + '_open'], 'focus', function() {t._focused = 1;}); Event.add([t.id, t.id + '_open'], 'blur', function() {t._focused = 0;}); // Old IE doesn't have hover on all elements if (tinymce.isIE6 || !DOM.boxModel) { Event.add(t.id, 'mouseover', function() { if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled')) DOM.addClass(t.id, 'mceSplitButtonHover'); }); Event.add(t.id, 'mouseout', function() { if (!DOM.hasClass(t.id, 'mceSplitButtonDisabled')) DOM.removeClass(t.id, 'mceSplitButtonHover'); }); } }, destroy : function() { this.parent(); Event.clear(this.id + '_action'); Event.clear(this.id + '_open'); Event.clear(this.id); } }); })(tinymce); (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, is = tinymce.is, each = tinymce.each; tinymce.create('tinymce.ui.ColorSplitButton:tinymce.ui.SplitButton', { ColorSplitButton : function(id, s, ed) { var t = this; t.parent(id, s, ed); t.settings = s = tinymce.extend({ colors : '000000,993300,333300,003300,003366,000080,333399,333333,800000,FF6600,808000,008000,008080,0000FF,666699,808080,FF0000,FF9900,99CC00,339966,33CCCC,3366FF,800080,999999,FF00FF,FFCC00,FFFF00,00FF00,00FFFF,00CCFF,993366,C0C0C0,FF99CC,FFCC99,FFFF99,CCFFCC,CCFFFF,99CCFF,CC99FF,FFFFFF', grid_width : 8, default_color : '#888888' }, t.settings); t.onShowMenu = new tinymce.util.Dispatcher(t); t.onHideMenu = new tinymce.util.Dispatcher(t); t.value = s.default_color; }, showMenu : function() { var t = this, r, p, e, p2; if (t.isDisabled()) return; if (!t.isMenuRendered) { t.renderMenu(); t.isMenuRendered = true; } if (t.isMenuVisible) return t.hideMenu(); e = DOM.get(t.id); DOM.show(t.id + '_menu'); DOM.addClass(e, 'mceSplitButtonSelected'); p2 = DOM.getPos(e); DOM.setStyles(t.id + '_menu', { left : p2.x, top : p2.y + e.firstChild.clientHeight, zIndex : 200000 }); e = 0; Event.add(DOM.doc, 'mousedown', t.hideMenu, t); t.onShowMenu.dispatch(t); if (t._focused) { t._keyHandler = Event.add(t.id + '_menu', 'keydown', function(e) { if (e.keyCode == 27) t.hideMenu(); }); DOM.select('a', t.id + '_menu')[0].focus(); // Select first link } t.isMenuVisible = 1; }, hideMenu : function(e) { var t = this; if (t.isMenuVisible) { // Prevent double toogles by canceling the mouse click event to the button if (e && e.type == "mousedown" && DOM.getParent(e.target, function(e) {return e.id === t.id + '_open';})) return; if (!e || !DOM.getParent(e.target, '.mceSplitButtonMenu')) { DOM.removeClass(t.id, 'mceSplitButtonSelected'); Event.remove(DOM.doc, 'mousedown', t.hideMenu, t); Event.remove(t.id + '_menu', 'keydown', t._keyHandler); DOM.hide(t.id + '_menu'); } t.isMenuVisible = 0; t.onHideMenu.dispatch(); } }, renderMenu : function() { var t = this, m, i = 0, s = t.settings, n, tb, tr, w, context; w = DOM.add(s.menu_container, 'div', {role: 'listbox', id : t.id + '_menu', 'class' : s.menu_class + ' ' + s['class'], style : 'position:absolute;left:0;top:-1000px;'}); m = DOM.add(w, 'div', {'class' : s['class'] + ' mceSplitButtonMenu'}); DOM.add(m, 'span', {'class' : 'mceMenuLine'}); n = DOM.add(m, 'table', {role: 'presentation', 'class' : 'mceColorSplitMenu'}); tb = DOM.add(n, 'tbody'); // Generate color grid i = 0; each(is(s.colors, 'array') ? s.colors : s.colors.split(','), function(c) { c = c.replace(/^#/, ''); if (!i--) { tr = DOM.add(tb, 'tr'); i = s.grid_width - 1; } n = DOM.add(tr, 'td'); var settings = { href : 'javascript:;', style : { backgroundColor : '#' + c }, 'title': t.editor.getLang('colors.' + c, c), 'data-mce-color' : '#' + c }; // adding a proper ARIA role = button causes JAWS to read things incorrectly on IE. if (!tinymce.isIE ) { settings.role = 'option'; } n = DOM.add(n, 'a', settings); if (t.editor.forcedHighContrastMode) { n = DOM.add(n, 'canvas', { width: 16, height: 16, 'aria-hidden': 'true' }); if (n.getContext && (context = n.getContext("2d"))) { context.fillStyle = '#' + c; context.fillRect(0, 0, 16, 16); } else { // No point leaving a canvas element around if it's not supported for drawing on anyway. DOM.remove(n); } } }); if (s.more_colors_func) { n = DOM.add(tb, 'tr'); n = DOM.add(n, 'td', {colspan : s.grid_width, 'class' : 'mceMoreColors'}); n = DOM.add(n, 'a', {role: 'option', id : t.id + '_more', href : 'javascript:;', onclick : 'return false;', 'class' : 'mceMoreColors'}, s.more_colors_title); Event.add(n, 'click', function(e) { s.more_colors_func.call(s.more_colors_scope || this); return Event.cancel(e); // Cancel to fix onbeforeunload problem }); } DOM.addClass(m, 'mceColorSplitMenu'); new tinymce.ui.KeyboardNavigation({ root: t.id + '_menu', items: DOM.select('a', t.id + '_menu'), onCancel: function() { t.hideMenu(); t.focus(); } }); // Prevent IE from scrolling and hindering click to occur #4019 Event.add(t.id + '_menu', 'mousedown', function(e) {return Event.cancel(e);}); Event.add(t.id + '_menu', 'click', function(e) { var c; e = DOM.getParent(e.target, 'a', tb); if (e && e.nodeName.toLowerCase() == 'a' && (c = e.getAttribute('data-mce-color'))) t.setColor(c); return false; // Prevent IE auto save warning }); return w; }, setColor : function(c) { this.displayColor(c); this.hideMenu(); this.settings.onselect(c); }, displayColor : function(c) { var t = this; DOM.setStyle(t.id + '_preview', 'backgroundColor', c); t.value = c; }, postRender : function() { var t = this, id = t.id; t.parent(); DOM.add(id + '_action', 'div', {id : id + '_preview', 'class' : 'mceColorPreview'}); DOM.setStyle(t.id + '_preview', 'backgroundColor', t.value); }, destroy : function() { this.parent(); Event.clear(this.id + '_menu'); Event.clear(this.id + '_more'); DOM.remove(this.id + '_menu'); } }); })(tinymce); (function(tinymce) { // Shorten class names var dom = tinymce.DOM, each = tinymce.each, Event = tinymce.dom.Event; tinymce.create('tinymce.ui.ToolbarGroup:tinymce.ui.Container', { renderHTML : function() { var t = this, h = [], controls = t.controls, each = tinymce.each, settings = t.settings; h.push('<div id="' + t.id + '" role="group" aria-labelledby="' + t.id + '_voice">'); //TODO: ACC test this out - adding a role = application for getting the landmarks working well. h.push("<span role='application'>"); h.push('<span id="' + t.id + '_voice" class="mceVoiceLabel" style="display:none;">' + dom.encode(settings.name) + '</span>'); each(controls, function(toolbar) { h.push(toolbar.renderHTML()); }); h.push("</span>"); h.push('</div>'); return h.join(''); }, focus : function() { var t = this; dom.get(t.id).focus(); }, postRender : function() { var t = this, items = []; each(t.controls, function(toolbar) { each (toolbar.controls, function(control) { if (control.id) { items.push(control); } }); }); t.keyNav = new tinymce.ui.KeyboardNavigation({ root: t.id, items: items, onCancel: function() { //Move focus if webkit so that navigation back will read the item. if (tinymce.isWebKit) { dom.get(t.editor.id+"_ifr").focus(); } t.editor.focus(); }, excludeFromTabOrder: !t.settings.tab_focus_toolbar }); }, destroy : function() { var self = this; self.parent(); self.keyNav.destroy(); Event.clear(self.id); } }); })(tinymce); (function(tinymce) { // Shorten class names var dom = tinymce.DOM, each = tinymce.each; tinymce.create('tinymce.ui.Toolbar:tinymce.ui.Container', { renderHTML : function() { var t = this, h = '', c, co, s = t.settings, i, pr, nx, cl; cl = t.controls; for (i=0; i<cl.length; i++) { // Get current control, prev control, next control and if the control is a list box or not co = cl[i]; pr = cl[i - 1]; nx = cl[i + 1]; // Add toolbar start if (i === 0) { c = 'mceToolbarStart'; if (co.Button) c += ' mceToolbarStartButton'; else if (co.SplitButton) c += ' mceToolbarStartSplitButton'; else if (co.ListBox) c += ' mceToolbarStartListBox'; h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->')); } // Add toolbar end before list box and after the previous button // This is to fix the o2k7 editor skins if (pr && co.ListBox) { if (pr.Button || pr.SplitButton) h += dom.createHTML('td', {'class' : 'mceToolbarEnd'}, dom.createHTML('span', null, '<!-- IE -->')); } // Render control HTML // IE 8 quick fix, needed to propertly generate a hit area for anchors if (dom.stdMode) h += '<td style="position: relative">' + co.renderHTML() + '</td>'; else h += '<td>' + co.renderHTML() + '</td>'; // Add toolbar start after list box and before the next button // This is to fix the o2k7 editor skins if (nx && co.ListBox) { if (nx.Button || nx.SplitButton) h += dom.createHTML('td', {'class' : 'mceToolbarStart'}, dom.createHTML('span', null, '<!-- IE -->')); } } c = 'mceToolbarEnd'; if (co.Button) c += ' mceToolbarEndButton'; else if (co.SplitButton) c += ' mceToolbarEndSplitButton'; else if (co.ListBox) c += ' mceToolbarEndListBox'; h += dom.createHTML('td', {'class' : c}, dom.createHTML('span', null, '<!-- IE -->')); return dom.createHTML('table', {id : t.id, 'class' : 'mceToolbar' + (s['class'] ? ' ' + s['class'] : ''), cellpadding : '0', cellspacing : '0', align : t.settings.align || '', role: 'presentation', tabindex: '-1'}, '<tbody><tr>' + h + '</tr></tbody>'); } }); })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each; tinymce.create('tinymce.AddOnManager', { AddOnManager : function() { var self = this; self.items = []; self.urls = {}; self.lookup = {}; self.onAdd = new Dispatcher(self); }, get : function(n) { if (this.lookup[n]) { return this.lookup[n].instance; } else { return undefined; } }, dependencies : function(n) { var result; if (this.lookup[n]) { result = this.lookup[n].dependencies; } return result || []; }, requireLangPack : function(n) { var s = tinymce.settings; if (s && s.language && s.language_load !== false) tinymce.ScriptLoader.add(this.urls[n] + '/langs/' + s.language + '.js'); }, add : function(id, o, dependencies) { this.items.push(o); this.lookup[id] = {instance:o, dependencies:dependencies}; this.onAdd.dispatch(this, id, o); return o; }, createUrl: function(baseUrl, dep) { if (typeof dep === "object") { return dep } else { return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; } }, addComponents: function(pluginName, scripts) { var pluginUrl = this.urls[pluginName]; tinymce.each(scripts, function(script){ tinymce.ScriptLoader.add(pluginUrl+"/"+script); }); }, load : function(n, u, cb, s) { var t = this, url = u; function loadDependencies() { var dependencies = t.dependencies(n); tinymce.each(dependencies, function(dep) { var newUrl = t.createUrl(u, dep); t.load(newUrl.resource, newUrl, undefined, undefined); }); if (cb) { if (s) { cb.call(s); } else { cb.call(tinymce.ScriptLoader); } } } if (t.urls[n]) return; if (typeof u === "object") url = u.prefix + u.resource + u.suffix; if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) url = tinymce.baseURL + '/' + url; t.urls[n] = url.substring(0, url.lastIndexOf('/')); if (t.lookup[n]) { loadDependencies(); } else { tinymce.ScriptLoader.add(url, loadDependencies, s); } } }); // Create plugin and theme managers tinymce.PluginManager = new tinymce.AddOnManager(); tinymce.ThemeManager = new tinymce.AddOnManager(); }(tinymce)); (function(tinymce) { // Shorten names var each = tinymce.each, extend = tinymce.extend, DOM = tinymce.DOM, Event = tinymce.dom.Event, ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager, explode = tinymce.explode, Dispatcher = tinymce.util.Dispatcher, undef, instanceCounter = 0; // Setup some URLs where the editor API is located and where the document is tinymce.documentBaseURL = window.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); if (!/[\/\\]$/.test(tinymce.documentBaseURL)) tinymce.documentBaseURL += '/'; tinymce.baseURL = new tinymce.util.URI(tinymce.documentBaseURL).toAbsolute(tinymce.baseURL); tinymce.baseURI = new tinymce.util.URI(tinymce.baseURL); // Add before unload listener // This was required since IE was leaking memory if you added and removed beforeunload listeners // with attachEvent/detatchEvent so this only adds one listener and instances can the attach to the onBeforeUnload event tinymce.onBeforeUnload = new Dispatcher(tinymce); // Must be on window or IE will leak if the editor is placed in frame or iframe Event.add(window, 'beforeunload', function(e) { tinymce.onBeforeUnload.dispatch(tinymce, e); }); tinymce.onAddEditor = new Dispatcher(tinymce); tinymce.onRemoveEditor = new Dispatcher(tinymce); tinymce.EditorManager = extend(tinymce, { editors : [], i18n : {}, activeEditor : null, init : function(s) { var t = this, pl, sl = tinymce.ScriptLoader, e, el = [], ed; function createId(elm) { var id = elm.id; // Use element id, or unique name or generate a unique id if (!id) { id = elm.name; if (id && !DOM.get(id)) { id = elm.name; } else { // Generate unique name id = DOM.uniqueId(); } elm.setAttribute('id', id); } return id; }; function execCallback(se, n, s) { var f = se[n]; if (!f) return; if (tinymce.is(f, 'string')) { s = f.replace(/\.\w+$/, ''); s = s ? tinymce.resolve(s) : 0; f = tinymce.resolve(f); } return f.apply(s || this, Array.prototype.slice.call(arguments, 2)); }; function hasClass(n, c) { return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c); }; s = extend({ theme : "simple", language : "en" }, s); t.settings = s; // Legacy call Event.bind(window, 'ready', function() { var l, co; execCallback(s, 'onpageload'); switch (s.mode) { case "exact": l = s.elements || ''; if(l.length > 0) { each(explode(l), function(v) { if (DOM.get(v)) { ed = new tinymce.Editor(v, s); el.push(ed); ed.render(1); } else { each(document.forms, function(f) { each(f.elements, function(e) { if (e.name === v) { v = 'mce_editor_' + instanceCounter++; DOM.setAttrib(e, 'id', v); ed = new tinymce.Editor(v, s); el.push(ed); ed.render(1); } }); }); } }); } break; case "textareas": case "specific_textareas": each(DOM.select('textarea'), function(elm) { if (s.editor_deselector && hasClass(elm, s.editor_deselector)) return; if (!s.editor_selector || hasClass(elm, s.editor_selector)) { ed = new tinymce.Editor(createId(elm), s); el.push(ed); ed.render(1); } }); break; default: if (s.types) { // Process type specific selector each(s.types, function(type) { each(DOM.select(type.selector), function(elm) { var editor = new tinymce.Editor(createId(elm), tinymce.extend({}, s, type)); el.push(editor); editor.render(1); }); }); } else if (s.selector) { // Process global selector each(DOM.select(s.selector), function(elm) { var editor = new tinymce.Editor(createId(elm), s); el.push(editor); editor.render(1); }); } } // Call onInit when all editors are initialized if (s.oninit) { l = co = 0; each(el, function(ed) { co++; if (!ed.initialized) { // Wait for it ed.onInit.add(function() { l++; // All done if (l == co) execCallback(s, 'oninit'); }); } else l++; // All done if (l == co) execCallback(s, 'oninit'); }); } }); }, get : function(id) { if (id === undef) return this.editors; return this.editors[id]; }, getInstanceById : function(id) { return this.get(id); }, add : function(editor) { var self = this, editors = self.editors; // Add named and index editor instance editors[editor.id] = editor; editors.push(editor); self._setActive(editor); self.onAddEditor.dispatch(self, editor); return editor; }, remove : function(editor) { var t = this, i, editors = t.editors; // Not in the collection if (!editors[editor.id]) return null; delete editors[editor.id]; for (i = 0; i < editors.length; i++) { if (editors[i] == editor) { editors.splice(i, 1); break; } } // Select another editor since the active one was removed if (t.activeEditor == editor) t._setActive(editors[0]); editor.destroy(); t.onRemoveEditor.dispatch(t, editor); return editor; }, execCommand : function(c, u, v) { var t = this, ed = t.get(v), w; function clr() { ed.destroy(); w.detachEvent('onunload', clr); w = w.tinyMCE = w.tinymce = null; // IE leak }; // Manager commands switch (c) { case "mceFocus": ed.focus(); return true; case "mceAddEditor": case "mceAddControl": if (!t.get(v)) new tinymce.Editor(v, t.settings).render(); return true; case "mceAddFrameControl": w = v.window; // Add tinyMCE global instance and tinymce namespace to specified window w.tinyMCE = tinyMCE; w.tinymce = tinymce; tinymce.DOM.doc = w.document; tinymce.DOM.win = w; ed = new tinymce.Editor(v.element_id, v); ed.render(); // Fix IE memory leaks if (tinymce.isIE) { w.attachEvent('onunload', clr); } v.page_window = null; return true; case "mceRemoveEditor": case "mceRemoveControl": if (ed) ed.remove(); return true; case 'mceToggleEditor': if (!ed) { t.execCommand('mceAddControl', 0, v); return true; } if (ed.isHidden()) ed.show(); else ed.hide(); return true; } // Run command on active editor if (t.activeEditor) return t.activeEditor.execCommand(c, u, v); return false; }, execInstanceCommand : function(id, c, u, v) { var ed = this.get(id); if (ed) return ed.execCommand(c, u, v); return false; }, triggerSave : function() { each(this.editors, function(e) { e.save(); }); }, addI18n : function(p, o) { var lo, i18n = this.i18n; if (!tinymce.is(p, 'string')) { each(p, function(o, lc) { each(o, function(o, g) { each(o, function(o, k) { if (g === 'common') i18n[lc + '.' + k] = o; else i18n[lc + '.' + g + '.' + k] = o; }); }); }); } else { each(o, function(o, k) { i18n[p + '.' + k] = o; }); } }, // Private methods _setActive : function(editor) { this.selectedInstance = this.activeEditor = editor; } }); })(tinymce); (function(tinymce) { // Shorten these names var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, isGecko = tinymce.isGecko, isIE = tinymce.isIE, isWebKit = tinymce.isWebKit, is = tinymce.is, ThemeManager = tinymce.ThemeManager, PluginManager = tinymce.PluginManager, explode = tinymce.explode; tinymce.create('tinymce.Editor', { Editor : function(id, settings) { var self = this, TRUE = true; self.settings = settings = extend({ id : id, language : 'en', theme : 'simple', skin : 'default', delta_width : 0, delta_height : 0, popup_css : '', plugins : '', document_base_url : tinymce.documentBaseURL, add_form_submit_trigger : TRUE, submit_patch : TRUE, add_unload_trigger : TRUE, convert_urls : TRUE, relative_urls : TRUE, remove_script_host : TRUE, table_inline_editing : false, object_resizing : TRUE, accessibility_focus : TRUE, doctype : tinymce.isIE6 ? '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">' : '<!DOCTYPE>', // Use old doctype on IE 6 to avoid horizontal scroll visual : TRUE, font_size_style_values : 'xx-small,x-small,small,medium,large,x-large,xx-large', font_size_legacy_values : 'xx-small,small,medium,large,x-large,xx-large,300%', // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size apply_source_formatting : TRUE, directionality : 'ltr', forced_root_block : 'p', hidden_input : TRUE, padd_empty_editor : TRUE, render_ui : TRUE, indentation : '30px', fix_table_elements : TRUE, inline_styles : TRUE, convert_fonts_to_spans : TRUE, indent : 'simple', indent_before : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure', indent_after : 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr,section,article,hgroup,aside,figure', validate : TRUE, entity_encoding : 'named', url_converter : self.convertURL, url_converter_scope : self, ie7_compat : TRUE }, settings); self.id = self.editorId = id; self.isNotDirty = false; self.plugins = {}; self.documentBaseURI = new tinymce.util.URI(settings.document_base_url || tinymce.documentBaseURL, { base_uri : tinyMCE.baseURI }); self.baseURI = tinymce.baseURI; self.contentCSS = []; // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic self.setupEvents(); // Internal command handler objects self.execCommands = {}; self.queryStateCommands = {}; self.queryValueCommands = {}; // Call setup self.execCallback('setup', self); }, render : function(nst) { var t = this, s = t.settings, id = t.id, sl = tinymce.ScriptLoader; // Page is not loaded yet, wait for it if (!Event.domLoaded) { Event.add(window, 'ready', function() { t.render(); }); return; } tinyMCE.settings = s; // Element not found, then skip initialization if (!t.getElement()) return; // Is a iPad/iPhone and not on iOS5, then skip initialization. We need to sniff // here since the browser says it has contentEditable support but there is no visible caret. if (tinymce.isIDevice && !tinymce.isIOS5) return; // Add hidden input for non input elements inside form elements if (!/TEXTAREA|INPUT/i.test(t.getElement().nodeName) && s.hidden_input && DOM.getParent(id, 'form')) DOM.insertAfter(DOM.create('input', {type : 'hidden', name : id}), id); if (tinymce.WindowManager) t.windowManager = new tinymce.WindowManager(t); if (s.encoding == 'xml') { t.onGetContent.add(function(ed, o) { if (o.save) o.content = DOM.encode(o.content); }); } if (s.add_form_submit_trigger) { t.onSubmit.addToTop(function() { if (t.initialized) { t.save(); t.isNotDirty = 1; } }); } if (s.add_unload_trigger) { t._beforeUnload = tinyMCE.onBeforeUnload.add(function() { if (t.initialized && !t.destroyed && !t.isHidden()) t.save({format : 'raw', no_events : true}); }); } tinymce.addUnload(t.destroy, t); if (s.submit_patch) { t.onBeforeRenderUI.add(function() { var n = t.getElement().form; if (!n) return; // Already patched if (n._mceOldSubmit) return; // Check page uses id="submit" or name="submit" for it's submit button if (!n.submit.nodeType && !n.submit.length) { t.formElement = n; n._mceOldSubmit = n.submit; n.submit = function() { // Save all instances tinymce.triggerSave(); t.isNotDirty = 1; return t.formElement._mceOldSubmit(t.formElement); }; } n = null; }); } // Load scripts function loadScripts() { if (s.language && s.language_load !== false) sl.add(tinymce.baseURL + '/langs/' + s.language + '.js'); if (s.theme && s.theme.charAt(0) != '-' && !ThemeManager.urls[s.theme]) ThemeManager.load(s.theme, 'themes/' + s.theme + '/editor_template' + tinymce.suffix + '.js'); each(explode(s.plugins), function(p) { if (p &&!PluginManager.urls[p]) { if (p.charAt(0) == '-') { p = p.substr(1, p.length); var dependencies = PluginManager.dependencies(p); each(dependencies, function(dep) { var defaultSettings = {prefix:'plugins/', resource: dep, suffix:'/editor_plugin' + tinymce.suffix + '.js'}; dep = PluginManager.createUrl(defaultSettings, dep); PluginManager.load(dep.resource, dep); }); } else { // Skip safari plugin, since it is removed as of 3.3b1 if (p == 'safari') { return; } PluginManager.load(p, {prefix:'plugins/', resource: p, suffix:'/editor_plugin' + tinymce.suffix + '.js'}); } } }); // Init when que is loaded sl.loadQueue(function() { if (!t.removed) t.init(); }); }; loadScripts(); }, init : function() { var n, t = this, s = t.settings, w, h, e = t.getElement(), o, ti, u, bi, bc, re, i, initializedPlugins = []; tinymce.add(t); s.aria_label = s.aria_label || DOM.getAttrib(e, 'aria-label', t.getLang('aria.rich_text_area')); if (s.theme) { s.theme = s.theme.replace(/-/, ''); o = ThemeManager.get(s.theme); t.theme = new o(); if (t.theme.init) t.theme.init(t, ThemeManager.urls[s.theme] || tinymce.documentBaseURL.replace(/\/$/, '')); } function initPlugin(p) { var c = PluginManager.get(p), u = PluginManager.urls[p] || tinymce.documentBaseURL.replace(/\/$/, ''), po; if (c && tinymce.inArray(initializedPlugins,p) === -1) { each(PluginManager.dependencies(p), function(dep){ initPlugin(dep); }); po = new c(t, u); t.plugins[p] = po; if (po.init) { po.init(t, u); initializedPlugins.push(p); } } } // Create all plugins each(explode(s.plugins.replace(/\-/g, '')), initPlugin); // Setup popup CSS path(s) if (s.popup_css !== false) { if (s.popup_css) s.popup_css = t.documentBaseURI.toAbsolute(s.popup_css); else s.popup_css = t.baseURI.toAbsolute("themes/" + s.theme + "/skins/" + s.skin + "/dialog.css"); } if (s.popup_css_add) s.popup_css += ',' + t.documentBaseURI.toAbsolute(s.popup_css_add); t.controlManager = new tinymce.ControlManager(t); t.onExecCommand.add(function(ed, c) { // Don't refresh the select lists until caret move if (!/^(FontName|FontSize)$/.test(c)) t.nodeChanged(); }); // Enables users to override the control factory t.onBeforeRenderUI.dispatch(t, t.controlManager); // Measure box if (s.render_ui && t.theme) { w = s.width || e.style.width || e.offsetWidth; h = s.height || e.style.height || e.offsetHeight; t.orgDisplay = e.style.display; re = /^[0-9\.]+(|px)$/i; if (re.test('' + w)) w = Math.max(parseInt(w, 10) + (o.deltaWidth || 0), 100); if (re.test('' + h)) h = Math.max(parseInt(h, 10) + (o.deltaHeight || 0), 100); // Render UI o = t.theme.renderUI({ targetNode : e, width : w, height : h, deltaWidth : s.delta_width, deltaHeight : s.delta_height }); t.editorContainer = o.editorContainer; } // Load specified content CSS last if (s.content_css) { each(explode(s.content_css), function(u) { t.contentCSS.push(t.documentBaseURI.toAbsolute(u)); }); } // Content editable mode ends here if (s.content_editable) { e = n = o = null; // Fix IE leak return t.initContentBody(); } // User specified a document.domain value if (document.domain && location.hostname != document.domain) tinymce.relaxedDomain = document.domain; // Resize editor DOM.setStyles(o.sizeContainer || o.editorContainer, { width : w, height : h }); h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); if (h < 100) h = 100; t.iframeHTML = s.doctype + '<html><head xmlns="http://www.w3.org/1999/xhtml">'; // We only need to override paths if we have to // IE has a bug where it remove site absolute urls to relative ones if this is specified if (s.document_base_url != tinymce.documentBaseURL) t.iframeHTML += '<base href="' + t.documentBaseURI.getURI() + '" />'; // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode. if (s.ie7_compat) t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />'; else t.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'; t.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />'; // Load the CSS by injecting them into the HTML this will reduce "flicker" for (i = 0; i < t.contentCSS.length; i++) { t.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + t.contentCSS[i] + '" />'; } t.contentCSS = []; bi = s.body_id || 'tinymce'; if (bi.indexOf('=') != -1) { bi = t.getParam('body_id', '', 'hash'); bi = bi[t.id] || bi; } bc = s.body_class || ''; if (bc.indexOf('=') != -1) { bc = t.getParam('body_class', '', 'hash'); bc = bc[t.id] || ''; } t.iframeHTML += '</head><body id="' + bi + '" class="mceContentBody ' + bc + '" onload="window.parent.tinyMCE.get(\'' + t.id + '\').onLoad.dispatch();"><br></body></html>'; // Domain relaxing enabled, then set document domain if (tinymce.relaxedDomain && (isIE || (tinymce.isOpera && parseFloat(opera.version()) < 11))) { // We need to write the contents here in IE since multiple writes messes up refresh button and back button u = 'javascript:(function(){document.open();document.domain="' + document.domain + '";var ed = window.parent.tinyMCE.get("' + t.id + '");document.write(ed.iframeHTML);document.close();ed.initContentBody();})()'; } // Create iframe // TODO: ACC add the appropriate description on this. n = DOM.add(o.iframeContainer, 'iframe', { id : t.id + "_ifr", src : u || 'javascript:""', // Workaround for HTTPS warning in IE6/7 frameBorder : '0', allowTransparency : "true", title : s.aria_label, style : { width : '100%', height : h, display : 'block' // Important for Gecko to render the iframe correctly } }); t.contentAreaContainer = o.iframeContainer; DOM.get(o.editorContainer).style.display = t.orgDisplay; DOM.get(t.id).style.display = 'none'; DOM.setAttrib(t.id, 'aria-hidden', true); if (!tinymce.relaxedDomain || !u) t.initContentBody(); e = n = o = null; // Cleanup }, initContentBody : function() { var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), html, body; // Setup iframe body if ((!isIE || !tinymce.relaxedDomain) && !settings.content_editable) { doc.open(); doc.write(self.iframeHTML); doc.close(); if (tinymce.relaxedDomain) doc.domain = tinymce.relaxedDomain; } if (settings.content_editable) { DOM.addClass(targetElm, 'mceContentBody'); self.contentDocument = doc = settings.content_document || document; self.contentWindow = settings.content_window || window; self.bodyElement = targetElm; // Prevent leak in IE settings.content_document = settings.content_window = null; } // It will not steal focus while setting contentEditable body = self.getBody(); body.disabled = true; if (!settings.readonly) body.contentEditable = self.getParam('content_editable_state', true); body.disabled = false; self.schema = new tinymce.html.Schema(settings); self.dom = new tinymce.dom.DOMUtils(doc, { keep_values : true, url_converter : self.convertURL, url_converter_scope : self, hex_colors : settings.force_hex_style_colors, class_filter : settings.class_filter, update_styles : true, root_element : settings.content_editable ? self.id : null, schema : self.schema }); self.parser = new tinymce.html.DomParser(settings, self.schema); // Convert src and href into data-mce-src, data-mce-href and data-mce-style self.parser.addAttributeFilter('src,href,style', function(nodes, name) { var i = nodes.length, node, dom = self.dom, value, internalName; while (i--) { node = nodes[i]; value = node.attr(name); internalName = 'data-mce-' + name; // Add internal attribute if we need to we don't on a refresh of the document if (!node.attributes.map[internalName]) { if (name === "style") node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name)); else node.attr(internalName, self.convertURL(value, name, node.name)); } } }); // Keep scripts from executing self.parser.addNodeFilter('script', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.attr('type', 'mce-' + (node.attr('type') || 'text/javascript')); } }); self.parser.addNodeFilter('#cdata', function(nodes, name) { var i = nodes.length, node; while (i--) { node = nodes[i]; node.type = 8; node.name = '#comment'; node.value = '[CDATA[' + node.value + ']]'; } }); self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes, name) { var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements(); while (i--) { node = nodes[i]; if (node.isEmpty(nonEmptyElements)) node.empty().append(new tinymce.html.Node('br', 1)).shortEnded = true; } }); self.serializer = new tinymce.dom.Serializer(settings, self.dom, self.schema); self.selection = new tinymce.dom.Selection(self.dom, self.getWin(), self.serializer); self.formatter = new tinymce.Formatter(self); self.undoManager = new tinymce.UndoManager(self); self.forceBlocks = new tinymce.ForceBlocks(self); self.enterKey = new tinymce.EnterKey(self); self.editorCommands = new tinymce.EditorCommands(self); // Pass through self.serializer.onPreProcess.add(function(se, o) { return self.onPreProcess.dispatch(self, o, se); }); self.serializer.onPostProcess.add(function(se, o) { return self.onPostProcess.dispatch(self, o, se); }); self.onPreInit.dispatch(self); if (!settings.gecko_spellcheck) doc.body.spellcheck = false; if (!settings.readonly) { self.bindNativeEvents(); } self.controlManager.onPostRender.dispatch(self, self.controlManager); self.onPostRender.dispatch(self); self.quirks = tinymce.util.Quirks(self); if (settings.directionality) body.dir = settings.directionality; if (settings.nowrap) body.style.whiteSpace = "nowrap"; if (settings.protect) { self.onBeforeSetContent.add(function(ed, o) { each(settings.protect, function(pattern) { o.content = o.content.replace(pattern, function(str) { return '<!--mce:protected ' + escape(str) + '-->'; }); }); }); } // Add visual aids when new contents is added self.onSetContent.add(function() { self.addVisual(self.getBody()); }); // Remove empty contents if (settings.padd_empty_editor) { self.onPostProcess.add(function(ed, o) { o.content = o.content.replace(/^(<p[^>]*>(&nbsp;|&#160;|\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, ''); }); } self.load({initial : true, format : 'html'}); self.startContent = self.getContent({format : 'raw'}); self.initialized = true; self.onInit.dispatch(self); self.execCallback('setupcontent_callback', self.id, body, doc); self.execCallback('init_instance_callback', self); self.focus(true); self.nodeChanged({initial : true}); // Load specified content CSS last each(self.contentCSS, function(url) { self.dom.loadCSS(url); }); // Handle auto focus if (settings.auto_focus) { setTimeout(function () { var ed = tinymce.get(settings.auto_focus); ed.selection.select(ed.getBody(), 1); ed.selection.collapse(1); ed.getBody().focus(); ed.getWin().focus(); }, 100); } // Clean up references for IE targetElm = doc = body = null; }, focus : function(skip_focus) { var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, ieRng, controlElm, doc = self.getDoc(), body; if (!skip_focus) { // Get selected control element ieRng = selection.getRng(); if (ieRng.item) { controlElm = ieRng.item(0); } self._refreshContentEditable(); // Focus the window iframe if (!contentEditable) { self.getWin().focus(); } // Focus the body as well since it's contentEditable if (tinymce.isGecko || contentEditable) { body = self.getBody(); // Check for setActive since it doesn't scroll to the element if (body.setActive) { body.setActive(); } else { body.focus(); } if (contentEditable) { selection.normalize(); } } // Restore selected control element // This is needed when for example an image is selected within a // layer a call to focus will then remove the control selection if (controlElm && controlElm.ownerDocument == doc) { ieRng = doc.body.createControlRange(); ieRng.addElement(controlElm); ieRng.select(); } } if (tinymce.activeEditor != self) { if ((oed = tinymce.activeEditor) != null) oed.onDeactivate.dispatch(oed, self); self.onActivate.dispatch(self, oed); } tinymce._setActive(self); }, execCallback : function(n) { var t = this, f = t.settings[n], s; if (!f) return; // Look through lookup if (t.callbackLookup && (s = t.callbackLookup[n])) { f = s.func; s = s.scope; } if (is(f, 'string')) { s = f.replace(/\.\w+$/, ''); s = s ? tinymce.resolve(s) : 0; f = tinymce.resolve(f); t.callbackLookup = t.callbackLookup || {}; t.callbackLookup[n] = {func : f, scope : s}; } return f.apply(s || t, Array.prototype.slice.call(arguments, 1)); }, translate : function(s) { var c = this.settings.language || 'en', i18n = tinymce.i18n; if (!s) return ''; return i18n[c + '.' + s] || s.replace(/\{\#([^\}]+)\}/g, function(a, b) { return i18n[c + '.' + b] || '{#' + b + '}'; }); }, getLang : function(n, dv) { return tinymce.i18n[(this.settings.language || 'en') + '.' + n] || (is(dv) ? dv : '{#' + n + '}'); }, getParam : function(n, dv, ty) { var tr = tinymce.trim, v = is(this.settings[n]) ? this.settings[n] : dv, o; if (ty === 'hash') { o = {}; if (is(v, 'string')) { each(v.indexOf('=') > 0 ? v.split(/[;,](?![^=;,]*(?:[;,]|$))/) : v.split(','), function(v) { v = v.split('='); if (v.length > 1) o[tr(v[0])] = tr(v[1]); else o[tr(v[0])] = tr(v); }); } else o = v; return o; } return v; }, nodeChanged : function(o) { var self = this, selection = self.selection, node; // Fix for bug #1896577 it seems that this can not be fired while the editor is loading if (self.initialized) { o = o || {}; // Normalize selection for example <b>a</b><i>|a</i> becomes <b>a|</b><i>a</i> selection.normalize(); // Get start node node = selection.getStart() || self.getBody(); node = isIE && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state // Get parents and add them to object o.parents = []; self.dom.getParent(node, function(node) { if (node.nodeName == 'BODY') return true; o.parents.push(node); }); self.onNodeChange.dispatch( self, o ? o.controlManager || self.controlManager : self.controlManager, node, selection.isCollapsed(), o ); } }, addButton : function(name, settings) { var self = this; self.buttons = self.buttons || {}; self.buttons[name] = settings; }, addCommand : function(name, callback, scope) { this.execCommands[name] = {func : callback, scope : scope || this}; }, addQueryStateHandler : function(name, callback, scope) { this.queryStateCommands[name] = {func : callback, scope : scope || this}; }, addQueryValueHandler : function(name, callback, scope) { this.queryValueCommands[name] = {func : callback, scope : scope || this}; }, addShortcut : function(pa, desc, cmd_func, sc) { var t = this, c; if (t.settings.custom_shortcuts === false) return false; t.shortcuts = t.shortcuts || {}; if (is(cmd_func, 'string')) { c = cmd_func; cmd_func = function() { t.execCommand(c, false, null); }; } if (is(cmd_func, 'object')) { c = cmd_func; cmd_func = function() { t.execCommand(c[0], c[1], c[2]); }; } each(explode(pa), function(pa) { var o = { func : cmd_func, scope : sc || this, desc : t.translate(desc), alt : false, ctrl : false, shift : false }; each(explode(pa, '+'), function(v) { switch (v) { case 'alt': case 'ctrl': case 'shift': o[v] = true; break; default: o.charCode = v.charCodeAt(0); o.keyCode = v.toUpperCase().charCodeAt(0); } }); t.shortcuts[(o.ctrl ? 'ctrl' : '') + ',' + (o.alt ? 'alt' : '') + ',' + (o.shift ? 'shift' : '') + ',' + o.keyCode] = o; }); return true; }, execCommand : function(cmd, ui, val, a) { var t = this, s = 0, o, st; if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint|SelectAll)$/.test(cmd) && (!a || !a.skip_focus)) t.focus(); a = extend({}, a); t.onBeforeExecCommand.dispatch(t, cmd, ui, val, a); if (a.terminate) return false; // Command callback if (t.execCallback('execcommand_callback', t.id, t.selection.getNode(), cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Registred commands if (o = t.execCommands[cmd]) { st = o.func.call(o.scope, ui, val); // Fall through on true if (st !== true) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return st; } } // Plugin commands each(t.plugins, function(p) { if (p.execCommand && p.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); s = 1; return false; } }); if (s) return true; // Theme commands if (t.theme && t.theme.execCommand && t.theme.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Editor commands if (t.editorCommands.execCommand(cmd, ui, val)) { t.onExecCommand.dispatch(t, cmd, ui, val, a); return true; } // Browser commands t.getDoc().execCommand(cmd, ui, val); t.onExecCommand.dispatch(t, cmd, ui, val, a); }, queryCommandState : function(cmd) { var t = this, o, s; // Is hidden then return undefined if (t._isHidden()) return; // Registred commands if (o = t.queryStateCommands[cmd]) { s = o.func.call(o.scope); // Fall though on true if (s !== true) return s; } // Registred commands o = t.editorCommands.queryCommandState(cmd); if (o !== -1) return o; // Browser commands try { return this.getDoc().queryCommandState(cmd); } catch (ex) { // Fails sometimes see bug: 1896577 } }, queryCommandValue : function(c) { var t = this, o, s; // Is hidden then return undefined if (t._isHidden()) return; // Registred commands if (o = t.queryValueCommands[c]) { s = o.func.call(o.scope); // Fall though on true if (s !== true) return s; } // Registred commands o = t.editorCommands.queryCommandValue(c); if (is(o)) return o; // Browser commands try { return this.getDoc().queryCommandValue(c); } catch (ex) { // Fails sometimes see bug: 1896577 } }, show : function() { var self = this; DOM.show(self.getContainer()); DOM.hide(self.id); self.load(); }, hide : function() { var self = this, doc = t.getDoc(); // Fixed bug where IE has a blinking cursor left from the editor if (isIE && doc) doc.execCommand('SelectAll'); // We must save before we hide so Safari doesn't crash self.save(); DOM.hide(self.getContainer()); DOM.setStyle(self.id, 'display', self.orgDisplay); }, isHidden : function() { return !DOM.isHidden(this.id); }, setProgressState : function(b, ti, o) { this.onSetProgressState.dispatch(this, b, ti, o); return b; }, load : function(o) { var t = this, e = t.getElement(), h; if (e) { o = o || {}; o.load = true; // Double encode existing entities in the value h = t.setContent(is(e.value) ? e.value : e.innerHTML, o); o.element = e; if (!o.no_events) t.onLoadContent.dispatch(t, o); o.element = e = null; return h; } }, save : function(o) { var t = this, e = t.getElement(), h, f; if (!e || !t.initialized) return; o = o || {}; o.save = true; o.element = e; h = o.content = t.getContent(o); if (!o.no_events) t.onSaveContent.dispatch(t, o); h = o.content; if (!/TEXTAREA|INPUT/i.test(e.nodeName)) { e.innerHTML = h; // Update hidden form element if (f = DOM.getParent(t.id, 'form')) { each(f.elements, function(e) { if (e.name == t.id) { e.value = h; return false; } }); } } else e.value = h; o.element = e = null; return h; }, setContent : function(content, args) { var self = this, rootNode, body = self.getBody(), forcedRootBlockName; // Setup args object args = args || {}; args.format = args.format || 'html'; args.set = true; args.content = content; // Do preprocessing if (!args.no_events) self.onBeforeSetContent.dispatch(self, args); content = args.content; // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content // It will also be impossible to place the caret in the editor unless there is a BR element present if (!tinymce.isIE && (content.length === 0 || /^\s+$/.test(content))) { forcedRootBlockName = self.settings.forced_root_block; if (forcedRootBlockName) content = '<' + forcedRootBlockName + '><br data-mce-bogus="1"></' + forcedRootBlockName + '>'; else content = '<br data-mce-bogus="1">'; body.innerHTML = content; self.selection.select(body, true); self.selection.collapse(true); return; } // Parse and serialize the html if (args.format !== 'raw') { content = new tinymce.html.Serializer({}, self.schema).serialize( self.parser.parse(content) ); } // Set the new cleaned contents to the editor args.content = tinymce.trim(content); self.dom.setHTML(body, args.content); // Do post processing if (!args.no_events) self.onSetContent.dispatch(self, args); self.selection.normalize(); return args.content; }, getContent : function(args) { var self = this, content; // Setup args object args = args || {}; args.format = args.format || 'html'; args.get = true; args.getInner = true; // Do preprocessing if (!args.no_events) self.onBeforeGetContent.dispatch(self, args); // Get raw contents or by default the cleaned contents if (args.format == 'raw') content = self.getBody().innerHTML; else content = self.serializer.serialize(self.getBody(), args); args.content = tinymce.trim(content); // Do post processing if (!args.no_events) self.onGetContent.dispatch(self, args); return args.content; }, isDirty : function() { var self = this; return tinymce.trim(self.startContent) != tinymce.trim(self.getContent({format : 'raw', no_events : 1})) && !self.isNotDirty; }, getContainer : function() { var self = this; if (!self.container) self.container = DOM.get(self.editorContainer || self.id + '_parent'); return self.container; }, getContentAreaContainer : function() { return this.contentAreaContainer; }, getElement : function() { return DOM.get(this.settings.content_element || this.id); }, getWin : function() { var self = this, elm; if (!self.contentWindow) { elm = DOM.get(self.id + "_ifr"); if (elm) self.contentWindow = elm.contentWindow; } return self.contentWindow; }, getDoc : function() { var self = this, win; if (!self.contentDocument) { win = self.getWin(); if (win) self.contentDocument = win.document; } return self.contentDocument; }, getBody : function() { return this.bodyElement || this.getDoc().body; }, convertURL : function(url, name, elm) { var self = this, settings = self.settings; // Use callback instead if (settings.urlconverter_callback) return self.execCallback('urlconverter_callback', url, elm, true, name); // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0) return url; // Convert to relative if (settings.relative_urls) return self.documentBaseURI.toRelative(url); // Convert to absolute url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host); return url; }, addVisual : function(elm) { var self = this, settings = self.settings, dom = self.dom, cls; elm = elm || self.getBody(); if (!is(self.hasVisual)) self.hasVisual = settings.visual; each(dom.select('table,a', elm), function(elm) { var value; switch (elm.nodeName) { case 'TABLE': cls = settings.visual_table_class || 'mceItemTable'; value = dom.getAttrib(elm, 'border'); if (!value || value == '0') { if (self.hasVisual) dom.addClass(elm, cls); else dom.removeClass(elm, cls); } return; case 'A': value = dom.getAttrib(elm, 'name'); cls = 'mceItemAnchor'; if (value) { if (self.hasVisual) dom.addClass(elm, cls); else dom.removeClass(elm, cls); } return; } }); self.onVisualAid.dispatch(self, elm, self.hasVisual); }, remove : function() { var self = this, elm = self.getContainer(); if (!self.removed) { self.removed = 1; // Cancels post remove event execution self.hide(); // Don't clear the window or document if content editable // is enabled since other instances might still be present if (!self.settings.content_editable) { Event.clear(self.getWin()); Event.clear(self.getDoc()); } Event.clear(self.getBody()); Event.clear(self.formElement); Event.unbind(elm); self.execCallback('remove_instance_callback', self); self.onRemove.dispatch(self); // Clear all execCommand listeners this is required to avoid errors if the editor was removed inside another command self.onExecCommand.listeners = []; tinymce.remove(self); DOM.remove(elm); } }, destroy : function(s) { var t = this; // One time is enough if (t.destroyed) return; // We must unbind on Gecko since it would otherwise produce the pesky "attempt to run compile-and-go script on a cleared scope" message if (isGecko) { Event.unbind(t.getDoc()); Event.unbind(t.getWin()); Event.unbind(t.getBody()); } if (!s) { tinymce.removeUnload(t.destroy); tinyMCE.onBeforeUnload.remove(t._beforeUnload); // Manual destroy if (t.theme && t.theme.destroy) t.theme.destroy(); // Destroy controls, selection and dom t.controlManager.destroy(); t.selection.destroy(); t.dom.destroy(); } if (t.formElement) { t.formElement.submit = t.formElement._mceOldSubmit; t.formElement._mceOldSubmit = null; } t.contentAreaContainer = t.formElement = t.container = t.settings.content_element = t.bodyElement = t.contentDocument = t.contentWindow = null; if (t.selection) t.selection = t.selection.win = t.selection.dom = t.selection.dom.doc = null; t.destroyed = 1; }, // Internal functions _refreshContentEditable : function() { var self = this, body, parent; // Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again if (self._isHidden()) { body = self.getBody(); parent = body.parentNode; parent.removeChild(body); parent.appendChild(body); body.focus(); } }, _isHidden : function() { var s; if (!isGecko) return 0; // Weird, wheres that cursor selection? s = this.selection.getSel(); return (!s || !s.rangeCount || s.rangeCount === 0); } }); })(tinymce); (function(tinymce) { var each = tinymce.each; tinymce.Editor.prototype.setupEvents = function() { var self = this, settings = self.settings; // Add events to the editor each([ 'onPreInit', 'onBeforeRenderUI', 'onPostRender', 'onLoad', 'onInit', 'onRemove', 'onActivate', 'onDeactivate', 'onClick', 'onEvent', 'onMouseUp', 'onMouseDown', 'onDblClick', 'onKeyDown', 'onKeyUp', 'onKeyPress', 'onContextMenu', 'onSubmit', 'onReset', 'onPaste', 'onPreProcess', 'onPostProcess', 'onBeforeSetContent', 'onBeforeGetContent', 'onSetContent', 'onGetContent', 'onLoadContent', 'onSaveContent', 'onNodeChange', 'onChange', 'onBeforeExecCommand', 'onExecCommand', 'onUndo', 'onRedo', 'onVisualAid', 'onSetProgressState', 'onSetAttrib' ], function(name) { self[name] = new tinymce.util.Dispatcher(self); }); // Handle legacy cleanup_callback option if (settings.cleanup_callback) { self.onBeforeSetContent.add(function(ed, o) { o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o); }); self.onPreProcess.add(function(ed, o) { if (o.set) ed.execCallback('cleanup_callback', 'insert_to_editor_dom', o.node, o); if (o.get) ed.execCallback('cleanup_callback', 'get_from_editor_dom', o.node, o); }); self.onPostProcess.add(function(ed, o) { if (o.set) o.content = ed.execCallback('cleanup_callback', 'insert_to_editor', o.content, o); if (o.get) o.content = ed.execCallback('cleanup_callback', 'get_from_editor', o.content, o); }); } // Handle legacy save_callback option if (settings.save_callback) { self.onGetContent.add(function(ed, o) { if (o.save) o.content = ed.execCallback('save_callback', ed.id, o.content, ed.getBody()); }); } // Handle legacy handle_event_callback option if (settings.handle_event_callback) { self.onEvent.add(function(ed, e, o) { if (self.execCallback('handle_event_callback', e, ed, o) === false) Event.cancel(e); }); } // Handle legacy handle_node_change_callback option if (settings.handle_node_change_callback) { self.onNodeChange.add(function(ed, cm, n) { ed.execCallback('handle_node_change_callback', ed.id, n, -1, -1, true, ed.selection.isCollapsed()); }); } // Handle legacy save_callback option if (settings.save_callback) { self.onSaveContent.add(function(ed, o) { var h = ed.execCallback('save_callback', ed.id, o.content, ed.getBody()); if (h) o.content = h; }); } // Handle legacy onchange_callback option if (settings.onchange_callback) { self.onChange.add(function(ed, l) { ed.execCallback('onchange_callback', ed, l); }); } }; tinymce.Editor.prototype.bindNativeEvents = function() { // 'focus', 'blur', 'dblclick', 'beforedeactivate', submit, reset var self = this, i, settings = self.settings, dom = self.dom, nativeToDispatcherMap; nativeToDispatcherMap = { mouseup : 'onMouseUp', mousedown : 'onMouseDown', click : 'onClick', keyup : 'onKeyUp', keydown : 'onKeyDown', keypress : 'onKeyPress', submit : 'onSubmit', reset : 'onReset', contextmenu : 'onContextMenu', dblclick : 'onDblClick', paste : 'onPaste' // Doesn't work in all browsers yet }; // Handler that takes a native event and sends it out to a dispatcher like onKeyDown function eventHandler(evt, args) { var type = evt.type; // Don't fire events when it's removed if (self.removed) return; // Sends the native event out to a global dispatcher then to the specific event dispatcher if (self.onEvent.dispatch(self, evt, args) !== false) { self[nativeToDispatcherMap[evt.fakeType || evt.type]].dispatch(self, evt, args); } }; // Opera doesn't support focus event for contentEditable elements so we need to fake it function doOperaFocus(e) { self.focus(true); }; // Add DOM events each(nativeToDispatcherMap, function(dispatcherName, nativeName) { var root = settings.content_editable ? self.getBody() : self.getDoc(); switch (nativeName) { case 'contextmenu': dom.bind(root, nativeName, eventHandler); break; case 'paste': dom.bind(self.getBody(), nativeName, eventHandler); break; case 'submit': case 'reset': dom.bind(self.getElement().form || tinymce.DOM.getParent(self.id, 'form'), nativeName, eventHandler); break; default: dom.bind(root, nativeName, eventHandler); } }); // Set the editor as active when focused dom.bind(settings.content_editable ? self.getBody() : (tinymce.isGecko ? self.getDoc() : self.getWin()), 'focus', function(e) { self.focus(true); }); if (settings.content_editable && tinymce.isOpera) { dom.bind(self.getBody(), 'click', doOperaFocus); dom.bind(self.getBody(), 'keydown', doOperaFocus); } // Add node change handler self.onMouseUp.add(self.nodeChanged); self.onKeyUp.add(function(ed, e) { var keyCode = e.keyCode; if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 13 || keyCode == 45 || keyCode == 46 || keyCode == 8 || (tinymce.isMac && (keyCode == 91 || keyCode == 93)) || e.ctrlKey) self.nodeChanged(); }); // Add reset handler self.onReset.add(function() { self.setContent(self.startContent, {format : 'raw'}); }); // Add shortcuts function handleShortcut(e, execute) { if (e.altKey || e.ctrlKey || e.metaKey) { each(self.shortcuts, function(shortcut) { var ctrlState = tinymce.isMac ? e.metaKey : e.ctrlKey; if (shortcut.ctrl != ctrlState || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) return; if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) { e.preventDefault(); if (execute) { shortcut.func.call(shortcut.scope); } return true; } }); } }; self.onKeyUp.add(function(ed, e) { handleShortcut(e); }); self.onKeyPress.add(function(ed, e) { handleShortcut(e); }); self.onKeyDown.add(function(ed, e) { handleShortcut(e, true); }); if (tinymce.isOpera) { self.onClick.add(function(ed, e) { e.preventDefault(); }); } }; })(tinymce); (function(tinymce) { // Added for compression purposes var each = tinymce.each, undef, TRUE = true, FALSE = false; tinymce.EditorCommands = function(editor) { var dom = editor.dom, selection = editor.selection, commands = {state: {}, exec : {}, value : {}}, settings = editor.settings, formatter = editor.formatter, bookmark; function execCommand(command, ui, value) { var func; command = command.toLowerCase(); if (func = commands.exec[command]) { func(command, ui, value); return TRUE; } return FALSE; }; function queryCommandState(command) { var func; command = command.toLowerCase(); if (func = commands.state[command]) return func(command); return -1; }; function queryCommandValue(command) { var func; command = command.toLowerCase(); if (func = commands.value[command]) return func(command); return FALSE; }; function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); }; // Expose public methods tinymce.extend(this, { execCommand : execCommand, queryCommandState : queryCommandState, queryCommandValue : queryCommandValue, addCommands : addCommands }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undef) ui = FALSE; if (value === undef) value = null; return editor.getDoc().execCommand(command, ui, value); }; function isFormatMatch(name) { return formatter.match(name); }; function toggleFormat(name, value) { formatter.toggle(name, value ? {value : value} : undef); }; function storeSelection(type) { bookmark = selection.getBookmark(type); }; function restoreSelection() { selection.moveToBookmark(bookmark); }; // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel' : function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel' : function() { editor.undoManager.add(); }, 'Cut,Copy,Paste' : function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { if (tinymce.isGecko) { editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { if (state) open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); }); } else editor.windowManager.alert(editor.getLang('clipboard_no_support')); } }, // Override unlink command unlink : function(command) { if (selection.isCollapsed()) selection.select(selection.getNode()); execNativeCommand(command); selection.collapse(FALSE); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var align = command.substring(7); // Remove all other alignments first each('left,center,right,full'.split(','), function(name) { if (align != name) formatter.remove('align' + name); }); toggleFormat('align' + align); execCommand('mceRepaint'); }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList' : function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName' : function(command, ui, value) { toggleFormat(command, value); }, FontSize : function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = tinymce.explode(settings.font_size_style_values); fontClasses = tinymce.explode(settings.font_size_classes); if (fontClasses) value = fontClasses[value - 1] || value; else value = fontSizes[value - 1] || value; } toggleFormat(command, value); }, RemoveFormat : function(command) { formatter.remove(command); }, mceBlockQuote : function(command) { toggleFormat('blockquote'); }, FormatBlock : function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup : function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup : TRUE}), {cleanup : TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode : function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth : function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode : function(command, ui, value) { selection.select(value); }, mceInsertContent : function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args, marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; //selection.normalize(); // Setup parser and serializer parser = editor.parser; serializer = new tinymce.html.Serializer({}, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">\uFEFF</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html'}; selection.onBeforeSetContent.dispatch(selection, args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) value += '{$caret}'; // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) editor.getDoc().execCommand('Delete', false, null); parentNode = selection.getNode(); // Parse the fragment within the context of the parent node args = {context : parentNode.nodeName.toLowerCase()}; fragment = parser.parse(value, args); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { node.parent.insert(marker, node, node.name === 'br'); break; } } } // If parser says valid we can insert the contents into that parent if (!args.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) dom.setHTML(parentNode, value); else selection.setContent(value); } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = editor.selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) parentNode = node = rootNode; else node = parentNode; // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) dom.setHTML(rootNode, value); else dom.setOuterHTML(parentNode, value); } marker = dom.get('mce_marker'); // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well nodeRect = dom.getRect(marker); viewPortRect = dom.getViewPort(editor.getWin()); // Check if node is out side the viewport if it is then scroll to it if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) || (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) { viewportBodyElement = tinymce.isIE ? editor.getDoc().documentElement : editor.getBody(); viewportBodyElement.scrollLeft = nodeRect.x; viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); // Dispatch after event and add any visual elements needed selection.onSetContent.dispatch(selection, args); editor.addVisual(); }, mceInsertRawHTML : function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent(editor.getContent().replace(/tiny_mce_marker/g, function() { return value })); }, mceSetContent : function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent' : function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { if (command == 'outdent') { value = Math.max(0, parseInt(element.style.paddingLeft || 0) - intentValue); dom.setStyle(element, 'paddingLeft', value ? value + indentUnit : ''); } else dom.setStyle(element, 'paddingLeft', (parseInt(element.style.paddingLeft || 0) + intentValue) + indentUnit); }); } else execNativeCommand(command); }, mceRepaint : function() { var bookmark; if (tinymce.isGecko) { try { storeSelection(TRUE); if (selection.getSel()) selection.getSel().selectAllChildren(editor.getBody()); selection.collapse(TRUE); restoreSelection(); } catch (ex) { // Ignore } } }, mceToggleFormat : function(command, ui, value) { formatter.toggle(value); }, InsertHorizontalRule : function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid : function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent : function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format : 'text'}))); }, mceInsertLink : function(command, ui, value) { var anchor; if (typeof(value) == 'string') value = {href : value}; anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll : function() { var root = dom.getRoot(), rng = dom.createRng(); rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); editor.selection.setRng(rng); } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull' : function(command) { var name = 'align' + command.substring(7); // Use Formatter.matchNode instead of Formatter.match so that we don't match on parent node. This fixes bug where for both left // and right align buttons can be active. This could occur when selected nodes have align right and the parent has align left. var nodes = selection.isCollapsed() ? [selection.getNode()] : selection.getSelectedBlocks(); var matches = tinymce.map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return tinymce.inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript' : function(command) { return isFormatMatch(command); }, mceBlockQuote : function() { return isFormatMatch('blockquote'); }, Outdent : function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft) > 0) return TRUE; } return queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')); }, 'InsertUnorderedList,InsertOrderedList' : function(command) { return dom.getParent(selection.getNode(), command == 'insertunorderedlist' ? 'UL' : 'OL'); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName' : function(command) { var value = 0, parent; if (parent = dom.getParent(selection.getNode(), 'span')) { if (command == 'fontsize') value = parent.style.fontSize; else value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo : function() { editor.undoManager.undo(); }, Redo : function() { editor.undoManager.redo(); } }); }; })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher; tinymce.UndoManager = function(editor) { var self, index = 0, data = [], beforeBookmark, onAdd, onUndo, onRedo; function getContent() { // Remove whitespace before/after and remove pure bogus nodes return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}).replace(/<span[^>]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\/span>/g, '')); }; function addNonTypingUndoLevel() { self.typing = false; self.add(); }; // Create event instances onAdd = new Dispatcher(self); onUndo = new Dispatcher(self); onRedo = new Dispatcher(self); // Pass though onAdd event from UndoManager to Editor as onChange onAdd.add(function(undoman, level) { if (undoman.hasUndo()) return editor.onChange.dispatch(editor, level, undoman); }); // Pass though onUndo event from UndoManager to Editor onUndo.add(function(undoman, level) { return editor.onUndo.dispatch(editor, level, undoman); }); // Pass though onRedo event from UndoManager to Editor onRedo.add(function(undoman, level) { return editor.onRedo.dispatch(editor, level, undoman); }); // Add initial undo level when the editor is initialized editor.onInit.add(function() { self.add(); }); // Get position before an execCommand is processed editor.onBeforeExecCommand.add(function(ed, cmd, ui, val, args) { if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) { self.beforeChange(); } }); // Add undo level after an execCommand call was made editor.onExecCommand.add(function(ed, cmd, ui, val, args) { if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint' && (!args || !args.skip_undo)) { self.add(); } }); // Add undo level on save contents, drag end and blur/focusout editor.onSaveContent.add(addNonTypingUndoLevel); editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel); editor.dom.bind(editor.getDoc(), tinymce.isGecko ? 'blur' : 'focusout', function(e) { if (!editor.removed && self.typing) { addNonTypingUndoLevel(); } }); editor.onKeyUp.add(function(editor, e) { var keyCode = e.keyCode; if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) { addNonTypingUndoLevel(); } }); editor.onKeyDown.add(function(editor, e) { var keyCode = e.keyCode; // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45) { if (self.typing) { addNonTypingUndoLevel(); } return; } // If key isn't shift,ctrl,alt,capslock,metakey if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !self.typing) { self.beforeChange(); self.typing = true; self.add(); } }); editor.onMouseDown.add(function(editor, e) { if (self.typing) { addNonTypingUndoLevel(); } }); // Add keyboard shortcuts for undo/redo keys editor.addShortcut('ctrl+z', 'undo_desc', 'Undo'); editor.addShortcut('ctrl+y', 'redo_desc', 'Redo'); self = { // Explose for debugging reasons data : data, typing : false, onAdd : onAdd, onUndo : onUndo, onRedo : onRedo, beforeChange : function() { beforeBookmark = editor.selection.getBookmark(2, true); }, add : function(level) { var i, settings = editor.settings, lastLevel; level = level || {}; level.content = getContent(); // Add undo level if needed lastLevel = data[index]; if (lastLevel && lastLevel.content == level.content) return null; // Set before bookmark on previous level if (data[index]) data[index].beforeBookmark = beforeBookmark; // Time to compress if (settings.custom_undo_redo_levels) { if (data.length > settings.custom_undo_redo_levels) { for (i = 0; i < data.length - 1; i++) data[i] = data[i + 1]; data.length--; index = data.length; } } // Get a non intrusive normalized bookmark level.bookmark = editor.selection.getBookmark(2, true); // Crop array if needed if (index < data.length - 1) data.length = index + 1; data.push(level); index = data.length - 1; self.onAdd.dispatch(self, level); editor.isNotDirty = 0; return level; }, undo : function() { var level, i; if (self.typing) { self.add(); self.typing = false; } if (index > 0) { level = data[--index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.beforeBookmark); self.onUndo.dispatch(self, level); } return level; }, redo : function() { var level; if (index < data.length - 1) { level = data[++index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.bookmark); self.onRedo.dispatch(self, level); } return level; }, clear : function() { data = []; index = 0; self.typing = false; }, hasUndo : function() { return index > 0 || this.typing; }, hasRedo : function() { return index < data.length - 1 && !this.typing; } }; return self; }; })(tinymce); tinymce.ForceBlocks = function(editor) { var settings = editor.settings, dom = editor.dom, selection = editor.selection, blockElements = editor.schema.getBlockElements(); function addRootBlocks() { var node = selection.getStart(), rootNode = editor.getBody(), rng, startContainer, startOffset, endContainer, endOffset, rootBlockNode, tempNode, offset = -0xFFFFFF; if (!node || node.nodeType !== 1 || !settings.forced_root_block) return; // Check if node is wrapped in block while (node != rootNode) { if (blockElements[node.nodeName]) return; node = node.parentNode; } // Get current selection rng = selection.getRng(); if (rng.setStart) { startContainer = rng.startContainer; startOffset = rng.startOffset; endContainer = rng.endContainer; endOffset = rng.endOffset; } else { // Force control range into text range if (rng.item) { node = rng.item(0); rng = editor.getDoc().body.createTextRange(); rng.moveToElementText(node); } tmpRng = rng.duplicate(); tmpRng.collapse(true); startOffset = tmpRng.move('character', offset) * -1; if (!tmpRng.collapsed) { tmpRng = rng.duplicate(); tmpRng.collapse(false); endOffset = (tmpRng.move('character', offset) * -1) - startOffset; } } // Wrap non block elements and text nodes node = rootNode.firstChild; while (node) { if (node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName])) { if (!rootBlockNode) { rootBlockNode = dom.create(settings.forced_root_block); node.parentNode.insertBefore(rootBlockNode, node); } tempNode = node; node = node.nextSibling; rootBlockNode.appendChild(tempNode); } else { rootBlockNode = null; node = node.nextSibling; } } if (rng.setStart) { rng.setStart(startContainer, startOffset); rng.setEnd(endContainer, endOffset); selection.setRng(rng); } else { try { rng = editor.getDoc().body.createTextRange(); rng.moveToElementText(rootNode); rng.collapse(true); rng.moveStart('character', startOffset); if (endOffset > 0) rng.moveEnd('character', endOffset); rng.select(); } catch (ex) { // Ignore } } editor.nodeChanged(); }; // Force root blocks if (settings.forced_root_block) { editor.onKeyUp.add(addRootBlocks); editor.onClick.add(addRootBlocks); } }; (function(tinymce) { // Shorten names var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, extend = tinymce.extend; tinymce.create('tinymce.ControlManager', { ControlManager : function(ed, s) { var t = this, i; s = s || {}; t.editor = ed; t.controls = {}; t.onAdd = new tinymce.util.Dispatcher(t); t.onPostRender = new tinymce.util.Dispatcher(t); t.prefix = s.prefix || ed.id + '_'; t._cls = {}; t.onPostRender.add(function() { each(t.controls, function(c) { c.postRender(); }); }); }, get : function(id) { return this.controls[this.prefix + id] || this.controls[id]; }, setActive : function(id, s) { var c = null; if (c = this.get(id)) c.setActive(s); return c; }, setDisabled : function(id, s) { var c = null; if (c = this.get(id)) c.setDisabled(s); return c; }, add : function(c) { var t = this; if (c) { t.controls[c.id] = c; t.onAdd.dispatch(c, t); } return c; }, createControl : function(n) { var c, t = this, ed = t.editor; each(ed.plugins, function(p) { if (p.createControl) { c = p.createControl(n, t); if (c) return false; } }); switch (n) { case "|": case "separator": return t.createSeparator(); } if (!c && ed.buttons && (c = ed.buttons[n])) return t.createButton(n, c); return t.add(c); }, createDropMenu : function(id, s, cc) { var t = this, ed = t.editor, c, bm, v, cls; s = extend({ 'class' : 'mceDropDown', constrain : ed.settings.constrain_menus }, s); s['class'] = s['class'] + ' ' + ed.getParam('skin') + 'Skin'; if (v = ed.getParam('skin_variant')) s['class'] += ' ' + ed.getParam('skin') + 'Skin' + v.substring(0, 1).toUpperCase() + v.substring(1); id = t.prefix + id; cls = cc || t._cls.dropmenu || tinymce.ui.DropMenu; c = t.controls[id] = new cls(id, s); c.onAddItem.add(function(c, o) { var s = o.settings; s.title = ed.getLang(s.title, s.title); if (!s.onclick) { s.onclick = function(v) { if (s.cmd) ed.execCommand(s.cmd, s.ui || false, s.value); }; } }); ed.onRemove.add(function() { c.destroy(); }); // Fix for bug #1897785, #1898007 if (tinymce.isIE) { c.onShowMenu.add(function() { // IE 8 needs focus in order to store away a range with the current collapsed caret location ed.focus(); bm = ed.selection.getBookmark(1); }); c.onHideMenu.add(function() { if (bm) { ed.selection.moveToBookmark(bm); bm = 0; } }); } return t.add(c); }, createListBox : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, scope : s.scope, control_manager : t }, s); id = t.prefix + id; function useNativeListForAccessibility(ed) { return ed.settings.use_accessible_selects && !tinymce.isGecko } if (ed.settings.use_native_selects || useNativeListForAccessibility(ed)) c = new tinymce.ui.NativeListBox(id, s); else { cls = cc || t._cls.listbox || tinymce.ui.ListBox; c = new cls(id, s, ed); } t.controls[id] = c; // Fix focus problem in Safari if (tinymce.isWebKit) { c.onPostRender.add(function(c, n) { // Store bookmark on mousedown Event.add(n, 'mousedown', function() { ed.bookmark = ed.selection.getBookmark(1); }); // Restore on focus, since it might be lost Event.add(n, 'focus', function() { ed.selection.moveToBookmark(ed.bookmark); ed.bookmark = null; }); }); } if (c.hideMenu) ed.onMouseDown.add(c.hideMenu, c); return t.add(c); }, createButton : function(id, s, cc) { var t = this, ed = t.editor, o, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.label = ed.translate(s.label); s.scope = s.scope || ed; if (!s.onclick && !s.menu_button) { s.onclick = function() { ed.execCommand(s.cmd, s.ui || false, s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, unavailable_prefix : ed.getLang('unavailable', ''), scope : s.scope, control_manager : t }, s); id = t.prefix + id; if (s.menu_button) { cls = cc || t._cls.menubutton || tinymce.ui.MenuButton; c = new cls(id, s, ed); ed.onMouseDown.add(c.hideMenu, c); } else { cls = t._cls.button || tinymce.ui.Button; c = new cls(id, s, ed); } return t.add(c); }, createMenuButton : function(id, s, cc) { s = s || {}; s.menu_button = 1; return this.createButton(id, s, cc); }, createSplitButton : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onclick) { s.onclick = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, scope : s.scope, control_manager : t }, s); id = t.prefix + id; cls = cc || t._cls.splitbutton || tinymce.ui.SplitButton; c = t.add(new cls(id, s, ed)); ed.onMouseDown.add(c.hideMenu, c); return c; }, createColorSplitButton : function(id, s, cc) { var t = this, ed = t.editor, cmd, c, cls, bm; if (t.get(id)) return null; s.title = ed.translate(s.title); s.scope = s.scope || ed; if (!s.onclick) { s.onclick = function(v) { if (tinymce.isIE) bm = ed.selection.getBookmark(1); ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } if (!s.onselect) { s.onselect = function(v) { ed.execCommand(s.cmd, s.ui || false, v || s.value); }; } s = extend({ title : s.title, 'class' : 'mce_' + id, 'menu_class' : ed.getParam('skin') + 'Skin', scope : s.scope, more_colors_title : ed.getLang('more_colors') }, s); id = t.prefix + id; cls = cc || t._cls.colorsplitbutton || tinymce.ui.ColorSplitButton; c = new cls(id, s, ed); ed.onMouseDown.add(c.hideMenu, c); // Remove the menu element when the editor is removed ed.onRemove.add(function() { c.destroy(); }); // Fix for bug #1897785, #1898007 if (tinymce.isIE) { c.onShowMenu.add(function() { // IE 8 needs focus in order to store away a range with the current collapsed caret location ed.focus(); bm = ed.selection.getBookmark(1); }); c.onHideMenu.add(function() { if (bm) { ed.selection.moveToBookmark(bm); bm = 0; } }); } return t.add(c); }, createToolbar : function(id, s, cc) { var c, t = this, cls; id = t.prefix + id; cls = cc || t._cls.toolbar || tinymce.ui.Toolbar; c = new cls(id, s, t.editor); if (t.get(id)) return null; return t.add(c); }, createToolbarGroup : function(id, s, cc) { var c, t = this, cls; id = t.prefix + id; cls = cc || this._cls.toolbarGroup || tinymce.ui.ToolbarGroup; c = new cls(id, s, t.editor); if (t.get(id)) return null; return t.add(c); }, createSeparator : function(cc) { var cls = cc || this._cls.separator || tinymce.ui.Separator; return new cls(); }, setControlType : function(n, c) { return this._cls[n.toLowerCase()] = c; }, destroy : function() { each(this.controls, function(c) { c.destroy(); }); this.controls = null; } }); })(tinymce); (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher, each = tinymce.each, isIE = tinymce.isIE, isOpera = tinymce.isOpera; tinymce.create('tinymce.WindowManager', { WindowManager : function(ed) { var t = this; t.editor = ed; t.onOpen = new Dispatcher(t); t.onClose = new Dispatcher(t); t.params = {}; t.features = {}; }, open : function(s, p) { var t = this, f = '', x, y, mo = t.editor.settings.dialog_type == 'modal', w, sw, sh, vp = tinymce.DOM.getViewPort(), u; // Default some options s = s || {}; p = p || {}; sw = isOpera ? vp.w : screen.width; // Opera uses windows inside the Opera window sh = isOpera ? vp.h : screen.height; s.name = s.name || 'mc_' + new Date().getTime(); s.width = parseInt(s.width || 320); s.height = parseInt(s.height || 240); s.resizable = true; s.left = s.left || parseInt(sw / 2.0) - (s.width / 2.0); s.top = s.top || parseInt(sh / 2.0) - (s.height / 2.0); p.inline = false; p.mce_width = s.width; p.mce_height = s.height; p.mce_auto_focus = s.auto_focus; if (mo) { if (isIE) { s.center = true; s.help = false; s.dialogWidth = s.width + 'px'; s.dialogHeight = s.height + 'px'; s.scroll = s.scrollbars || false; } } // Build features string each(s, function(v, k) { if (tinymce.is(v, 'boolean')) v = v ? 'yes' : 'no'; if (!/^(name|url)$/.test(k)) { if (isIE && mo) f += (f ? ';' : '') + k + ':' + v; else f += (f ? ',' : '') + k + '=' + v; } }); t.features = s; t.params = p; t.onOpen.dispatch(t, s, p); u = s.url || s.file; u = tinymce._addVer(u); try { if (isIE && mo) { w = 1; window.showModalDialog(u, window, f); } else w = window.open(u, s.name, f); } catch (ex) { // Ignore } if (!w) alert(t.editor.getLang('popup_blocked')); }, close : function(w) { w.close(); this.onClose.dispatch(this); }, createInstance : function(cl, a, b, c, d, e) { var f = tinymce.resolve(cl); return new f(a, b, c, d, e); }, confirm : function(t, cb, s, w) { w = w || window; cb.call(s || this, w.confirm(this._decode(this.editor.getLang(t, t)))); }, alert : function(tx, cb, s, w) { var t = this; w = w || window; w.alert(t._decode(t.editor.getLang(tx, tx))); if (cb) cb.call(s || t); }, resizeBy : function(dw, dh, win) { win.resizeBy(dw, dh); }, // Internal functions _decode : function(s) { return tinymce.DOM.decode(s).replace(/\\n/g, '\n'); } }); }(tinymce)); (function(tinymce) { tinymce.Formatter = function(ed) { var formats = {}, each = tinymce.each, dom = ed.dom, selection = ed.selection, TreeWalker = tinymce.dom.TreeWalker, rangeUtils = new tinymce.dom.RangeUtils(dom), isValid = ed.schema.isValidChild, isBlock = dom.isBlock, forcedRootBlock = ed.settings.forced_root_block, nodeIndex = dom.nodeIndex, INVISIBLE_CHAR = tinymce.isGecko ? '\u200B' : '\uFEFF', MCE_ATTR_RE = /^(src|href|style)$/, FALSE = false, TRUE = true, undef, getContentEditable = dom.getContentEditable; function isArray(obj) { return obj instanceof Array; }; function getParents(node, selector) { return dom.getParents(node, selector, dom.getRoot()); }; function isCaretNode(node) { return node.nodeType === 1 && node.id === '_mce_caret'; }; function defaultFormats() { register({ alignleft : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}, defaultBlock: 'div'}, {selector : 'img,table', collapsed : false, styles : {'float' : 'left'}} ], aligncenter : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}, defaultBlock: 'div'}, {selector : 'img', collapsed : false, styles : {display : 'block', marginLeft : 'auto', marginRight : 'auto'}}, {selector : 'table', collapsed : false, styles : {marginLeft : 'auto', marginRight : 'auto'}} ], alignright : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}, defaultBlock: 'div'}, {selector : 'img,table', collapsed : false, styles : {'float' : 'right'}} ], alignfull : [ {selector : 'figure,p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'justify'}, defaultBlock: 'div'} ], bold : [ {inline : 'strong', remove : 'all'}, {inline : 'span', styles : {fontWeight : 'bold'}}, {inline : 'b', remove : 'all'} ], italic : [ {inline : 'em', remove : 'all'}, {inline : 'span', styles : {fontStyle : 'italic'}}, {inline : 'i', remove : 'all'} ], underline : [ {inline : 'span', styles : {textDecoration : 'underline'}, exact : true}, {inline : 'u', remove : 'all'} ], strikethrough : [ {inline : 'span', styles : {textDecoration : 'line-through'}, exact : true}, {inline : 'strike', remove : 'all'} ], forecolor : {inline : 'span', styles : {color : '%value'}, wrap_links : false}, hilitecolor : {inline : 'span', styles : {backgroundColor : '%value'}, wrap_links : false}, fontname : {inline : 'span', styles : {fontFamily : '%value'}}, fontsize : {inline : 'span', styles : {fontSize : '%value'}}, fontsize_class : {inline : 'span', attributes : {'class' : '%value'}}, blockquote : {block : 'blockquote', wrapper : 1, remove : 'all'}, subscript : {inline : 'sub'}, superscript : {inline : 'sup'}, link : {inline : 'a', selector : 'a', remove : 'all', split : true, deep : true, onmatch : function(node) { return true; }, onformat : function(elm, fmt, vars) { each(vars, function(value, key) { dom.setAttrib(elm, key, value); }); } }, removeformat : [ {selector : 'b,strong,em,i,font,u,strike', remove : 'all', split : true, expand : false, block_expand : true, deep : true}, {selector : 'span', attributes : ['style', 'class'], remove : 'empty', split : true, expand : false, deep : true}, {selector : '*', attributes : ['style', 'class'], split : false, expand : false, deep : true} ] }); // Register default block formats each('p h1 h2 h3 h4 h5 h6 div address pre div code dt dd samp'.split(/\s/), function(name) { register(name, {block : name, remove : 'all'}); }); // Register user defined formats register(ed.settings.formats); }; function addKeyboardShortcuts() { // Add some inline shortcuts ed.addShortcut('ctrl+b', 'bold_desc', 'Bold'); ed.addShortcut('ctrl+i', 'italic_desc', 'Italic'); ed.addShortcut('ctrl+u', 'underline_desc', 'Underline'); // BlockFormat shortcuts keys for (var i = 1; i <= 6; i++) { ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]); } ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']); ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']); ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']); }; // Public functions function get(name) { return name ? formats[name] : formats; }; function register(name, format) { if (name) { if (typeof(name) !== 'string') { each(name, function(format, name) { register(name, format); }); } else { // Force format into array and add it to internal collection format = format.length ? format : [format]; each(format, function(format) { // Set deep to false by default on selector formats this to avoid removing // alignment on images inside paragraphs when alignment is changed on paragraphs if (format.deep === undef) format.deep = !format.selector; // Default to true if (format.split === undef) format.split = !format.selector || format.inline; // Default to true if (format.remove === undef && format.selector && !format.inline) format.remove = 'none'; // Mark format as a mixed format inline + block level if (format.selector && format.inline) { format.mixed = true; format.block_expand = true; } // Split classes if needed if (typeof(format.classes) === 'string') format.classes = format.classes.split(/\s+/); }); formats[name] = format; } } }; var getTextDecoration = function(node) { var decoration; ed.dom.getParent(node, function(n) { decoration = ed.dom.getStyle(n, 'text-decoration'); return decoration && decoration !== 'none'; }); return decoration; }; var processUnderlineAndColor = function(node) { var textDecoration; if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) { textDecoration = getTextDecoration(node.parentNode); if (ed.dom.getStyle(node, 'color') && textDecoration) { ed.dom.setStyle(node, 'text-decoration', textDecoration); } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) { ed.dom.setStyle(node, 'text-decoration', null); } } }; function apply(name, vars, node) { var formatList = get(name), format = formatList[0], bookmark, rng, i, isCollapsed = selection.isCollapsed(); function setElementFormat(elm, fmt) { fmt = fmt || format; if (elm) { if (fmt.onformat) { fmt.onformat(elm, fmt, vars, node); } each(fmt.styles, function(value, name) { dom.setStyle(elm, name, replaceVars(value, vars)); }); each(fmt.attributes, function(value, name) { dom.setAttrib(elm, name, replaceVars(value, vars)); }); each(fmt.classes, function(value) { value = replaceVars(value, vars); if (!dom.hasClass(elm, value)) dom.addClass(elm, value); }); } }; function adjustSelectionToVisibleSelection() { function findSelectionEnd(start, end) { var walker = new TreeWalker(end); for (node = walker.current(); node; node = walker.prev()) { if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') { return node; } } }; // Adjust selection so that a end container with a end offset of zero is not included in the selection // as this isn't visible to the user. var rng = ed.selection.getRng(); var start = rng.startContainer; var end = rng.endContainer; if (start != end && rng.endOffset === 0) { var newEnd = findSelectionEnd(start, end); var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length; rng.setEnd(newEnd, endOffset); } return rng; } function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){ var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm; // find the index of the first child list. each(node.childNodes, function(n, index) { if (n.nodeName === "UL" || n.nodeName === "OL") { listIndex = index; list = n; return false; } }); // get the index of the bookmarks each(node.childNodes, function(n, index) { if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") { if (n.id == bookmark.id + "_start") { startIndex = index; } else if (n.id == bookmark.id + "_end") { endIndex = index; } } }); // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) { each(tinymce.grep(node.childNodes), process); return 0; } else { currentWrapElm = dom.clone(wrapElm, FALSE); // create a list of the nodes on the same side of the list as the selection each(tinymce.grep(node.childNodes), function(n, index) { if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) { nodes.push(n); n.parentNode.removeChild(n); } }); // insert the wrapping element either before or after the list. if (startIndex < listIndex) { node.insertBefore(currentWrapElm, list); } else if (startIndex > listIndex) { node.insertBefore(currentWrapElm, list.nextSibling); } // add the new nodes to the list. newWrappers.push(currentWrapElm); each(nodes, function(node) { currentWrapElm.appendChild(node); }); return currentWrapElm; } }; function applyRngStyle(rng, bookmark, node_specific) { var newWrappers = [], wrapName, wrapElm, contentEditable = true; // Setup wrapper element wrapName = format.inline || format.block; wrapElm = dom.create(wrapName); setElementFormat(wrapElm); rangeUtils.walk(rng, function(nodes) { var currentWrapElm; function process(node) { var nodeName, parentName, found, hasContentEditableState, lastContentEditable; lastContentEditable = contentEditable; nodeName = node.nodeName.toLowerCase(); parentName = node.parentNode.nodeName.toLowerCase(); // Node has a contentEditable value if (node.nodeType === 1 && getContentEditable(node)) { lastContentEditable = contentEditable; contentEditable = getContentEditable(node) === "true"; hasContentEditableState = true; // We don't want to wrap the container only it's children } // Stop wrapping on br elements if (isEq(nodeName, 'br')) { currentWrapElm = 0; // Remove any br elements when we wrap things if (format.block) dom.remove(node); return; } // If node is wrapper type if (format.wrapper && matchNode(node, name, vars)) { currentWrapElm = 0; return; } // Can we rename the block if (contentEditable && !hasContentEditableState && format.block && !format.wrapper && isTextBlock(nodeName)) { node = dom.rename(node, wrapName); setElementFormat(node); newWrappers.push(node); currentWrapElm = 0; return; } // Handle selector patterns if (format.selector) { // Look for matching formats each(formatList, function(format) { // Check collapsed state if it exists if ('collapsed' in format && format.collapsed !== isCollapsed) { return; } if (dom.is(node, format.selector) && !isCaretNode(node)) { setElementFormat(node, format); found = true; } }); // Continue processing if a selector match wasn't found and a inline element is defined if (!format.inline || found) { currentWrapElm = 0; return; } } // Is it valid to wrap this item if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) && !(!node_specific && node.nodeType === 3 && node.nodeValue.length === 1 && node.nodeValue.charCodeAt(0) === 65279) && !isCaretNode(node)) { // Start wrapping if (!currentWrapElm) { // Wrap the node currentWrapElm = dom.clone(wrapElm, FALSE); node.parentNode.insertBefore(currentWrapElm, node); newWrappers.push(currentWrapElm); } currentWrapElm.appendChild(node); } else if (nodeName == 'li' && bookmark) { // Start wrapping - if we are in a list node and have a bookmark, then we will always begin by wrapping in a new element. currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process); } else { // Start a new wrapper for possible children currentWrapElm = 0; each(tinymce.grep(node.childNodes), process); if (hasContentEditableState) { contentEditable = lastContentEditable; // Restore last contentEditable state from stack } // End the last wrapper currentWrapElm = 0; } }; // Process siblings from range each(nodes, process); }); // Wrap links inside as well, for example color inside a link when the wrapper is around the link if (format.wrap_links === false) { each(newWrappers, function(node) { function process(node) { var i, currentWrapElm, children; if (node.nodeName === 'A') { currentWrapElm = dom.clone(wrapElm, FALSE); newWrappers.push(currentWrapElm); children = tinymce.grep(node.childNodes); for (i = 0; i < children.length; i++) currentWrapElm.appendChild(children[i]); node.appendChild(currentWrapElm); } each(tinymce.grep(node.childNodes), process); }; process(node); }); } // Cleanup each(newWrappers, function(node) { var childCount; function getChildCount(node) { var count = 0; each(node.childNodes, function(node) { if (!isWhiteSpaceNode(node) && !isBookmarkNode(node)) count++; }); return count; }; function mergeStyles(node) { var child, clone; each(node.childNodes, function(node) { if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) { child = node; return FALSE; // break loop } }); // If child was found and of the same type as the current node if (child && matchName(child, format)) { clone = dom.clone(child, FALSE); setElementFormat(clone); dom.replace(clone, node, TRUE); dom.remove(child, 1); } return clone || node; }; childCount = getChildCount(node); // Remove empty nodes but only if there is multiple wrappers and they are not block // elements so never remove single <h1></h1> since that would remove the currrent empty block element where the caret is at if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) { dom.remove(node, 1); return; } if (format.inline || format.wrapper) { // Merges the current node with it's children of similar type to reduce the number of elements if (!format.exact && childCount === 1) node = mergeStyles(node); // Remove/merge children each(formatList, function(format) { // Merge all children of similar type will move styles from child to parent // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span> // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span> each(dom.select(format.inline, node), function(child) { var parent; // When wrap_links is set to false we don't want // to remove the format on children within links if (format.wrap_links === false) { parent = child.parentNode; do { if (parent.nodeName === 'A') return; } while (parent = parent.parentNode); } removeFormat(format, vars, child, format.exact ? child : null); }); }); // Remove child if direct parent is of same type if (matchNode(node.parentNode, name, vars)) { dom.remove(node, 1); node = 0; return TRUE; } // Look for parent with similar style format if (format.merge_with_parents) { dom.getParent(node.parentNode, function(parent) { if (matchNode(parent, name, vars)) { dom.remove(node, 1); node = 0; return TRUE; } }); } // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b> if (node && format.merge_siblings !== false) { node = mergeSiblings(getNonWhiteSpaceSibling(node), node); node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE)); } } }); }; if (format) { if (node) { if (node.nodeType) { rng = dom.createRng(); rng.setStartBefore(node); rng.setEndAfter(node); applyRngStyle(expandRng(rng, formatList), null, true); } else { applyRngStyle(node, null, true); } } else { if (!isCollapsed || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) { // Obtain selection node before selection is unselected by applyRngStyle() var curSelNode = ed.selection.getNode(); // If the formats have a default block and we can't find a parent block then start wrapping it with a DIV this is for forced_root_blocks: false // It's kind of a hack but people should be using the default block type P since all desktop editors work that way if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) { apply(formatList[0].defaultBlock); } // Apply formatting to selection ed.selection.setRng(adjustSelectionToVisibleSelection()); bookmark = selection.getBookmark(); applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark); // Colored nodes should be underlined so that the color of the underline matches the text color. if (format.styles && (format.styles.color || format.styles.textDecoration)) { tinymce.walk(curSelNode, processUnderlineAndColor, 'childNodes'); processUnderlineAndColor(curSelNode); } selection.moveToBookmark(bookmark); moveStart(selection.getRng(TRUE)); ed.nodeChanged(); } else performCaretAction('apply', name, vars); } } }; function remove(name, vars, node) { var formatList = get(name), format = formatList[0], bookmark, i, rng, contentEditable = true; // Merges the styles for each node function process(node) { var children, i, l, localContentEditable, lastContentEditable, hasContentEditableState; // Node has a contentEditable value if (node.nodeType === 1 && getContentEditable(node)) { lastContentEditable = contentEditable; contentEditable = getContentEditable(node) === "true"; hasContentEditableState = true; // We don't want to wrap the container only it's children } // Grab the children first since the nodelist might be changed children = tinymce.grep(node.childNodes); // Process current node if (contentEditable && !hasContentEditableState) { for (i = 0, l = formatList.length; i < l; i++) { if (removeFormat(formatList[i], vars, node, node)) break; } } // Process the children if (format.deep) { if (children.length) { for (i = 0, l = children.length; i < l; i++) process(children[i]); if (hasContentEditableState) { contentEditable = lastContentEditable; // Restore last contentEditable state from stack } } } }; function findFormatRoot(container) { var formatRoot; // Find format root each(getParents(container.parentNode).reverse(), function(parent) { var format; // Find format root element if (!formatRoot && parent.id != '_start' && parent.id != '_end') { // Is the node matching the format we are looking for format = matchNode(parent, name, vars); if (format && format.split !== false) formatRoot = parent; } }); return formatRoot; }; function wrapAndSplit(format_root, container, target, split) { var parent, clone, lastClone, firstClone, i, formatRootParent; // Format root found then clone formats and split it if (format_root) { formatRootParent = format_root.parentNode; for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) { clone = dom.clone(parent, FALSE); for (i = 0; i < formatList.length; i++) { if (removeFormat(formatList[i], vars, clone, clone)) { clone = 0; break; } } // Build wrapper node if (clone) { if (lastClone) clone.appendChild(lastClone); if (!firstClone) firstClone = clone; lastClone = clone; } } // Never split block elements if the format is mixed if (split && (!format.mixed || !isBlock(format_root))) container = dom.split(format_root, container); // Wrap container in cloned formats if (lastClone) { target.parentNode.insertBefore(lastClone, target); firstClone.appendChild(target); } } return container; }; function splitToFormatRoot(container) { return wrapAndSplit(findFormatRoot(container), container, container, true); }; function unwrap(start) { var node = dom.get(start ? '_start' : '_end'), out = node[start ? 'firstChild' : 'lastChild']; // If the end is placed within the start the result will be removed // So this checks if the out node is a bookmark node if it is it // checks for another more suitable node if (isBookmarkNode(out)) out = out[start ? 'firstChild' : 'lastChild']; dom.remove(node, true); return out; }; function removeRngStyle(rng) { var startContainer, endContainer, node; rng = expandRng(rng, formatList, TRUE); if (format.split) { startContainer = getContainer(rng, TRUE); endContainer = getContainer(rng); if (startContainer != endContainer) { // WebKit will render the table incorrectly if we wrap a TD in a SPAN so lets see if the can use the first child instead // This will happen if you tripple click a table cell and use remove formatting node = startContainer.firstChild; if (startContainer.nodeName == "TD" && node) { startContainer = node; } // Wrap start/end nodes in span element since these might be cloned/moved startContainer = wrap(startContainer, 'span', {id : '_start', 'data-mce-type' : 'bookmark'}); endContainer = wrap(endContainer, 'span', {id : '_end', 'data-mce-type' : 'bookmark'}); // Split start/end splitToFormatRoot(startContainer); splitToFormatRoot(endContainer); // Unwrap start/end to get real elements again startContainer = unwrap(TRUE); endContainer = unwrap(); } else startContainer = endContainer = splitToFormatRoot(startContainer); // Update range positions since they might have changed after the split operations rng.startContainer = startContainer.parentNode; rng.startOffset = nodeIndex(startContainer); rng.endContainer = endContainer.parentNode; rng.endOffset = nodeIndex(endContainer) + 1; } // Remove items between start/end rangeUtils.walk(rng, function(nodes) { each(nodes, function(node) { process(node); // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined. if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' && node.parentNode && getTextDecoration(node.parentNode) === 'underline') { removeFormat({'deep': false, 'exact': true, 'inline': 'span', 'styles': {'textDecoration' : 'underline'}}, null, node); } }); }); }; // Handle node if (node) { if (node.nodeType) { rng = dom.createRng(); rng.setStartBefore(node); rng.setEndAfter(node); removeRngStyle(rng); } else { removeRngStyle(node); } return; } if (!selection.isCollapsed() || !format.inline || dom.select('td.mceSelected,th.mceSelected').length) { bookmark = selection.getBookmark(); removeRngStyle(selection.getRng(TRUE)); selection.moveToBookmark(bookmark); // Check if start element still has formatting then we are at: "<b>text|</b>text" and need to move the start into the next text node if (format.inline && match(name, vars, selection.getStart())) { moveStart(selection.getRng(true)); } ed.nodeChanged(); } else performCaretAction('remove', name, vars); }; function toggle(name, vars, node) { var fmt = get(name); if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) remove(name, vars, node); else apply(name, vars, node); }; function matchNode(node, name, vars, similar) { var formatList = get(name), format, i, classes; function matchItems(node, format, item_name) { var key, value, items = format[item_name], i; // Custom match if (format.onmatch) { return format.onmatch(node, format, item_name); } // Check all items if (items) { // Non indexed object if (items.length === undef) { for (key in items) { if (items.hasOwnProperty(key)) { if (item_name === 'attributes') value = dom.getAttrib(node, key); else value = getStyle(node, key); if (similar && !value && !format.exact) return; if ((!similar || format.exact) && !isEq(value, replaceVars(items[key], vars))) return; } } } else { // Only one match needed for indexed arrays for (i = 0; i < items.length; i++) { if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i])) return format; } } } return format; }; if (formatList && node) { // Check each format in list for (i = 0; i < formatList.length; i++) { format = formatList[i]; // Name name, attributes, styles and classes if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) { // Match classes if (classes = format.classes) { for (i = 0; i < classes.length; i++) { if (!dom.hasClass(node, classes[i])) return; } } return format; } } } }; function match(name, vars, node) { var startNode; function matchParents(node) { // Find first node with similar format settings node = dom.getParent(node, function(node) { return !!matchNode(node, name, vars, true); }); // Do an exact check on the similar format element return matchNode(node, name, vars); }; // Check specified node if (node) return matchParents(node); // Check selected node node = selection.getNode(); if (matchParents(node)) return TRUE; // Check start node if it's different startNode = selection.getStart(); if (startNode != node) { if (matchParents(startNode)) return TRUE; } return FALSE; }; function matchAll(names, vars) { var startElement, matchedFormatNames = [], checkedMap = {}, i, ni, name; // Check start of selection for formats startElement = selection.getStart(); dom.getParent(startElement, function(node) { var i, name; for (i = 0; i < names.length; i++) { name = names[i]; if (!checkedMap[name] && matchNode(node, name, vars)) { checkedMap[name] = true; matchedFormatNames.push(name); } } }); return matchedFormatNames; }; function canApply(name) { var formatList = get(name), startNode, parents, i, x, selector; if (formatList) { startNode = selection.getStart(); parents = getParents(startNode); for (x = formatList.length - 1; x >= 0; x--) { selector = formatList[x].selector; // Format is not selector based, then always return TRUE if (!selector) return TRUE; for (i = parents.length - 1; i >= 0; i--) { if (dom.is(parents[i], selector)) return TRUE; } } } return FALSE; }; // Expose to public tinymce.extend(this, { get : get, register : register, apply : apply, remove : remove, toggle : toggle, match : match, matchAll : matchAll, matchNode : matchNode, canApply : canApply }); // Initialize defaultFormats(); addKeyboardShortcuts(); // Private functions function matchName(node, format) { // Check for inline match if (isEq(node, format.inline)) return TRUE; // Check for block match if (isEq(node, format.block)) return TRUE; // Check for selector match if (format.selector) return dom.is(node, format.selector); }; function isEq(str1, str2) { str1 = str1 || ''; str2 = str2 || ''; str1 = '' + (str1.nodeName || str1); str2 = '' + (str2.nodeName || str2); return str1.toLowerCase() == str2.toLowerCase(); }; function getStyle(node, name) { var styleVal = dom.getStyle(node, name); // Force the format to hex if (name == 'color' || name == 'backgroundColor') styleVal = dom.toHex(styleVal); // Opera will return bold as 700 if (name == 'fontWeight' && styleVal == 700) styleVal = 'bold'; return '' + styleVal; }; function replaceVars(value, vars) { if (typeof(value) != "string") value = value(vars); else if (vars) { value = value.replace(/%(\w+)/g, function(str, name) { return vars[name] || str; }); } return value; }; function isWhiteSpaceNode(node) { return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue); }; function wrap(node, name, attrs) { var wrapper = dom.create(name, attrs); node.parentNode.insertBefore(wrapper, node); wrapper.appendChild(node); return wrapper; }; function expandRng(rng, format, remove) { var sibling, lastIdx, leaf, endPoint, startContainer = rng.startContainer, startOffset = rng.startOffset, endContainer = rng.endContainer, endOffset = rng.endOffset; // This function walks up the tree if there is no siblings before/after the node function findParentContainer(start) { var container, parent, child, sibling, siblingName, root; container = parent = start ? startContainer : endContainer; siblingName = start ? 'previousSibling' : 'nextSibling'; root = dom.getRoot(); // If it's a text node and the offset is inside the text if (container.nodeType == 3 && !isWhiteSpaceNode(container)) { if (start ? startOffset > 0 : endOffset < container.nodeValue.length) { return container; } } for (;;) { // Stop expanding on block elements if (!format[0].block_expand && isBlock(parent)) return parent; // Walk left/right for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) { if (!isBookmarkNode(sibling) && !isWhiteSpaceNode(sibling)) { return parent; } } // Check if we can move up are we at root level or body level if (parent.parentNode == root) { container = parent; break; } parent = parent.parentNode; } return container; }; // This function walks down the tree to find the leaf at the selection. // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node. function findLeaf(node, offset) { if (offset === undef) offset = node.nodeType === 3 ? node.length : node.childNodes.length; while (node && node.hasChildNodes()) { node = node.childNodes[offset]; if (node) offset = node.nodeType === 3 ? node.length : node.childNodes.length; } return { node: node, offset: offset }; } // If index based start position then resolve it if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { lastIdx = startContainer.childNodes.length - 1; startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset]; if (startContainer.nodeType == 3) startOffset = 0; } // If index based end position then resolve it if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { lastIdx = endContainer.childNodes.length - 1; endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1]; if (endContainer.nodeType == 3) endOffset = endContainer.nodeValue.length; } // Expands the node to the closes contentEditable false element if it exists function findParentContentEditable(node) { var parent = node; while (parent) { if (parent.nodeType === 1 && getContentEditable(parent)) { return getContentEditable(parent) === "false" ? parent : node; } parent = parent.parentNode; } return node; }; function findWordEndPoint(container, offset, start) { var walker, node, pos, lastTextNode; function findSpace(node, offset) { var pos, pos2, str = node.nodeValue; if (typeof(offset) == "undefined") { offset = start ? str.length : 0; } if (start) { pos = str.lastIndexOf(' ', offset); pos2 = str.lastIndexOf('\u00a0', offset); pos = pos > pos2 ? pos : pos2; // Include the space on remove to avoid tag soup if (pos !== -1 && !remove) { pos++; } } else { pos = str.indexOf(' ', offset); pos2 = str.indexOf('\u00a0', offset); pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2; } return pos; }; if (container.nodeType === 3) { pos = findSpace(container, offset); if (pos !== -1) { return {container : container, offset : pos}; } lastTextNode = container; } // Walk the nodes inside the block walker = new TreeWalker(container, dom.getParent(container, isBlock) || ed.getBody()); while (node = walker[start ? 'prev' : 'next']()) { if (node.nodeType === 3) { lastTextNode = node; pos = findSpace(node); if (pos !== -1) { return {container : node, offset : pos}; } } else if (isBlock(node)) { break; } } if (lastTextNode) { if (start) { offset = 0; } else { offset = lastTextNode.length; } return {container: lastTextNode, offset: offset}; } }; function findSelectorEndPoint(container, sibling_name) { var parents, i, y, curFormat; if (container.nodeType == 3 && container.nodeValue.length === 0 && container[sibling_name]) container = container[sibling_name]; parents = getParents(container); for (i = 0; i < parents.length; i++) { for (y = 0; y < format.length; y++) { curFormat = format[y]; // If collapsed state is set then skip formats that doesn't match that if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed) continue; if (dom.is(parents[i], curFormat.selector)) return parents[i]; } } return container; }; function findBlockEndPoint(container, sibling_name, sibling_name2) { var node; // Expand to block of similar type if (!format[0].wrapper) node = dom.getParent(container, format[0].block); // Expand to first wrappable block element or any block element if (!node) node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, isBlock); // Exclude inner lists from wrapping if (node && format[0].wrapper) node = getParents(node, 'ul,ol').reverse()[0] || node; // Didn't find a block element look for first/last wrappable element if (!node) { node = container; while (node[sibling_name] && !isBlock(node[sibling_name])) { node = node[sibling_name]; // Break on BR but include it will be removed later on // we can't remove it now since we need to check if it can be wrapped if (isEq(node, 'br')) break; } } return node || container; }; // Expand to closest contentEditable element startContainer = findParentContentEditable(startContainer); endContainer = findParentContentEditable(endContainer); // Exclude bookmark nodes if possible if (isBookmarkNode(startContainer.parentNode) || isBookmarkNode(startContainer)) { startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode; startContainer = startContainer.nextSibling || startContainer; if (startContainer.nodeType == 3) startOffset = 0; } if (isBookmarkNode(endContainer.parentNode) || isBookmarkNode(endContainer)) { endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode; endContainer = endContainer.previousSibling || endContainer; if (endContainer.nodeType == 3) endOffset = endContainer.length; } if (format[0].inline) { if (rng.collapsed) { // Expand left to closest word boundery endPoint = findWordEndPoint(startContainer, startOffset, true); if (endPoint) { startContainer = endPoint.container; startOffset = endPoint.offset; } // Expand right to closest word boundery endPoint = findWordEndPoint(endContainer, endOffset); if (endPoint) { endContainer = endPoint.container; endOffset = endPoint.offset; } } // Avoid applying formatting to a trailing space. leaf = findLeaf(endContainer, endOffset); if (leaf.node) { while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling) leaf = findLeaf(leaf.node.previousSibling); if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 && leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') { if (leaf.offset > 1) { endContainer = leaf.node; endContainer.splitText(leaf.offset - 1); } } } } // Move start/end point up the tree if the leaves are sharp and if we are in different containers // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>! // This will reduce the number of wrapper elements that needs to be created // Move start point up the tree if (format[0].inline || format[0].block_expand) { if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { startContainer = findParentContainer(true); } if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { endContainer = findParentContainer(); } } // Expand start/end container to matching selector if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { // Find new startContainer/endContainer if there is better one startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); } // Expand start/end container to matching block element or text node if (format[0].block || format[0].selector) { // Find new startContainer/endContainer if there is better one startContainer = findBlockEndPoint(startContainer, 'previousSibling'); endContainer = findBlockEndPoint(endContainer, 'nextSibling'); // Non block element then try to expand up the leaf if (format[0].block) { if (!isBlock(startContainer)) startContainer = findParentContainer(true); if (!isBlock(endContainer)) endContainer = findParentContainer(); } } // Setup index for startContainer if (startContainer.nodeType == 1) { startOffset = nodeIndex(startContainer); startContainer = startContainer.parentNode; } // Setup index for endContainer if (endContainer.nodeType == 1) { endOffset = nodeIndex(endContainer) + 1; endContainer = endContainer.parentNode; } // Return new range like object return { startContainer : startContainer, startOffset : startOffset, endContainer : endContainer, endOffset : endOffset }; } function removeFormat(format, vars, node, compare_node) { var i, attrs, stylesModified; // Check if node matches format if (!matchName(node, format)) return FALSE; // Should we compare with format attribs and styles if (format.remove != 'all') { // Remove styles each(format.styles, function(value, name) { value = replaceVars(value, vars); // Indexed array if (typeof(name) === 'number') { name = value; compare_node = 0; } if (!compare_node || isEq(getStyle(compare_node, name), value)) dom.setStyle(node, name, ''); stylesModified = 1; }); // Remove style attribute if it's empty if (stylesModified && dom.getAttrib(node, 'style') == '') { node.removeAttribute('style'); node.removeAttribute('data-mce-style'); } // Remove attributes each(format.attributes, function(value, name) { var valueOut; value = replaceVars(value, vars); // Indexed array if (typeof(name) === 'number') { name = value; compare_node = 0; } if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { // Keep internal classes if (name == 'class') { value = dom.getAttrib(node, name); if (value) { // Build new class value where everything is removed except the internal prefixed classes valueOut = ''; each(value.split(/\s+/), function(cls) { if (/mce\w+/.test(cls)) valueOut += (valueOut ? ' ' : '') + cls; }); // We got some internal classes left if (valueOut) { dom.setAttrib(node, name, valueOut); return; } } } // IE6 has a bug where the attribute doesn't get removed correctly if (name == "class") node.removeAttribute('className'); // Remove mce prefixed attributes if (MCE_ATTR_RE.test(name)) node.removeAttribute('data-mce-' + name); node.removeAttribute(name); } }); // Remove classes each(format.classes, function(value) { value = replaceVars(value, vars); if (!compare_node || dom.hasClass(compare_node, value)) dom.removeClass(node, value); }); // Check for non internal attributes attrs = dom.getAttribs(node); for (i = 0; i < attrs.length; i++) { if (attrs[i].nodeName.indexOf('_') !== 0) return FALSE; } } // Remove the inline child if it's empty for example <b> or <span> if (format.remove != 'none') { removeNode(node, format); return TRUE; } }; function removeNode(node, format) { var parentNode = node.parentNode, rootBlockElm; function find(node, next, inc) { node = getNonWhiteSpaceSibling(node, next, inc); return !node || (node.nodeName == 'BR' || isBlock(node)); }; if (format.block) { if (!forcedRootBlock) { // Append BR elements if needed before we remove the block if (isBlock(node) && !isBlock(parentNode)) { if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1)) node.insertBefore(dom.create('br'), node.firstChild); if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1)) node.appendChild(dom.create('br')); } } else { // Wrap the block in a forcedRootBlock if we are at the root of document if (parentNode == dom.getRoot()) { if (!format.list_block || !isEq(node, format.list_block)) { each(tinymce.grep(node.childNodes), function(node) { if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) { if (!rootBlockElm) rootBlockElm = wrap(node, forcedRootBlock); else rootBlockElm.appendChild(node); } else rootBlockElm = 0; }); } } } } // Never remove nodes that isn't the specified inline element if a selector is specified too if (format.selector && format.inline && !isEq(format.inline, node)) return; dom.remove(node, 1); }; function getNonWhiteSpaceSibling(node, next, inc) { if (node) { next = next ? 'nextSibling' : 'previousSibling'; for (node = inc ? node : node[next]; node; node = node[next]) { if (node.nodeType == 1 || !isWhiteSpaceNode(node)) return node; } } }; function isBookmarkNode(node) { return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark'; }; function mergeSiblings(prev, next) { var marker, sibling, tmpSibling; function compareElements(node1, node2) { // Not the same name if (node1.nodeName != node2.nodeName) return FALSE; function getAttribs(node) { var attribs = {}; each(dom.getAttribs(node), function(attr) { var name = attr.nodeName.toLowerCase(); // Don't compare internal attributes or style if (name.indexOf('_') !== 0 && name !== 'style') attribs[name] = dom.getAttrib(node, name); }); return attribs; }; function compareObjects(obj1, obj2) { var value, name; for (name in obj1) { // Obj1 has item obj2 doesn't have if (obj1.hasOwnProperty(name)) { value = obj2[name]; // Obj2 doesn't have obj1 item if (value === undef) return FALSE; // Obj2 item has a different value if (obj1[name] != value) return FALSE; // Delete similar value delete obj2[name]; } } // Check if obj 2 has something obj 1 doesn't have for (name in obj2) { // Obj2 has item obj1 doesn't have if (obj2.hasOwnProperty(name)) return FALSE; } return TRUE; }; // Attribs are not the same if (!compareObjects(getAttribs(node1), getAttribs(node2))) return FALSE; // Styles are not the same if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) return FALSE; return TRUE; }; function findElementSibling(node, sibling_name) { for (sibling = node; sibling; sibling = sibling[sibling_name]) { if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0) return node; if (sibling.nodeType == 1 && !isBookmarkNode(sibling)) return sibling; } return node; }; // Check if next/prev exists and that they are elements if (prev && next) { // If previous sibling is empty then jump over it prev = findElementSibling(prev, 'previousSibling'); next = findElementSibling(next, 'nextSibling'); // Compare next and previous nodes if (compareElements(prev, next)) { // Append nodes between for (sibling = prev.nextSibling; sibling && sibling != next;) { tmpSibling = sibling; sibling = sibling.nextSibling; prev.appendChild(tmpSibling); } // Remove next node dom.remove(next); // Move children into prev node each(tinymce.grep(next.childNodes), function(node) { prev.appendChild(node); }); return prev; } } return next; }; function isTextBlock(name) { return /^(h[1-6]|p|div|pre|address|dl|dt|dd)$/.test(name); }; function getContainer(rng, start) { var container, offset, lastIdx, walker; container = rng[start ? 'startContainer' : 'endContainer']; offset = rng[start ? 'startOffset' : 'endOffset']; if (container.nodeType == 1) { lastIdx = container.childNodes.length - 1; if (!start && offset) offset--; container = container.childNodes[offset > lastIdx ? lastIdx : offset]; } // If start text node is excluded then walk to the next node if (container.nodeType === 3 && start && offset >= container.nodeValue.length) { container = new TreeWalker(container, ed.getBody()).next() || container; } // If end text node is excluded then walk to the previous node if (container.nodeType === 3 && !start && offset === 0) { container = new TreeWalker(container, ed.getBody()).prev() || container; } return container; }; function performCaretAction(type, name, vars) { var caretContainerId = '_mce_caret', debug = ed.settings.caret_debug; // Creates a caret container bogus element function createCaretContainer(fill) { var caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style: debug ? 'color:red' : ''}); if (fill) { caretContainer.appendChild(ed.getDoc().createTextNode(INVISIBLE_CHAR)); } return caretContainer; }; function isCaretContainerEmpty(node, nodes) { while (node) { if ((node.nodeType === 3 && node.nodeValue !== INVISIBLE_CHAR) || node.childNodes.length > 1) { return false; } // Collect nodes if (nodes && node.nodeType === 1) { nodes.push(node); } node = node.firstChild; } return true; }; // Returns any parent caret container element function getParentCaretContainer(node) { while (node) { if (node.id === caretContainerId) { return node; } node = node.parentNode; } }; // Finds the first text node in the specified node function findFirstTextNode(node) { var walker; if (node) { walker = new TreeWalker(node, node); for (node = walker.current(); node; node = walker.next()) { if (node.nodeType === 3) { return node; } } } }; // Removes the caret container for the specified node or all on the current document function removeCaretContainer(node, move_caret) { var child, rng; if (!node) { node = getParentCaretContainer(selection.getStart()); if (!node) { while (node = dom.get(caretContainerId)) { removeCaretContainer(node, false); } } } else { rng = selection.getRng(true); if (isCaretContainerEmpty(node)) { if (move_caret !== false) { rng.setStartBefore(node); rng.setEndBefore(node); } dom.remove(node); } else { child = findFirstTextNode(node); if (child.nodeValue.charAt(0) === INVISIBLE_CHAR) { child = child.deleteData(0, 1); } dom.remove(node, 1); } selection.setRng(rng); } }; // Applies formatting to the caret postion function applyCaretFormat() { var rng, caretContainer, textNode, offset, bookmark, container, text; rng = selection.getRng(true); offset = rng.startOffset; container = rng.startContainer; text = container.nodeValue; caretContainer = getParentCaretContainer(selection.getStart()); if (caretContainer) { textNode = findFirstTextNode(caretContainer); } // Expand to word is caret is in the middle of a text node and the char before/after is a alpha numeric character if (text && offset > 0 && offset < text.length && /\w/.test(text.charAt(offset)) && /\w/.test(text.charAt(offset - 1))) { // Get bookmark of caret position bookmark = selection.getBookmark(); // Collapse bookmark range (WebKit) rng.collapse(true); // Expand the range to the closest word and split it at those points rng = expandRng(rng, get(name)); rng = rangeUtils.split(rng); // Apply the format to the range apply(name, vars, rng); // Move selection back to caret position selection.moveToBookmark(bookmark); } else { if (!caretContainer || textNode.nodeValue !== INVISIBLE_CHAR) { caretContainer = createCaretContainer(true); textNode = caretContainer.firstChild; rng.insertNode(caretContainer); offset = 1; apply(name, vars, caretContainer); } else { apply(name, vars, caretContainer); } // Move selection to text node selection.setCursorLocation(textNode, offset); } }; function removeCaretFormat() { var rng = selection.getRng(true), container, offset, bookmark, hasContentAfter, node, formatNode, parents = [], i, caretContainer; container = rng.startContainer; offset = rng.startOffset; node = container; if (container.nodeType == 3) { if (offset != container.nodeValue.length || container.nodeValue === INVISIBLE_CHAR) { hasContentAfter = true; } node = node.parentNode; } while (node) { if (matchNode(node, name, vars)) { formatNode = node; break; } if (node.nextSibling) { hasContentAfter = true; } parents.push(node); node = node.parentNode; } // Node doesn't have the specified format if (!formatNode) { return; } // Is there contents after the caret then remove the format on the element if (hasContentAfter) { // Get bookmark of caret position bookmark = selection.getBookmark(); // Collapse bookmark range (WebKit) rng.collapse(true); // Expand the range to the closest word and split it at those points rng = expandRng(rng, get(name), true); rng = rangeUtils.split(rng); // Remove the format from the range remove(name, vars, rng); // Move selection back to caret position selection.moveToBookmark(bookmark); } else { caretContainer = createCaretContainer(); node = caretContainer; for (i = parents.length - 1; i >= 0; i--) { node.appendChild(dom.clone(parents[i], false)); node = node.firstChild; } // Insert invisible character into inner most format element node.appendChild(dom.doc.createTextNode(INVISIBLE_CHAR)); node = node.firstChild; // Insert caret container after the formated node dom.insertAfter(caretContainer, formatNode); // Move selection to text node selection.setCursorLocation(node, 1); } }; // Only bind the caret events once if (!self._hasCaretEvents) { // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements ed.onBeforeGetContent.addToTop(function() { var nodes = [], i; if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { // Mark children i = nodes.length; while (i--) { dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); } } }); // Remove caret container on mouse up and on key up tinymce.each('onMouseUp onKeyUp'.split(' '), function(name) { ed[name].addToTop(function() { removeCaretContainer(); }); }); // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys ed.onKeyDown.addToTop(function(ed, e) { var keyCode = e.keyCode; if (keyCode == 8 || keyCode == 37 || keyCode == 39) { removeCaretContainer(getParentCaretContainer(selection.getStart())); } }); self._hasCaretEvents = true; } // Do apply or remove caret format if (type == "apply") { applyCaretFormat(); } else { removeCaretFormat(); } }; function moveStart(rng) { var container = rng.startContainer, offset = rng.startOffset, isAtEndOfText, walker, node, nodes, tmpNode; // Convert text node into index if possible if (container.nodeType == 3 && offset >= container.nodeValue.length) { // Get the parent container location and walk from there offset = nodeIndex(container); container = container.parentNode; isAtEndOfText = true; } // Move startContainer/startOffset in to a suitable node if (container.nodeType == 1) { nodes = container.childNodes; container = nodes[Math.min(offset, nodes.length - 1)]; walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); // If offset is at end of the parent node walk to the next one if (offset > nodes.length - 1 || isAtEndOfText) walker.next(); for (node = walker.current(); node; node = walker.next()) { if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { // IE has a "neat" feature where it moves the start node into the closest element // we can avoid this by inserting an element before it and then remove it after we set the selection tmpNode = dom.create('a', null, INVISIBLE_CHAR); node.parentNode.insertBefore(tmpNode, node); // Set selection and remove tmpNode rng.setStart(node, 0); selection.setRng(rng); dom.remove(tmpNode); return; } } } }; }; })(tinymce); tinymce.onAddEditor.add(function(tinymce, ed) { var filters, fontSizes, dom, settings = ed.settings; function replaceWithSpan(node, styles) { tinymce.each(styles, function(value, name) { if (value) dom.setStyle(node, name, value); }); dom.rename(node, 'span'); }; function convert(editor, params) { dom = editor.dom; if (settings.convert_fonts_to_spans) { tinymce.each(dom.select('font,u,strike', params.node), function(node) { filters[node.nodeName.toLowerCase()](ed.dom, node); }); } }; if (settings.inline_styles) { fontSizes = tinymce.explode(settings.font_size_legacy_values); filters = { font : function(dom, node) { replaceWithSpan(node, { backgroundColor : node.style.backgroundColor, color : node.color, fontFamily : node.face, fontSize : fontSizes[parseInt(node.size, 10) - 1] }); }, u : function(dom, node) { replaceWithSpan(node, { textDecoration : 'underline' }); }, strike : function(dom, node) { replaceWithSpan(node, { textDecoration : 'line-through' }); } }; ed.onPreProcess.add(convert); ed.onSetContent.add(convert); ed.onInit.add(function() { ed.selection.onSetContent.add(convert); }); } }); (function(tinymce) { var TreeWalker = tinymce.dom.TreeWalker; tinymce.EnterKey = function(editor) { var dom = editor.dom, selection = editor.selection, settings = editor.settings, undoManager = editor.undoManager; function handleEnterKey(evt) { var rng = selection.getRng(true), tmpRng, editableRoot, container, offset, parentBlock, documentMode, newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer; // Returns true if the block can be split into two blocks or not function canSplitBlock(node) { return node && dom.isBlock(node) && !/^(TD|TH|CAPTION)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== "true"; }; // Moves the caret to a suitable position within the root for example in the first non pure whitespace text node or before an image function moveToCaretPosition(root) { var walker, node, rng, y, viewPort, lastNode = root, tempElm; rng = dom.createRng(); if (root.hasChildNodes()) { walker = new TreeWalker(root, root); while (node = walker.current()) { if (node.nodeType == 3) { rng.setStart(node, 0); rng.setEnd(node, 0); break; } if (/^(BR|IMG)$/.test(node.nodeName)) { rng.setStartBefore(node); rng.setEndBefore(node); break; } lastNode = node; node = walker.next(); } if (!node) { rng.setStart(lastNode, 0); rng.setEnd(lastNode, 0); } } else { if (root.nodeName == 'BR') { if (root.nextSibling && dom.isBlock(root.nextSibling)) { // Trick on older IE versions to render the caret before the BR between two lists if (!documentMode || documentMode < 9) { tempElm = dom.create('br'); root.parentNode.insertBefore(tempElm, root); } rng.setStartBefore(root); rng.setEndBefore(root); } else { rng.setStartAfter(root); rng.setEndAfter(root); } } else { rng.setStart(root, 0); rng.setEnd(root, 0); } } selection.setRng(rng); // Remove tempElm created for old IE:s dom.remove(tempElm); viewPort = dom.getViewPort(editor.getWin()); // scrollIntoView seems to scroll the parent window in most browsers now including FF 3.0b4 so it's time to stop using it and do it our selfs y = dom.getPos(root).y; if (y < viewPort.y || y + 25 > viewPort.y + viewPort.h) { editor.getWin().scrollTo(0, y < viewPort.y ? y : y - viewPort.h + 25); // Needs to be hardcoded to roughly one line of text if a huge text block is broken into two blocks } }; // Creates a new block element by cloning the current one or creating a new one if the name is specified // This function will also copy any text formatting from the parent block and add it to the new one function createNewBlock(name) { var node = container, block, clonedNode, caretNode; block = name || parentBlockName == "TABLE" ? dom.create(name || newBlockName) : parentBlock.cloneNode(false); caretNode = block; // Clone any parent styles if (settings.keep_styles !== false) { do { if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U)$/.test(node.nodeName)) { clonedNode = node.cloneNode(false); dom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique if (block.hasChildNodes()) { clonedNode.appendChild(block.firstChild); block.appendChild(clonedNode); } else { caretNode = clonedNode; block.appendChild(clonedNode); } } } while (node = node.parentNode); } // BR is needed in empty blocks on non IE browsers if (!tinymce.isIE) { caretNode.innerHTML = '<br>'; } return block; }; // Returns true/false if the caret is at the start/end of the parent block element function isCaretAtStartOrEndOfBlock(start) { var walker, node, name; // Caret is in the middle of a text node like "a|b" if (container.nodeType == 3 && (start ? offset > 0 : offset < container.nodeValue.length)) { return false; } // If after the last element in block node edge case for #5091 if (container.parentNode == parentBlock && isAfterLastNodeInContainer && !start) { return true; } // Caret can be before/after a table if (container.nodeName === "TABLE" || (container.previousSibling && container.previousSibling.nodeName == "TABLE")) { return (isAfterLastNodeInContainer && !start) || (!isAfterLastNodeInContainer && start); } // Walk the DOM and look for text nodes or non empty elements walker = new TreeWalker(container, parentBlock); while (node = (start ? walker.prev() : walker.next())) { if (node.nodeType === 1) { // Ignore bogus elements if (node.getAttribute('data-mce-bogus')) { continue; } // Keep empty elements like <img /> name = node.nodeName.toLowerCase(); if (name === 'IMG') { return false; } } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) { return false; } } return true; }; // Wraps any text nodes or inline elements in the specified forced root block name function wrapSelfAndSiblingsInDefaultBlock(container, offset) { var newBlock, parentBlock, startNode, node, next, blockName = newBlockName || 'P'; // Not in a block element or in a table cell or caption parentBlock = dom.getParent(container, dom.isBlock); if (!parentBlock || !canSplitBlock(parentBlock)) { parentBlock = parentBlock || editableRoot; if (!parentBlock.hasChildNodes()) { newBlock = dom.create(blockName); parentBlock.appendChild(newBlock); rng.setStart(newBlock, 0); rng.setEnd(newBlock, 0); return newBlock; } // Find parent that is the first child of parentBlock node = container; while (node.parentNode != parentBlock) { node = node.parentNode; } // Loop left to find start node start wrapping at while (node && !dom.isBlock(node)) { startNode = node; node = node.previousSibling; } if (startNode) { newBlock = dom.create(blockName); startNode.parentNode.insertBefore(newBlock, startNode); // Start wrapping until we hit a block node = startNode; while (node && !dom.isBlock(node)) { next = node.nextSibling; newBlock.appendChild(node); node = next; } // Restore range to it's past location rng.setStart(container, offset); rng.setEnd(container, offset); } } return container; }; // Inserts a block or br before/after or in the middle of a split list of the LI is empty function handleEmptyListItem() { function isFirstOrLastLi(first) { var node = containerBlock[first ? 'firstChild' : 'lastChild']; // Find first/last element since there might be whitespace there while (node) { if (node.nodeType == 1) { break; } node = node[first ? 'nextSibling' : 'previousSibling']; } return node === parentBlock; }; newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR'); if (isFirstOrLastLi(true) && isFirstOrLastLi()) { // Is first and last list item then replace the OL/UL with a text block dom.replace(newBlock, containerBlock); } else if (isFirstOrLastLi(true)) { // First LI in list then remove LI and add text block before list containerBlock.parentNode.insertBefore(newBlock, containerBlock); } else if (isFirstOrLastLi()) { // Last LI in list then temove LI and add text block after list dom.insertAfter(newBlock, containerBlock); } else { // Middle LI in list the split the list and insert a text block in the middle // Extract after fragment and insert it after the current block tmpRng = rng.cloneRange(); tmpRng.setStartAfter(parentBlock); tmpRng.setEndAfter(containerBlock); fragment = tmpRng.extractContents(); dom.insertAfter(fragment, containerBlock); dom.insertAfter(newBlock, containerBlock); } dom.remove(parentBlock); moveToCaretPosition(newBlock); undoManager.add(); }; // Walks the parent block to the right and look for BR elements function hasRightSideBr() { var walker = new TreeWalker(container, parentBlock), node; while (node = walker.current()) { if (node.nodeName == 'BR') { return true; } node = walker.next(); } } // Inserts a BR element if the forced_root_block option is set to false or empty string function insertBr() { var brElm, extraBr; if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { // Insert extra BR element at the end block elements if (!tinymce.isIE && !hasRightSideBr()) { brElm = dom.create('br') rng.insertNode(brElm); rng.setStartAfter(brElm); rng.setEndAfter(brElm); extraBr = true; } } brElm = dom.create('br'); rng.insertNode(brElm); // Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it if (tinymce.isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); } if (!extraBr) { rng.setStartAfter(brElm); rng.setEndAfter(brElm); } else { rng.setStartBefore(brElm); rng.setEndBefore(brElm); } selection.setRng(rng); undoManager.add(); }; // Trims any linebreaks at the beginning of node user for example when pressing enter in a PRE element function trimLeadingLineBreaks(node) { do { if (node.nodeType === 3) { node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, ''); } node = node.firstChild; } while (node); }; function getEditableRoot(node) { var root = dom.getRoot(), parent, editableRoot; // Get all parents until we hit a non editable parent or the root parent = node; while (parent !== root && dom.getContentEditable(parent) !== "false") { if (dom.getContentEditable(parent) === "true") { editableRoot = parent; } parent = parent.parentNode; } return parent !== root ? editableRoot : root; }; // Delete any selected contents if (!rng.collapsed) { editor.execCommand('Delete'); return; } // Event is blocked by some other handler for example the lists plugin if (evt.isDefaultPrevented()) { return; } // Setup range items and newBlockName container = rng.startContainer; offset = rng.startOffset; newBlockName = settings.forced_root_block; newBlockName = newBlockName ? newBlockName.toUpperCase() : ''; documentMode = dom.doc.documentMode; // Resolve node index if (container.nodeType == 1 && container.hasChildNodes()) { isAfterLastNodeInContainer = offset > container.childNodes.length - 1; container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; offset = 0; } // Get editable root node normaly the body element but sometimes a div or span editableRoot = getEditableRoot(container); // If there is no editable root then enter is done inside a contentEditable false element if (!editableRoot) { return; } undoManager.beforeChange(); // If editable root isn't block nor the root of the editor if (!dom.isBlock(editableRoot) && editableRoot != dom.getRoot()) { if (!newBlockName || evt.shiftKey) { insertBr(); } return; } // Wrap the current node and it's sibling in a default block if it's needed. // for example this <td>text|<b>text2</b></td> will become this <td><p>text|<b>text2</p></b></td> // This won't happen if root blocks are disabled or the shiftKey is pressed if ((newBlockName && !evt.shiftKey) || (!newBlockName && evt.shiftKey)) { container = wrapSelfAndSiblingsInDefaultBlock(container, offset); } // Find parent block and setup empty block paddings parentBlock = dom.getParent(container, dom.isBlock); containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null; // Setup block names parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 // Handle enter inside an empty list item if (parentBlockName == 'LI' && dom.isEmpty(parentBlock)) { // Let the list plugin or browser handle nested lists for now if (/^(UL|OL|LI)$/.test(containerBlock.parentNode.nodeName)) { return false; } handleEmptyListItem(); return; } // Don't split PRE tags but insert a BR instead easier when writing code samples etc if (parentBlockName == 'PRE' && settings.br_in_pre !== false) { if (!evt.shiftKey) { insertBr(); return; } } else { // If no root block is configured then insert a BR by default or if the shiftKey is pressed if ((!newBlockName && !evt.shiftKey && parentBlockName != 'LI') || (newBlockName && evt.shiftKey)) { insertBr(); return; } } // Default block name if it's not configured newBlockName = newBlockName || 'P'; // Insert new block before/after the parent block depending on caret location if (isCaretAtStartOrEndOfBlock()) { // If the caret is at the end of a header we produce a P tag after it similar to Word unless we are in a hgroup if (/^(H[1-6]|PRE)$/.test(parentBlockName) && containerBlockName != 'HGROUP') { newBlock = createNewBlock(newBlockName); } else { newBlock = createNewBlock(); } // Split the current container block element if enter is pressed inside an empty inner block element if (settings.end_container_on_empty_block && canSplitBlock(containerBlock) && dom.isEmpty(parentBlock)) { // Split container block for example a BLOCKQUOTE at the current blockParent location for example a P newBlock = dom.split(containerBlock, parentBlock); } else { dom.insertAfter(newBlock, parentBlock); } } else if (isCaretAtStartOrEndOfBlock(true)) { // Insert new block before newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock); } else { // Extract after fragment and insert it after the current block tmpRng = rng.cloneRange(); tmpRng.setEndAfter(parentBlock); fragment = tmpRng.extractContents(); trimLeadingLineBreaks(fragment); newBlock = fragment.firstChild; dom.insertAfter(fragment, parentBlock); } dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique moveToCaretPosition(newBlock); undoManager.add(); } editor.onKeyDown.add(function(ed, evt) { if (evt.keyCode == 13) { if (handleEnterKey(evt) !== false) { evt.preventDefault(); } } }); }; })(tinymce);
dirCheck
11.311b914b.chunk.js
(this["webpackJsonppancake-frontend"]=this["webpackJsonppancake-frontend"]||[]).push([[11],{1158:function(e,t,n){"use strict";n.r(t);var c,o,r,i,a,s,l,u,b,j,d,m,f,O,p,x=n(0),h=n(24),g=n(53),v=n(98),y=n(5),I=n(172),w=n(28),k=n(11),P=n(2),A=k.e.div(c||(c=Object(w.a)(["\n background: ",";\n padding-bottom: 40px;\n padding-top: 40px;\n"])),(function(e){var t=e.theme;return t.isDark?"repeating-linear-gradient(to right, #332453, #332453 40px, #281D44 40px, #281D44 80px)":"repeating-linear-gradient(to right, #21d4e2, #21d4e2 40px, #53dee9 40px, #53dee9 80px)"})),C=k.e.div(o||(o=Object(w.a)(["\n background-image: url('/images/curtain-bottom-",".png');\n background-repeat: repeat-x;\n background-size: contain;\n height: 20px;\n"])),(function(e){return e.theme.isDark?"dark":"light"})),S=function(){var e=Object(h.b)().t;return Object(P.jsxs)(y.m,{mb:"32px",children:[Object(P.jsx)(A,{children:Object(P.jsxs)(I.a,{children:[Object(P.jsx)(y.S,{as:"h1",scale:"xl",mb:"24px",children:e("IFO: Initial Farm Offerings")}),Object(P.jsx)(y.Ob,{bold:!0,fontSize:"20px",children:e("Buy new tokens with a brand new token sale model.")})]})}),Object(P.jsx)(C,{})]})},L=n(147),T=n(3),D=n.n(T),B=n(12),R=n(10),U=n(21),E=n(16),F=n.n(E),N=n(50),q=n(37),_=n(15),G=n(143),W=n(100),Y=n(34),z=function(e,t,n){return 0===e?"idle":e<t?"coming_soon":e>=t&&e<=n?"live":e>n?"finished":"idle"},K=function(e){return{raisingAmountPool:new F.a(e[0]),offeringAmountPool:new F.a(e[1]),limitPerUserInLP:new F.a(e[2]),hasTax:e[3],totalAmountPool:new F.a(e[4]),sumTaxesOverflow:new F.a(e[5])}},V=function(e){var t=e.address,n=e.releaseBlockNumber,c=Object(q.D)(e.currency.symbol),o=Object(G.a)().fastRefresh,r=Object(x.useState)({status:"idle",blocksRemaining:0,secondsUntilStart:0,progress:5,secondsUntilEnd:0,poolBasic:{raisingAmountPool:Y.c,offeringAmountPool:Y.c,limitPerUserInLP:Y.c,taxRate:0,totalAmountPool:Y.c,sumTaxesOverflow:Y.c},poolUnlimited:{raisingAmountPool:Y.c,offeringAmountPool:Y.c,limitPerUserInLP:Y.c,taxRate:0,totalAmountPool:Y.c,sumTaxesOverflow:Y.c},startBlockNum:0,endBlockNum:0,numberPoints:0}),i=Object(U.a)(r,2),a=i[0],s=i[1],l=Object(q.c)().currentBlock,u=Object(_.G)(t),b=Object(x.useCallback)(Object(R.a)(D.a.mark((function e(){var t,c,o,r,i,a,b,j,d,m,f,O,p,x,h,g;return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Object(W.a)([u.methods.startBlock().call,u.methods.endBlock().call,u.methods.viewPoolInformation(0).call,u.methods.viewPoolInformation(1).call,u.methods.viewPoolTaxRateOverflow(1).call,u.methods.numberPoints().call]);case 2:t=e.sent,c=Object(U.a)(t,6),o=c[0],r=c[1],i=c[2],a=c[3],b=c[4],j=c[5],d=K(i),m=K(a),f=parseInt(o,10),O=parseInt(r,10),p=z(l,f,O),x=O-f,h=O-l,g=l>f?(l-f)/x*100:(l-n)/(f-n)*100,s((function(e){return Object(B.a)(Object(B.a)({},e),{},{secondsUntilEnd:h*N.e,secondsUntilStart:(f-l)*N.e,poolBasic:Object(B.a)(Object(B.a)({},d),{},{taxRate:0}),poolUnlimited:Object(B.a)(Object(B.a)({},m),{},{taxRate:b/1e10}),status:p,progress:g,blocksRemaining:h,startBlockNum:f,endBlockNum:O,numberPoints:j})}));case 19:case"end":return e.stop()}}),e)}))),[u,l,n]);return Object(x.useEffect)((function(){b()}),[b,o]),Object(B.a)(Object(B.a)({},a),{},{currencyPriceInUSD:c,fetchIfoData:b})},Q=n(36),H=n(17),M=n(911),J=n(18),$=function(e){var t=Object(G.a)().fastRefresh,n=Object(x.useState)({poolBasic:{amountTokenCommittedInLP:Y.c,offeringAmountInToken:Y.c,refundingAmountInLP:Y.c,taxAmountInLP:Y.c,hasClaimed:!1,isPendingTx:!1},poolUnlimited:{amountTokenCommittedInLP:Y.c,offeringAmountInToken:Y.c,refundingAmountInLP:Y.c,taxAmountInLP:Y.c,hasClaimed:!1,isPendingTx:!1}}),c=Object(U.a)(n,2),o=c[0],r=c[1],i=e.address,a=e.currency,s=Object(H.c)().account,l=Object(_.G)(i),u=Object(_.o)(Object(J.a)(a.address)),b=Object(M.a)(u,i),j=Object(x.useCallback)(Object(R.a)(D.a.mark((function e(){var t,n,c,o;return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Object(W.a)([l.methods.viewUserInfo(s,[0,1]).call,l.methods.viewUserOfferingAndRefundingAmountsForPools(s,[0,1]).call]);case 2:t=e.sent,n=Object(U.a)(t,2),c=n[0],o=n[1],r((function(e){return Object(B.a)(Object(B.a)({},e),{},{poolBasic:Object(B.a)(Object(B.a)({},e.poolBasic),{},{amountTokenCommittedInLP:new F.a(c[0][0]),offeringAmountInToken:new F.a(o[0][0]),refundingAmountInLP:new F.a(o[0][1]),taxAmountInLP:new F.a(o[0][2]),hasClaimed:c[1][0]}),poolUnlimited:Object(B.a)(Object(B.a)({},e.poolUnlimited),{},{amountTokenCommittedInLP:new F.a(c[0][1]),offeringAmountInToken:new F.a(o[1][0]),refundingAmountInLP:new F.a(o[1][1]),taxAmountInLP:new F.a(o[1][2]),hasClaimed:c[1][1]})})}));case 7:case"end":return e.stop()}}),e)}))),[s,l]);return Object(x.useEffect)((function(){s&&j()}),[s,j,t]),Object(B.a)(Object(B.a)({},o),{},{allowance:b,contract:l,setPendingTx:function(e,t){return r((function(n){return Object(B.a)(Object(B.a)({},n),{},Object(Q.a)({},t,Object(B.a)(Object(B.a)({},n[t]),{},{isPendingTx:e})))}))},setIsClaimed:function(e){r((function(t){return Object(B.a)(Object(B.a)({},t),{},Object(Q.a)({},e,Object(B.a)(Object(B.a)({},t[e]),{},{hasClaimed:!0})))}))},fetchIfoData:j})},X=n(19),Z=n(102),ee=n(33),te=function(e){var t=e.userAmount,n=e.totalAmount,c=Object(Z.a)(e,["userAmount","totalAmount"]),o=Object(h.b)().t,r=(n.isGreaterThan(0)?t.div(n).times(100).toNumber():Y.c).toLocaleString(void 0,{maximumFractionDigits:5});return Object(P.jsx)(y.Ob,Object(B.a)(Object(B.a)({fontSize:"14px",color:"textSubtle"},c),{},{children:o("%num% of total",{num:r})}))},ne=function(){return Object(P.jsx)(y.Fb,{height:"48px"})},ce=function(){return Object(P.jsxs)("div",{children:[Object(P.jsxs)(y.R,{justifyContent:"space-between",alignItems:"center",mb:"24px",children:[Object(P.jsx)(y.Fb,{variant:"circle",width:"32px",height:"32px",mr:"16px"}),Object(P.jsx)(y.Fb,{width:"90%"})]}),Object(P.jsxs)(y.R,{justifyContent:"space-between",alignItems:"center",children:[Object(P.jsx)(y.Fb,{variant:"circle",width:"32px",height:"32px",mr:"16px"}),Object(P.jsx)(y.Fb,{width:"90%"})]})]})},oe=function(){return Object(P.jsxs)("div",{children:[Object(P.jsx)(y.Fb,{mb:"8px"}),Object(P.jsx)(y.Fb,{})]})},re=function(e){var t=e.img,n=e.children,c=Object(Z.a)(e,["img","children"]);return Object(P.jsxs)(y.R,Object(B.a)(Object(B.a)({},c),{},{children:[Object(P.jsx)(y.W,{src:t,width:32,height:32,mr:"16px"}),Object(P.jsx)("div",{children:n})]}))},ie=function(e){return Object(P.jsx)(y.Ob,Object(B.a)({bold:!0,fontSize:"12px",color:"secondary",textTransform:"uppercase"},e))},ae=function(e){return Object(P.jsx)(y.Ob,Object(B.a)({bold:!0,fontSize:"20px",style:{wordBreak:"break-all"}},e))},se=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=e.walletIfoData,r=e.hasProfile,i=e.isLoading,a=Object(H.c)().account,s=Object(h.b)().t,l=Object(y.kc)(s("Sorry, you didn\u2019t contribute enough LP tokens to meet the minimum threshold. You didn\u2019t buy anything in this sale, but you can still reclaim your LP tokens."),{placement:"bottom"}),u=l.targetRef,b=l.tooltip,j=l.tooltipVisible,d=c[t],m=o[t],f=n.currency,O=n.token,p=m.hasClaimed,x=100*n[t].distributionRatio,g="/images/tokens/".concat(n.token.symbol.toLowerCase(),".png");return Object(P.jsxs)(y.m,{pb:"24px",children:[j&&b,i?Object(P.jsx)(ce,{}):a&&!r?Object(P.jsx)(y.Ob,{textAlign:"center",children:s("You need an active PancakeSwap Profile to take part in an IFO!")}):"coming_soon"===c.status?Object(P.jsxs)(P.Fragment,{children:[Object(P.jsxs)(re,{img:"/images/bunny-placeholder.svg",children:[Object(P.jsx)(ie,{children:s("On sale")}),Object(P.jsx)(ae,{children:n[t].saleAmount})]}),Object(P.jsx)(y.Ob,{fontSize:"14px",color:"textSubtle",pl:"48px",children:s("%ratio%% of total sale",{ratio:x})})]}):"live"===c.status?Object(P.jsxs)(P.Fragment,{children:[Object(P.jsxs)(re,{img:"/images/farms/cake-bnb.svg",mb:"24px",children:[Object(P.jsx)(ie,{children:s("Your %symbol% committed",{symbol:f.symbol})}),Object(P.jsx)(ae,{children:Object(ee.c)(m.amountTokenCommittedInLP,f.decimals)}),Object(P.jsx)(te,{userAmount:m.amountTokenCommittedInLP,totalAmount:d.totalAmountPool})]}),Object(P.jsxs)(re,{img:g,children:[Object(P.jsx)(ie,{children:s("%symbol% to receive",{symbol:O.symbol})}),Object(P.jsx)(ae,{children:Object(ee.c)(m.offeringAmountInToken,O.decimals)})]})]}):"finished"===c.status?m.amountTokenCommittedInLP.isEqualTo(0)?Object(P.jsxs)(y.R,{flexDirection:"column",alignItems:"center",children:[Object(P.jsx)(y.W,{src:"/images/bunny-placeholder.svg",width:80,height:80,mb:"16px"}),Object(P.jsx)(y.Ob,{children:s("You didn\u2019t participate in this sale!")})]}):Object(P.jsxs)(P.Fragment,{children:[Object(P.jsxs)(re,{img:"/images/farms/cake-bnb.svg",mb:"24px",children:[Object(P.jsx)(ie,{children:s(p?"Your %symbol% RECLAIMED":"Your %symbol% TO RECLAIM",{symbol:f.symbol})}),Object(P.jsxs)(y.R,{alignItems:"center",children:[Object(P.jsx)(ae,{children:Object(ee.c)(m.refundingAmountInLP,f.decimals)}),p&&Object(P.jsx)(y.D,{color:"success",ml:"8px"})]}),Object(P.jsx)(te,{userAmount:m.amountTokenCommittedInLP,totalAmount:d.totalAmountPool})]}),Object(P.jsxs)(re,{img:g,children:[Object(P.jsxs)(ie,{children:[" ",s(p?"%symbol% received":"%symbol% to receive",{symbol:O.symbol})]}),Object(P.jsxs)(y.R,{alignItems:"center",children:[Object(P.jsx)(ae,{children:Object(ee.c)(m.offeringAmountInToken,O.decimals)}),!p&&m.offeringAmountInToken.isEqualTo(0)&&Object(P.jsx)("div",{ref:u,style:{display:"flex",marginLeft:"8px"},children:Object(P.jsx)(y.T,{})}),p&&Object(P.jsx)(y.D,{color:"success",ml:"8px"})]})]})]}):null]})},le=n(125),ue=n(880),be=n(69),je=n(111),de=n(904),me=n(905),fe=[.1,.25,.5,.75,1],Oe=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=e.walletIfoData,r=e.userCurrencyBalance,i=e.onDismiss,a=e.onSuccess,s=c[t],l=o[t],u=n.currency,b=s.limitPerUserInLP,j=l.amountTokenCommittedInLP,d=o.contract,m=Object(x.useState)(""),f=Object(U.a)(m,2),O=f[0],p=f[1],g=Object(H.c)().account,v=Object(_.o)(Object(J.a)(u.address)),I=Object(h.b)().t,w=new F.a(O).times(N.g),k=Y.b.times(Y.b.pow(Y.a)).toString(),A=Object(me.a)({onRequiresApproval:function(){var e=Object(R.a)(D.a.mark((function e(){var t,n;return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,v.methods.allowance(g,d.options.address).call();case 3:return t=e.sent,n=new F.a(t),e.abrupt("return",n.gt(0));case 8:return e.prev=8,e.t0=e.catch(0),e.abrupt("return",!1);case 11:case"end":return e.stop()}}),e,null,[[0,8]])})));return function(){return e.apply(this,arguments)}}(),onApprove:function(){return v.methods.approve(d.options.address,je.a.constants.MaxUint256).send({from:g,gasPrice:k})},onConfirm:function(){return d.methods.depositPool(w.toString(),t===X.c.poolBasic?0:1).send({from:g,gasPrice:k})},onSuccess:function(){var e=Object(R.a)(D.a.mark((function e(){return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,a(w);case 2:i();case 3:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()}),C=A.isApproving,S=A.isApproved,L=A.isConfirmed,T=A.isConfirming,B=A.handleApprove,E=A.handleConfirm,q=b.isGreaterThan(0)&&b.minus(j).isLessThanOrEqualTo(r)?b:r;return Object(P.jsx)(y.nb,{title:I("Contribute %symbol%",{symbol:u.symbol}),onDismiss:i,children:Object(P.jsxs)(y.ob,{maxWidth:"320px",children:[b.isGreaterThan(0)&&Object(P.jsxs)(y.R,{justifyContent:"space-between",mb:"16px",children:[Object(P.jsx)(y.Ob,{children:I("Max. LP token entry")}),Object(P.jsx)(y.Ob,{children:Object(ee.c)(b,u.decimals)})]}),Object(P.jsxs)(y.R,{justifyContent:"space-between",mb:"8px",children:[Object(P.jsxs)(y.Ob,{children:[I("Commit"),":"]}),Object(P.jsxs)(y.R,{flexGrow:1,justifyContent:"flex-end",children:[Object(P.jsx)(y.W,{src:"/images/farms/".concat(u.symbol.split(" ")[0].toLocaleLowerCase(),".svg"),width:24,height:24}),Object(P.jsx)(y.Ob,{children:u.symbol})]})]}),Object(P.jsx)(y.h,{value:O,currencyValue:c.currencyPriceInUSD.times(O||0).toFixed(2),onUserInput:p,isWarning:w.isGreaterThan(q),mb:"8px"}),Object(P.jsx)(y.Ob,{color:"textSubtle",textAlign:"right",fontSize:"12px",mb:"16px",children:I("Balance: %balance%",{balance:Object(ee.a)(Object(ee.c)(r,u.decimals),2,5)})}),Object(P.jsx)(y.R,{justifyContent:"space-between",mb:"16px",children:fe.map((function(e,t){return Object(P.jsxs)(y.q,{scale:"xs",variant:"tertiary",onClick:function(){return p(Object(ee.c)(q.times(e)).toString())},mr:t<fe.length-1?"8px":0,children:[100*e,"%"]},e)}))}),Object(P.jsx)(y.Ob,{color:"textSubtle",fontSize:"12px",mb:"24px",children:I("If you don\u2019t commit enough LP tokens, you may not receive any IFO tokens at all and will only receive a full refund of your LP tokens.")}),Object(P.jsx)(de.a,{isApproveDisabled:L||T||S,isApproving:C,isConfirmDisabled:!S||L||w.isNaN()||w.eq(0),isConfirming:T,onApprove:B,onConfirm:E})]})})},pe=function(e){var t=e.currency,n=e.onDismiss,c=Object(h.b)().t;return Object(P.jsx)(y.nb,{title:c("LP Tokens required"),onDismiss:n,children:Object(P.jsxs)(y.ob,{maxWidth:"288px",children:[Object(P.jsx)(y.W,{src:"/images/farms/".concat(t.symbol.split(" ")[0].toLocaleLowerCase(),".svg"),width:72,height:72,margin:"auto",mb:"24px"}),Object(P.jsx)(y.Ob,{mb:"16px",children:c("You\u2019ll need CAKE-BNB LP tokens to participate in the IFO!")}),Object(P.jsx)(y.Ob,{mb:"24px",children:c("Get LP tokens, or make sure your tokens aren\u2019t staked somewhere else.")}),Object(P.jsx)(y.q,{as:y.bb,external:!0,href:"".concat(N.a,"/BNB/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82"),endIcon:Object(P.jsx)(y.wb,{color:"white"}),minWidth:"100%",children:c("Get LP tokens")})]})})},xe=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=e.walletIfoData,r=c[t],i=o[t],a=i.isPendingTx,s=i.amountTokenCommittedInLP,l=r.limitPerUserInLP,u=Object(h.b)().t,b=Object(be.a)().toastSuccess,j=Object(ue.b)(Object(J.a)(n.currency.address)),d=function(){var e=Object(R.a)(D.a.mark((function e(t){return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Promise.all([c.fetchIfoData(),o.fetchIfoData()]);case 2:b(u("Success!"),u("You have contributed %amount% CAKE-BNB LP tokens to this IFO!",{amount:Object(ee.c)(t)}));case 3:case"end":return e.stop()}}),e)})));return function(t){return e.apply(this,arguments)}}(),m=Object(y.ic)(Object(P.jsx)(Oe,{poolId:t,ifo:n,publicIfoData:c,walletIfoData:o,onSuccess:d,userCurrencyBalance:j}),!1),f=Object(U.a)(m,1)[0],O=Object(y.ic)(Object(P.jsx)(pe,{currency:n.currency}),!1),p=Object(U.a)(O,1)[0],x=a||l.isGreaterThan(0)&&s.isGreaterThanOrEqualTo(l);return Object(P.jsx)(y.q,{onClick:j.isEqualTo(0)?p:f,width:"100%",disabled:x,children:u(x?"Max. Committed":"Commit LP Tokens")})},he=function(e){var t=e.poolId,n=e.walletIfoData,c=n[t],o=Object(h.b)().t,r=Object(H.c)().account,i=Object(be.a)(),a=i.toastError,s=i.toastSuccess,l=function(e){return n.setPendingTx(e,t)},u=function(){var e=Object(R.a)(D.a.mark((function e(){return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,l(!0),e.next=4,n.contract.methods.harvestPool(t===X.c.poolBasic?0:1).send({from:r});case 4:n.setIsClaimed(t),s(o("Success!"),o("You have successfully claimed your rewards.")),e.next=12;break;case 8:e.prev=8,e.t0=e.catch(0),a(o("Error"),null===e.t0||void 0===e.t0?void 0:e.t0.message),console.error(e.t0);case 12:return e.prev=12,l(!1),e.finish(12);case 15:case"end":return e.stop()}}),e,null,[[0,8,12,15]])})));return function(){return e.apply(this,arguments)}}();return Object(P.jsx)(y.q,{onClick:u,disabled:c.isPendingTx,width:"100%",isLoading:c.isPendingTx,endIcon:c.isPendingTx?Object(P.jsx)(y.g,{spin:!0,color:"currentColor"}):null,children:o("Claim")})},ge=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=e.walletIfoData,r=e.hasProfile,i=e.isLoading,a=Object(h.b)().t,s=Object(H.c)().account,l=o[t];return i?Object(P.jsx)(ne,{}):s?r?Object(P.jsxs)(P.Fragment,{children:["live"===c.status&&Object(P.jsx)(xe,{poolId:t,ifo:n,publicIfoData:c,walletIfoData:o}),"finished"===c.status&&!l.hasClaimed&&(l.offeringAmountInToken.isGreaterThan(0)||l.refundingAmountInLP.isGreaterThan(0))&&Object(P.jsx)(he,{poolId:t,walletIfoData:o})]}):Object(P.jsx)(y.q,{as:v.a,to:"/profile",width:"100%",children:a("Activate your profile")}):Object(P.jsx)(le.a,{width:"100%"})},ve=function(e){var t=e.label,n=e.value;return Object(P.jsxs)(y.R,{justifyContent:"space-between",alignItems:"center",children:[Object(P.jsx)(y.Ob,{small:!0,color:"textSubtle",children:t}),Object(P.jsx)(y.Ob,{small:!0,textAlign:"right",children:n})]})},ye=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=Object(h.b)().t,r=c.status,i=c.currencyPriceInUSD,a=c[t],s=Object(ee.c)(a.limitPerUserInLP,n.currency.decimals),l="".concat(a.taxRate,"%"),u=a.totalAmountPool.div(a.raisingAmountPool).times(100).toFixed(2),b=Object(ee.c)(a.totalAmountPool,n.currency.decimals),j=i.times(b),d="~$".concat(Object(ee.a)(j.toNumber())," (").concat(u,"%)");return Object(P.jsx)(y.m,{paddingTop:"24px",children:"coming_soon"===r?Object(P.jsxs)(P.Fragment,{children:[t===X.c.poolBasic&&Object(P.jsx)(ve,{label:o("Max. LP token entry"),value:s}),Object(P.jsx)(ve,{label:o("Funds to raise:"),value:n[t].raiseAmount}),Object(P.jsx)(ve,{label:o("CAKE to burn:"),value:n[t].cakeToBurn}),Object(P.jsx)(ve,{label:o("Price per %symbol%:",{symbol:n.token.symbol}),value:"$".concat(n.tokenOfferingPrice)})]}):"live"===r?Object(P.jsxs)(P.Fragment,{children:[t===X.c.poolBasic&&Object(P.jsx)(ve,{label:o("Max. LP token entry"),value:s}),t===X.c.poolUnlimited&&Object(P.jsx)(ve,{label:o("Additional fee:"),value:l}),Object(P.jsx)(ve,{label:o("Total committed:"),value:d})]}):"finished"===r?Object(P.jsxs)(P.Fragment,{children:[t===X.c.poolBasic&&Object(P.jsx)(ve,{label:o("Max. LP token entry"),value:s}),t===X.c.poolUnlimited&&Object(P.jsx)(ve,{label:o("Additional fee:"),value:l}),Object(P.jsx)(ve,{label:o("Total committed:"),value:d}),Object(P.jsx)(ve,{label:o("Funds to raise:"),value:n[t].raiseAmount}),Object(P.jsx)(ve,{label:o("CAKE to burn:"),value:n[t].cakeToBurn}),Object(P.jsx)(ve,{label:o("Price per %symbol%:",{symbol:n.token.symbol}),value:"$".concat(n.tokenOfferingPrice?n.tokenOfferingPrice:"?")})]}):Object(P.jsx)(oe,{})})},Ie=(r={},Object(Q.a)(r,X.c.poolBasic,{title:"Basic Sale",variant:"blue",tooltip:"Every person can only commit a limited amount, but may expect a higher return per token committed."}),Object(Q.a)(r,X.c.poolUnlimited,{title:"Unlimited Sale",variant:"violet",tooltip:"No limits on the amount you can commit. Additional fee applies when claiming."}),r),we=function(e){var t=e.poolId,n=e.ifo,c=e.publicIfoData,o=e.walletIfoData,r=Object(h.b)().t,i=Ie[t],a=Object(q.H)(),s=a.hasProfile,l=a.isLoading,u=Object(y.kc)(r(i.tooltip),{placement:"bottom"}),b=u.targetRef,j=u.tooltip,d=u.tooltipVisible,m=l||"idle"===c.status;return Object(P.jsxs)(P.Fragment,{children:[d&&j,Object(P.jsxs)(y.u,{children:[Object(P.jsx)(y.x,{variant:i.variant,children:Object(P.jsxs)(y.R,{justifyContent:"space-between",alignItems:"center",children:[Object(P.jsx)(y.Ob,{bold:!0,fontSize:"20px",children:i.title}),Object(P.jsx)("div",{ref:b,children:Object(P.jsx)(y.T,{})})]})}),Object(P.jsxs)(y.v,{children:[Object(P.jsx)(se,{poolId:t,ifo:n,publicIfoData:c,walletIfoData:o,hasProfile:s,isLoading:m}),Object(P.jsx)(ge,{poolId:t,ifo:n,publicIfoData:c,walletIfoData:o,hasProfile:s,isLoading:m}),Object(P.jsx)(ye,{poolId:t,ifo:n,publicIfoData:c})]})]})]})},ke=n(281),Pe=function(e){var t=e.publicIfoData,n=Object(h.b)().t,c=t.status,o=t.secondsUntilStart,r=t.secondsUntilEnd,i=t.startBlockNum,a="coming_soon"===c?o:r,s=Object(ke.a)(a),l="coming_soon"===c?n("Start").toLowerCase():n("Finish").toLowerCase();return Object(P.jsx)(y.R,{justifyContent:"center",mb:"32px",children:"idle"===c?Object(P.jsx)(y.Fb,{animation:"pulse",variant:"rect",width:"100%",height:"48px"}):Object(P.jsxs)(P.Fragment,{children:[Object(P.jsx)(y.zb,{width:"48px",mr:"16px"}),Object(P.jsxs)(y.R,{alignItems:"center",children:[Object(P.jsxs)(y.Ob,{bold:!0,mr:"16px",children:[l,":"]}),Object(P.jsx)(y.Ob,{children:n("%day%d %hour%h %minute%m",{day:s.days,hour:s.hours,minute:s.minutes})}),Object(P.jsx)(y.bb,{href:"https://bscscan.com/block/countdown/".concat(i),target:"blank",rel:"noopener noreferrer",ml:"8px",children:"(blocks)"})]})]})})},Ae=Y.b,Ce=Object(k.e)(y.R)(i||(i=Object(w.a)(["\n justify-content: space-between;\n flex-direction: column;\n align-items: center;\n "," {\n flex-direction: row;\n align-items: initial;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),Se=Object(k.e)(y.cb)(a||(a=Object(w.a)(["\n margin-top: 32px;\n "," {\n margin-top: 0;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),Le=function(e){var t=e.ifo,n=e.publicIfoData,c=Object(h.b)().t,o=t.token.symbol.toLowerCase(),r=t.name,i=Ae.div(n.currencyPriceInUSD).toNumber();return Object(P.jsxs)(Ce,{children:[Object(P.jsxs)(y.R,{alignItems:"center",flexGrow:1,children:[Object(P.jsx)(y.W,{src:"/images/achievements/ifo-".concat(o,".svg"),width:56,height:56,mr:"8px"}),Object(P.jsxs)(y.R,{flexDirection:"column",children:[Object(P.jsx)(y.Ob,{color:"secondary",fontSize:"12px",children:"".concat(c("Achievement"),":")}),Object(P.jsxs)(y.R,{children:[Object(P.jsx)(y.Ob,{bold:!0,mr:"8px",children:c("IFO Shopper: %title%",{title:r})}),Object(P.jsxs)(y.R,{alignItems:"center",mr:"8px",children:[Object(P.jsx)(y.Ab,{color:"textSubtle",width:"16px",mr:"4px"}),Object(P.jsx)(y.Ob,{color:"textSubtle",children:n.numberPoints})]})]}),n.currencyPriceInUSD.gt(0)?Object(P.jsx)(y.Ob,{color:"textSubtle",fontSize:"12px",children:c("Commit ~%amount% LP in total to earn!",{amount:i.toFixed(3)})}):Object(P.jsx)(y.Fb,{minHeight:18,width:80})]})]}),Object(P.jsx)(Se,{href:t.articleUrl,children:c("Learn more about %title%",{title:r})})]})},Te=Object(k.e)(y.u)(s||(s=Object(w.a)(["\n max-width: 736px;\n width: 100%;\n margin: auto;\n"]))),De=Object(k.e)(y.x)(l||(l=Object(w.a)(["\n display: flex;\n justify-content: flex-end;\n align-items: center;\n height: 112px;\n background-repeat: no-repeat;\n background-size: cover;\n background-position: center;\n background-image: ",";\n"])),(function(e){var t=e.ifoId;return"url('/images/ifos/".concat(t,"-bg.svg')")})),Be=k.e.div(u||(u=Object(w.a)(["\n display: ",";\n background: ",";\n"])),(function(e){return e.isVisible?"block":"none"}),(function(e){var t=e.isActive,n=e.theme;return t?n.colors.gradients.bubblegum:n.colors.dropdown})),Re=k.e.div(b||(b=Object(w.a)(["\n display: grid;\n grid-gap: 32px;\n grid-template-columns: 1fr;\n margin-bottom: 32px;\n "," {\n grid-template-columns: ",";\n justify-items: ",";\n }\n"])),(function(e){return e.theme.mediaQueries.md}),(function(e){return e.singleCard?"1fr":"1fr 1fr"}),(function(e){return e.singleCard?"center":"unset"})),Ue=Object(k.e)(y.v)(j||(j=Object(w.a)(["\n padding: 24px 16px;\n "," {\n padding: 24px;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),Ee=Object(k.e)(y.w)(d||(d=Object(w.a)(["\n text-align: center;\n padding: 8px;\n background: ",";\n"])),(function(e){return e.theme.colors.backgroundAlt})),Fe=function(e){var t=e.ifo,n=e.publicIfoData,c=e.walletIfoData,o=e.isInitiallyVisible,r=Object(x.useState)(o),i=Object(U.a)(r,2),a=i[0],s=i[1],l=Object(h.b)().t,u=function(e,t){return"coming_soon"===e?Object(P.jsx)(y.y,{variantColor:"textDisabled",ribbonPosition:"left",text:t("Coming Soon")}):"live"===e?Object(P.jsx)(y.y,{variantColor:"primary",ribbonPosition:"left",style:{textTransform:"uppercase"},text:"".concat(t("Live"),"!")}):null}(n.status,l),b="finished"!==n.status&&t.isActive;return Object(P.jsxs)(Te,{ribbon:u,children:[Object(P.jsx)(De,{ifoId:t.id,children:Object(P.jsx)(y.O,{expanded:a,onClick:function(){return s((function(e){return!e}))}})}),Object(P.jsxs)(Be,{isVisible:a,isActive:"idle"!==n.status&&b,children:[b&&Object(P.jsx)(y.Bb,{variant:"flat",primaryStep:n.progress}),Object(P.jsxs)(Ue,{children:[b&&Object(P.jsx)(Pe,{publicIfoData:n}),Object(P.jsxs)(Re,{singleCard:!n.poolBasic||!c.poolBasic,children:[n.poolBasic&&c.poolBasic&&Object(P.jsx)(we,{poolId:X.c.poolBasic,ifo:t,publicIfoData:n,walletIfoData:c}),Object(P.jsx)(we,{poolId:X.c.poolUnlimited,ifo:t,publicIfoData:n,walletIfoData:c})]}),Object(P.jsx)(Le,{ifo:t,publicIfoData:n})]}),Object(P.jsx)(Ee,{children:Object(P.jsx)(y.q,{variant:"text",endIcon:Object(P.jsx)(y.I,{color:"primary"}),onClick:function(){return s(!1)},children:l("Close")})})]})]})},Ne=k.e.div(m||(m=Object(w.a)(["\n display: grid;\n grid-gap: 32px;\n padding: 40px 0;\n border-top: 2px solid ",";\n"])),(function(e){return e.theme.colors.textSubtle})),qe=n(974),_e=n.n(qe),Ge=Object(k.e)(I.a)(f||(f=Object(w.a)(["\n background: ",";\n margin-left: -16px;\n margin-right: -16px;\n padding-top: 48px;\n padding-bottom: 48px;\n\n "," {\n margin-left: -24px;\n margin-right: -24px;\n }\n"])),(function(e){return e.theme.colors.gradients.bubblegum}),(function(e){return e.theme.mediaQueries.sm})),We=function(e){var t=e.ifo,n=e.walletIfoData,c=n.poolBasic,o=n.poolUnlimited,r=Object(q.H)().hasProfile,i=Object(h.b)().t,a=[r,Object(ue.b)(Object(J.a)(t.currency.address)).isGreaterThan(0),c.amountTokenCommittedInLP.isGreaterThan(0)||o.amountTokenCommittedInLP.isGreaterThan(0),c.hasClaimed||o.hasClaimed],s=function(e){var t=0===e||_e()(a.slice(0,e),Boolean);return a[e]?t?"past":"future":t?"current":"future"},l=function(e){var t=a[e];switch(e){case 0:return Object(P.jsxs)(y.v,{children:[Object(P.jsx)(y.S,{as:"h4",color:"secondary",mb:"16px",children:i("Activate your Profile")}),Object(P.jsx)(y.Ob,{color:"textSubtle",small:!0,mb:"16px",children:i("You\u2019ll need an active PancakeSwap Profile to take part in an IFO!")}),t?Object(P.jsx)(y.Ob,{color:"success",bold:!0,children:i("Profile Active!")}):Object(P.jsx)(y.q,{as:y.bb,href:"/profile",children:i("Activate your profile")})]});case 1:return Object(P.jsxs)(y.v,{children:[Object(P.jsx)(y.S,{as:"h4",color:"secondary",mb:"16px",children:i("Get CAKE-BNB LP Tokens")}),Object(P.jsxs)(y.Ob,{color:"textSubtle",small:!0,children:[i("Stake CAKE and BNB in the liquidity pool to get LP tokens.")," ",Object(P.jsx)("br",{}),i("You\u2019ll spend them to buy IFO sale tokens.")]}),Object(P.jsx)(y.q,{as:y.bb,external:!0,href:"".concat(N.a,"/BNB/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82"),endIcon:Object(P.jsx)(y.wb,{color:"white"}),mt:"16px",children:i("Get LP tokens")})]});case 2:return Object(P.jsxs)(y.v,{children:[Object(P.jsx)(y.S,{as:"h4",color:"secondary",mb:"16px",children:i("Commit LP Tokens")}),Object(P.jsxs)(y.Ob,{color:"textSubtle",small:!0,children:[i("When the IFO sales are live, you can \u201ccommit\u201d your LP tokens to buy the tokens being sold.")," ",Object(P.jsx)("br",{}),i("We recommend committing to the Basic Sale first, but you can do both if you want.")]})]});case 3:return Object(P.jsxs)(y.v,{children:[Object(P.jsx)(y.S,{as:"h4",color:"secondary",mb:"16px",children:i("Claim your tokens and achievement")}),Object(P.jsx)(y.Ob,{color:"textSubtle",small:!0,children:i("After the IFO sales finish, you can claim any IFO tokens that you bought, and any unspent CAKE-BNB LP tokens will be returned to your wallet.")})]});default:return null}};return Object(P.jsxs)(Ge,{children:[Object(P.jsx)(y.S,{as:"h2",scale:"xl",color:"secondary",mb:"24px",textAlign:"center",children:i("How to Take Part")}),Object(P.jsx)(y.Ib,{children:a.map((function(e,t){return Object(P.jsx)(y.Hb,{index:t,status:s(t),children:Object(P.jsx)(y.u,{children:l(t)})},t)}))})]})},Ye=n(917),ze=[{title:"What\u2019s the difference between a Basic Sale and Unlimited Sale?",description:["In the Basic Sale, every user can commit a maximum of about 100 USD worth of CAKE-BNB LP Tokens. We calculate the maximum LP amount about 30 minutes before each IFO. The Basic Sale has no participation fee.","In the Unlimited Sale, there\u2019s no limit to the amount of CAKE-BNB LP Tokens you can commit. However, there\u2019s a fee for participation: see below."]},{title:"Which sale should I commit to? Can I do both?",description:["You can choose one or both at the same time! If you\u2019re only committing a small amount, we recommend the Basic Sale first. Just remember you need a PancakeSwap Profile in order to participate."]},{title:"How much is the participation fee?",description:["There\u2019s only a participation fee for the Unlimited Sale: there\u2019s no fee for the Basic Sale.","The fee will start at 1%.","The 1% participation fee decreases in cliffs, based on the percentage of overflow from the \u201cUnlimited\u201d portion of the sale."]},{title:"Where does the participation fee go?",description:["We burn it. The CAKE-BNB LP tokens from the participation fee will be decomposed, then we use the BNB portion to market buy the CAKE equivalent, then finally throw all of the CAKE into the weekly token burn."]},{title:"How can I get an achievement for participating in the IFO?",description:["You need to contribute a minimum of about 10 USD worth of CAKE-BNB LP Tokens to either sale.","You can contribute to one or both, it doesn\u2019t matter: only your overall contribution is counted for the achievement."]}],Ke=k.e.div(O||(O=Object(w.a)(["\n flex: none;\n order: 2;\n width: 224px;\n\n "," {\n order: 1;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),Ve=k.e.div(p||(p=Object(w.a)(["\n order: 1;\n margin-bottom: 40px;\n\n "," {\n order: 2;\n margin-bottom: 0;\n margin-left: 40px;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),Qe=function(){var e=Object(h.b)().t;return Object(P.jsxs)(y.R,{alignItems:["center",null,null,"start"],flexDirection:["column",null,null,"row"],children:[Object(P.jsx)(Ke,{children:Object(P.jsx)("img",{src:"/images/ifo-bunny.png",alt:"ifo bunny",width:"224px",height:"208px"})}),Object(P.jsx)(Ve,{children:Object(P.jsxs)(y.u,{children:[Object(P.jsx)(y.x,{children:Object(P.jsx)(y.S,{scale:"lg",color:"secondary",children:e("Details")})}),Object(P.jsx)(y.v,{children:ze.map((function(t,n,c){var o=t.title,r=t.description,i=c.length;return Object(P.jsx)(Ye.a,{id:o,mb:n+1===i?"":"24px",title:e(o),children:r.map((function(t){return Object(P.jsx)(y.Ob,{color:"textSubtle",as:"p",children:e(t)},t)}))},o)}))})]})})]})},He=L.b.find((function(e){return e.isActive})),Me=function(){var e=V(He),t=$(He);return Object(P.jsxs)(Ne,{children:[Object(P.jsx)(Fe,{ifo:He,publicIfoData:e,walletIfoData:t,isInitiallyVisible:!0}),Object(P.jsx)(We,{ifo:He,walletIfoData:t}),Object(P.jsx)(Qe,{})]})},Je=function(e){var t=e.ifo,n=e.isInitiallyVisible,c=V(t),o=$(t);return Object(P.jsx)(Fe,{ifo:t,publicIfoData:c,walletIfoData:o,isInitiallyVisible:n})},$e=function(e){var t=e.address,n=e.releaseBlockNumber,c=Object(q.D)(e.currency.symbol),o=Object(x.useState)(Object(Q.a)({status:"idle",blocksRemaining:0,secondsUntilStart:0,progress:5,secondsUntilEnd:0,startBlockNum:0,endBlockNum:0,numberPoints:null},X.c.poolUnlimited,{raisingAmountPool:Y.c,totalAmountPool:Y.c,offeringAmountPool:Y.c,limitPerUserInLP:Y.c,taxRate:0,sumTaxesOverflow:Y.c})),r=Object(U.a)(o,2),i=r[0],a=r[1],s=Object(q.c)().currentBlock,l=Object(_.F)(t),u=Object(x.useCallback)(Object(R.a)(D.a.mark((function e(){var t,c,o,r,i,u,b,j,d,m,f,O;return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Object(W.a)([l.methods.startBlock().call,l.methods.endBlock().call,l.methods.raisingAmount().call,l.methods.totalAmount().call]);case 2:t=e.sent,c=Object(U.a)(t,4),o=c[0],r=c[1],i=c[2],u=c[3],b=parseInt(o,10),j=parseInt(r,10),d=z(s,b,j),m=j-b,f=j-s,O=s>b?(s-b)/m*100:(s-n)/(b-n)*100,a((function(e){return Object(Q.a)({status:d,blocksRemaining:f,secondsUntilStart:(b-s)*N.e,progress:O,secondsUntilEnd:f*N.e,startBlockNum:b,endBlockNum:j,currencyPriceInUSD:null,numberPoints:null},X.c.poolUnlimited,Object(B.a)(Object(B.a)({},e.poolUnlimited),{},{raisingAmountPool:new F.a(i),totalAmountPool:new F.a(u)}))}));case 15:case"end":return e.stop()}}),e)}))),[l,s,n]);return Object(x.useEffect)((function(){u()}),[u]),Object(B.a)(Object(B.a)({},i),{},{currencyPriceInUSD:c,fetchIfoData:u})},Xe=function(e){var t=Object(x.useState)(Object(Q.a)({},X.c.poolUnlimited,{amountTokenCommittedInLP:Y.c,hasClaimed:!1,isPendingTx:!1,offeringAmountInToken:Y.c,refundingAmountInLP:Y.c,taxAmountInLP:Y.c})),n=Object(U.a)(t,2),c=n[0],o=n[1],r=e.address,i=e.currency,a=c.poolUnlimited,s=Object(H.c)().account,l=Object(_.F)(r),u=Object(_.o)(Object(J.a)(i.address)),b=Object(M.a)(u,r,a.isPendingTx),j=Object(x.useCallback)(Object(R.a)(D.a.mark((function e(){var t,n,c,r,i;return D.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,Object(W.a)([l.methods.getOfferingAmount(s).call,l.methods.userInfo(s).call,l.methods.getRefundingAmount(s).call]);case 2:t=e.sent,n=Object(U.a)(t,3),c=n[0],r=n[1],i=n[2],o((function(e){return Object(Q.a)({},X.c.poolUnlimited,Object(B.a)(Object(B.a)({},e.poolUnlimited),{},{amountTokenCommittedInLP:new F.a(r.amount),hasClaimed:r.claimed,offeringAmountInToken:new F.a(c),refundingAmountInLP:new F.a(i)}))}));case 8:case"end":return e.stop()}}),e)}))),[s,l]);return Object(x.useEffect)((function(){s&&j()}),[s,j]),Object(B.a)(Object(B.a)({},c),{},{allowance:b,contract:l,setPendingTx:function(e){return o((function(t){return Object(Q.a)({},X.c.poolUnlimited,Object(B.a)(Object(B.a)({},t.poolUnlimited),{},{isPendingTx:e}))}))},setIsClaimed:function(){o((function(e){return Object(Q.a)({},X.c.poolUnlimited,Object(B.a)(Object(B.a)({},e.poolUnlimited),{},{hasClaimed:!0}))}))},fetchIfoData:j})},Ze=function(e){var t=e.ifo,n=$e(t),c=Xe(t);return Object(P.jsx)(Fe,{ifo:t,publicIfoData:n,walletIfoData:c,isInitiallyVisible:!1})},et=L.b.filter((function(e){return!e.isActive})),tt=function(){return Object(P.jsx)(Ne,{children:et.map((function(e){return e.isV1?Object(P.jsx)(Ze,{ifo:e},e.id):Object(P.jsx)(Je,{ifo:e,isInitiallyVisible:!1},e.id)}))})};t.default=function(){var e=Object(h.b)().t,t=Object(g.i)(),n=t.path,c=t.url,o=t.isExact;return Object(P.jsxs)(P.Fragment,{children:[Object(P.jsx)(S,{}),Object(P.jsxs)(I.a,{children:[Object(P.jsx)(y.R,{justifyContent:"center",alignItems:"center",mb:"32px",children:Object(P.jsxs)(y.r,{activeIndex:o?0:1,scale:"sm",variant:"subtle",children:[Object(P.jsx)(y.s,{as:v.a,to:"".concat(c),children:e("Next IFO")}),Object(P.jsx)(y.s,{as:v.a,to:"".concat(c,"/history"),children:e("Past IFOs")})]})}),Object(P.jsx)(g.b,{exact:!0,path:"".concat(n),children:Object(P.jsx)(Me,{})}),Object(P.jsx)(g.b,{path:"".concat(n,"/history"),children:Object(P.jsx)(tt,{})})]})]})}},880:function(e,t,n){"use strict";n.d(t,"b",(function(){return O})),n.d(t,"a",(function(){return p}));var c=n(3),o=n.n(c),r=n(10),i=n(21),a=n(0),s=n(16),l=n.n(s),u=n(17),b=n(22),j=n(34),d=n(30),m=n(143),f=n(275),O=function(e){var t=Object(a.useState)(j.c),n=Object(i.a)(t,2),c=n[0],s=n[1],f=Object(u.c)().account,O=Object(d.a)(),p=Object(m.a)().fastRefresh;return Object(a.useEffect)((function(){f&&function(){var t=Object(r.a)(o.a.mark((function t(){var n,c;return o.a.wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return n=Object(b.a)(e,O),t.next=3,n.methods.balanceOf(f).call();case 3:c=t.sent,s(new l.a(c));case 5:case"end":return t.stop()}}),t)})));return function(){return t.apply(this,arguments)}}()()}),[f,e,O,p]),c},p=function(){var e=Object(a.useState)(j.c),t=Object(i.a)(e,2),n=t[0],c=t[1],s=Object(u.c)().account,b=Object(f.a)(),m=b.lastUpdated,O=b.setLastUpdated,p=Object(d.a)();return Object(a.useEffect)((function(){s&&function(){var e=Object(r.a)(o.a.mark((function e(){var t;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,p.eth.getBalance(s);case 2:t=e.sent,c(new l.a(t));case 4:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()()}),[s,p,m,c]),{balance:n,refresh:O}}},904:function(e,t,n){"use strict";var c,o,r,i,a=n(28),s=(n(0),n(11)),l=n(5),u=n(24),b=n(2),j=s.e.div(c||(c=Object(a.a)(["\n align-items: center;\n display: grid;\n grid-template-columns: 1fr;\n justify-content: center;\n\n "," {\n grid-template-columns: 1fr 24px 1fr;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),d=Object(s.e)(l.q)(o||(o=Object(a.a)(["\n width: 100%;\n\n "," {\n min-width: 160px;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),m={width:"24px",color:"textDisabled"},f=Object(s.e)(l.H).attrs(m)(r||(r=Object(a.a)(["\n display: none;\n\n "," {\n display: block;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),O=Object(s.e)(l.F).attrs(m)(i||(i=Object(a.a)(["\n display: block;\n\n "," {\n display: none;\n }\n"])),(function(e){return e.theme.mediaQueries.md})),p=Object(b.jsx)(l.g,{spin:!0,color:"currentColor"});t.a=function(e){var t=e.isApproveDisabled,n=e.isApproving,c=e.isConfirming,o=e.isConfirmDisabled,r=e.onApprove,i=e.onConfirm,a=Object(u.b)().t;return Object(b.jsxs)(j,{children:[Object(b.jsx)(l.m,{children:Object(b.jsx)(d,{disabled:t,onClick:r,endIcon:n?p:void 0,isLoading:n,children:a(n?"Approving":"Approve")})}),Object(b.jsxs)(l.R,{justifyContent:"center",children:[Object(b.jsx)(f,{}),Object(b.jsx)(O,{})]}),Object(b.jsx)(l.m,{children:Object(b.jsx)(d,{onClick:i,disabled:o,isLoading:c,endIcon:c?p:void 0,children:a(c?"Confirming":"Confirm")})})]})}},905:function(e,t,n){"use strict";var c=n(21),o=n(12),r=n(0),i=n(174),a=n(17),s=n(69),l=n(24),u={approvalState:"idle",approvalReceipt:null,approvalError:null,confirmState:"idle",confirmReceipt:null,confirmError:null},b=function(e,t){switch(t.type){case"requires_approval":return Object(o.a)(Object(o.a)({},e),{},{approvalState:"success"});case"approve_sending":return Object(o.a)(Object(o.a)({},e),{},{approvalState:"loading"});case"approve_receipt":return Object(o.a)(Object(o.a)({},e),{},{approvalState:"success",approvalReceipt:t.payload});case"approve_error":return Object(o.a)(Object(o.a)({},e),{},{approvalState:"fail",approvalError:t.payload});case"confirm_sending":return Object(o.a)(Object(o.a)({},e),{},{confirmState:"loading"});case"confirm_receipt":return Object(o.a)(Object(o.a)({},e),{},{confirmState:"success",confirmReceipt:t.payload});case"confirm_error":return Object(o.a)(Object(o.a)({},e),{},{confirmState:"fail",confirmError:t.payload});default:return e}};t.a=function(e){var t=e.onApprove,n=e.onConfirm,o=e.onRequiresApproval,j=e.onSuccess,d=void 0===j?i.noop:j,m=Object(l.b)().t,f=Object(a.c)().account,O=Object(r.useReducer)(b,u),p=Object(c.a)(O,2),x=p[0],h=p[1],g=Object(r.useRef)(o),v=Object(s.a)().toastError;return Object(r.useEffect)((function(){f&&g.current&&g.current().then((function(e){e&&h({type:"requires_approval"})}))}),[f,g,h]),{isApproving:"loading"===x.approvalState,isApproved:"success"===x.approvalState,isConfirming:"loading"===x.confirmState,isConfirmed:"success"===x.confirmState,approvalReceipt:x.approvalReceipt,approvalError:x.approvalError,confirmReceipt:x.confirmReceipt,confirmError:x.confirmError,handleApprove:function(){t().on("sending",(function(){h({type:"approve_sending"})})).on("receipt",(function(e){h({type:"approve_receipt",payload:e})})).on("error",(function(e){h({type:"approve_error",payload:e}),console.error("An error occurred approving transaction:",e),v(m("An error occurred approving transaction"))}))},handleConfirm:function(){n().on("sending",(function(){h({type:"confirm_sending"})})).on("receipt",(function(e){h({type:"confirm_receipt",payload:e}),d(x)})).on("error",(function(e){h({type:"confirm_error",payload:e}),console.error("An error occurred confirming transaction:",e),v(m("An error occurred confirming transaction"))}))}}}},911:function(e,t,n){"use strict";n.d(t,"b",(function(){return f})),n.d(t,"a",(function(){return O}));var c=n(3),o=n.n(c),r=n(10),i=n(21),a=n(0),s=n(16),l=n.n(s),u=n(17),b=n(18),j=n(34),d=n(15),m=n(143),f=function(){var e=Object(a.useState)(j.c),t=Object(i.a)(e,2),n=t[0],c=t[1],s=Object(u.c)().account,f=Object(d.g)(),O=Object(m.a)().fastRefresh;return Object(a.useEffect)((function(){s&&function(){var e=Object(r.a)(o.a.mark((function e(){var t;return o.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,f.methods.allowance(s,Object(b.W)()).call();case 2:t=e.sent,c(new l.a(t));case 4:case"end":return e.stop()}}),e)})));return function(){return e.apply(this,arguments)}}()()}),[s,f,O]),n},O=function(e,t,n){var c=Object(u.c)().account,s=Object(a.useState)(j.c),b=Object(i.a)(s,2),d=b[0],m=b[1];return Object(a.useEffect)((function(){c&&function(){var n=Object(r.a)(o.a.mark((function n(){var r;return o.a.wrap((function(n){for(;;)switch(n.prev=n.next){case 0:return n.prev=0,n.next=3,e.methods.allowance(c,t).call();case 3:r=n.sent,m(new l.a(r)),n.next=10;break;case 7:n.prev=7,n.t0=n.catch(0),console.error(n.t0);case 10:case"end":return n.stop()}}),n,null,[[0,7]])})));return function(){return n.apply(this,arguments)}}()()}),[c,t,e,n]),d}},917:function(e,t,n){"use strict";var c,o,r,i=n(12),a=n(21),s=n(102),l=n(28),u=n(0),b=n(11),j=n(5),d=n(24),m=n(2),f=Object(b.e)(j.R)(c||(c=Object(l.a)(["\n cursor: pointer;\n"]))),O=Object(b.e)(j.R)(o||(o=Object(l.a)(["\n button {\n align-items: center;\n justify-content: flex-start;\n }\n"]))),p=Object(b.e)(j.R)(r||(r=Object(l.a)(["\n overflow: hidden;\n height: ",";\n padding-bottom: ",";\n border-bottom: 1px solid ",";\n"])),(function(e){return e.isExpanded?"100%":"0px"}),(function(e){return e.isExpanded?"16px":"0px"}),(function(e){return e.theme.colors.inputSecondary}));t.a=function(e){var t=e.title,n=e.children,c=Object(s.a)(e,["title","children"]),o=Object(d.b)().t,r=Object(u.useState)(!1),l=Object(a.a)(r,2),b=l[0],x=l[1];return Object(m.jsxs)(f,Object(i.a)(Object(i.a)({},c),{},{flexDirection:"column",onClick:function(){return x(!b)},children:[Object(m.jsxs)(j.R,{justifyContent:"space-between",alignItems:"center",pb:"16px",children:[Object(m.jsx)(j.Ob,{fontWeight:"bold",children:t}),Object(m.jsx)(O,{children:Object(m.jsx)(j.P,{expanded:b,onClick:function(){return x(!b)},children:o(b?"Hide":"Details")})})]}),Object(m.jsx)(p,{isExpanded:b,flexDirection:"column",children:n})]}))}},974:function(e,t,n){var c=n(975),o=n(976),r=n(219),i=n(80),a=n(294);e.exports=function(e,t,n){var s=i(e)?c:o;return n&&a(e,t,n)&&(t=void 0),s(e,r(t,3))}},975:function(e,t){e.exports=function(e,t){for(var n=-1,c=null==e?0:e.length;++n<c;)if(!t(e[n],n,e))return!1;return!0}},976:function(e,t,n){var c=n(299);e.exports=function(e,t){var n=!0;return c(e,(function(e,c,o){return n=!!t(e,c,o)})),n}}}]); //# sourceMappingURL=11.311b914b.chunk.js.map
edit_message_caption.rs
use std::borrow::Cow; use types::*; use requests::*; /// Use this method to edit captions of messages sent by the bot. #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)] #[must_use = "requests do nothing unless sent"] pub struct EditMessageCaption<'s> { chat_id: ChatRef, message_id: MessageId, caption: Cow<'s, str>, #[serde(skip_serializing_if = "Option::is_none")] reply_markup: Option<ReplyMarkup>, } impl<'s> Request for EditMessageCaption<'s> { type Response = IdResponse<Message>; fn name(&self) -> &'static str { "editMessageCaption" } } impl<'s> EditMessageCaption<'s> { pub fn new<C, M, T>(chat: C, message_id: M, caption: T) -> Self where C: ToChatRef, M: ToMessageId, T: Into<Cow<'s, str>>, { EditMessageCaption { chat_id: chat.to_chat_ref(), message_id: message_id.to_message_id(), caption: caption.into(), reply_markup: None, } } pub fn reply_markup<R>(&mut self, reply_markup: R) -> &mut Self where R: Into<ReplyMarkup>, { // TODO(knsd): nice builder? self.reply_markup = Some(reply_markup.into()); self } } /// Edit captions of messages sent by the bot. pub trait CanEditMessageCaption { fn edit_caption<'s, T>(&self, caption: T) -> EditMessageCaption<'s> where T: Into<Cow<'s, str>>; } impl<M> CanEditMessageCaption for M where M: ToMessageId + ToSourceChat, { fn edit_caption<'s, T>(&self, caption: T) -> EditMessageCaption<'s> where T: Into<Cow<'s, str>>,
}
{ EditMessageCaption::new(self.to_source_chat(), self.to_message_id(), caption) }
lib.rs
// Copyright 2019, 2020 Wingchain // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Service to make chain, txpool, consensus, api work together //! //! Architecture: //! //! +------------------------------------------------------------+ //! | Service | //! +------------------------------------------------------------+ //! +------------------------------------------------------------+ //! | API | //! +------------------------------------------------------------+ //! +---------------------------+ +-----------------------------+ //! | Consensus | | Coordinator | //! +---------------------------+ +-----------------------------+ //! +---------------------------+ +-----------------------------+ //! | TxPool | | Network | //! +---------------------------+ +-----------------------------+ //! +------------------------------------------------------------+ //! | Chain | //! +------------------------------------------------------------+ //! +------------------------------------------------------------+ //! | Executor | //! +------------------------------------------------------------+ //! +------------------------------------------------------------+ //! | StateDB | //! +------------------------------------------------------------+ //! +------------------------------------------------------------+ //! | DB | //! +------------------------------------------------------------+ //! +------------------------------------------------------------+ //! | Crypto | //! +------------------------------------------------------------+ use std::path::PathBuf; use std::sync::Arc; use tokio::runtime::Runtime; use tokio::time::Duration; use node_api::support::DefaultApiSupport; use node_api::Api; use node_chain::Chain; use node_consensus::Consensus; use node_consensus_base::support::DefaultConsensusSupport; use node_coordinator::support::DefaultCoordinatorSupport; use node_coordinator::Coordinator; use node_txpool::support::DefaultTxPoolSupport; use node_txpool::TxPool; use primitives::errors::CommonResult; use crate::config::{get_chain_config, get_file_config, get_other_config}; use crate::errors::ErrorKind; mod config; pub mod errors; pub struct ServiceConfig { /// Home path pub home: PathBuf, /// Agent version pub agent_version: String, } pub struct Service { #[allow(dead_code)] config: ServiceConfig, #[allow(dead_code)] chain: Arc<Chain>, #[allow(dead_code)] txpool: Arc<TxPool<DefaultTxPoolSupport>>, #[allow(dead_code)] api: Arc<Api<DefaultApiSupport>>, #[allow(dead_code)] consensus: Arc<Consensus<DefaultConsensusSupport>>, #[allow(dead_code)] coordinator: Arc<Coordinator<DefaultCoordinatorSupport>>, } impl Service { pub fn new(config: ServiceConfig) -> CommonResult<Self> { let file_config = get_file_config(&config.home)?; // init chain let chain_config = get_chain_config(&file_config, &config)?; let chain = Arc::new(Chain::new(chain_config)?); let other_config = get_other_config(&file_config, &config, chain.get_basic())?; // init txpool let txpool_support = Arc::new(DefaultTxPoolSupport::new(chain.clone())); let txpool = Arc::new(TxPool::new(other_config.txpool, txpool_support)?); // init consensus poa let consensus_support = Arc::new(DefaultConsensusSupport::new(chain.clone(), txpool.clone())); let consensus = Arc::new(Consensus::new(other_config.consensus, consensus_support)?); // init coordinator let coordinator_support = Arc::new(DefaultCoordinatorSupport::new( chain.clone(), txpool.clone(), consensus.clone(), )); let coordinator = Arc::new(Coordinator::new( other_config.coordinator, coordinator_support, )?); // init api let api_support = Arc::new(DefaultApiSupport::new( chain.clone(), txpool.clone(), consensus.clone(), coordinator.clone(), )); let api = Arc::new(Api::new(other_config.api, api_support)); Ok(Self { config, chain, txpool, api, consensus, coordinator, }) } } /// Start service daemon pub fn start(config: ServiceConfig) -> CommonResult<()> { let rt = Runtime::new().map_err(ErrorKind::Runtime)?; rt.block_on(start_service(config))?; Ok(()) } async fn start_service(config: ServiceConfig) -> CommonResult<()> { let service = Service::new(config)?; wait_shutdown().await; drop(service); tokio::time::sleep(Duration::from_millis(50)).await; Ok(()) } async fn wait_shutdown() { #[cfg(windows)] let _ = tokio::signal::ctrl_c().await; #[cfg(unix)]
}
{ use tokio::signal::unix; let mut sigtun_int = unix::signal(unix::SignalKind::interrupt()).unwrap(); let mut sigtun_term = unix::signal(unix::SignalKind::terminate()).unwrap(); tokio::select! { _ = sigtun_int.recv() => {} _ = sigtun_term.recv() => {} } }
test_cert_parser.py
# # Copyright 2014 OpenStack Foundation. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import datetime from cryptography import x509 import mock from octavia.common import data_models import octavia.common.exceptions as exceptions import octavia.common.tls_utils.cert_parser as cert_parser from octavia.tests.common import sample_certs from octavia.tests.unit import base from octavia.tests.unit.common.sample_configs import sample_configs_combined class TestTLSParseUtils(base.TestCase): def test_alt_subject_name_parses(self): hosts = cert_parser.get_host_names(sample_certs.ALT_EXT_CRT) self.assertIn('www.cnfromsubject.org', hosts['cn']) self.assertIn('www.hostFromDNSName1.com', hosts['dns_names']) self.assertIn('www.hostFromDNSName2.com', hosts['dns_names']) self.assertIn('www.hostFromDNSName3.com', hosts['dns_names']) self.assertIn('www.hostFromDNSName4.com', hosts['dns_names']) def test_x509_parses(self): self.assertRaises(exceptions.UnreadableCert, cert_parser.validate_cert, "BAD CERT") self.assertTrue(cert_parser.validate_cert(sample_certs.X509_CERT)) self.assertTrue(cert_parser.validate_cert(sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY)) def test_read_private_key_pkcs8(self): self.assertRaises(exceptions.NeedsPassphrase, cert_parser._read_private_key, sample_certs.ENCRYPTED_PKCS8_CRT_KEY) cert_parser._read_private_key( sample_certs.ENCRYPTED_PKCS8_CRT_KEY, passphrase=sample_certs.ENCRYPTED_PKCS8_CRT_KEY_PASSPHRASE) def test_read_private_key_pem(self): self.assertRaises(exceptions.NeedsPassphrase, cert_parser._read_private_key, sample_certs.X509_CERT_KEY_ENCRYPTED) cert_parser._read_private_key( sample_certs.X509_CERT_KEY_ENCRYPTED, passphrase=sample_certs.X509_CERT_KEY_PASSPHRASE) def test_prepare_private_key(self): self.assertEqual( cert_parser.prepare_private_key( sample_certs.X509_CERT_KEY_ENCRYPTED, passphrase=sample_certs.X509_CERT_KEY_PASSPHRASE), sample_certs.X509_CERT_KEY) def test_prepare_private_key_orig_not_encrypted(self): self.assertEqual( cert_parser.prepare_private_key( sample_certs.X509_CERT_KEY), sample_certs.X509_CERT_KEY) def test_validate_cert_and_key_match(self): self.assertTrue( cert_parser.validate_cert( sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY)) self.assertTrue( cert_parser.validate_cert( sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY.decode('utf-8'))) self.assertRaises(exceptions.MisMatchedKey, cert_parser.validate_cert, sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY_2) def test_validate_cert_handles_intermediates(self): self.assertTrue( cert_parser.validate_cert( sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY, intermediates=(sample_certs.X509_IMDS + b"\nParser should ignore junk\n"))) self.assertTrue( cert_parser.validate_cert( sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY, intermediates=sample_certs.X509_IMDS_LIST)) def test_split_x509s(self): imds = [] for x509Pem in cert_parser._split_x509s(sample_certs.TEST_X509_IMDS): imds.append(cert_parser._get_x509_from_pem_bytes(x509Pem)) for i in range(0, len(imds)): self.assertEqual(sample_certs.EXPECTED_IMD_TEST_SUBJS[i], imds[i].subject.get_attributes_for_oid( x509.OID_COMMON_NAME)[0].value) def test_get_intermediates_pem_chain(self): self.assertEqual( sample_certs.X509_IMDS_LIST, list(cert_parser.get_intermediates_pems(sample_certs.X509_IMDS))) def test_get_intermediates_pkcs7_pem(self): self.assertEqual( sample_certs.X509_IMDS_LIST, list(cert_parser.get_intermediates_pems(sample_certs.PKCS7_PEM))) def test_get_intermediates_pkcs7_pem_bad(self): self.assertRaises( exceptions.UnreadableCert, lambda: list(cert_parser.get_intermediates_pems( b'-----BEGIN PKCS7-----\nbad data\n-----END PKCS7-----'))) def test_get_intermediates_pkcs7_der(self): self.assertEqual( sample_certs.X509_IMDS_LIST, list(cert_parser.get_intermediates_pems(sample_certs.PKCS7_DER))) def test_get_intermediates_pkcs7_der_bad(self): self.assertRaises( exceptions.UnreadableCert, lambda: list(cert_parser.get_intermediates_pems( b'\xfe\xfe\xff\xff'))) def test_get_x509_from_der_bytes_bad(self): self.assertRaises( exceptions.UnreadableCert, cert_parser._get_x509_from_der_bytes, b'bad data') @mock.patch('oslo_context.context.RequestContext') def test_load_certificates(self, mock_oslo): listener = sample_configs_combined.sample_listener_tuple( tls=True, sni=True, client_ca_cert=True) client = mock.MagicMock() context = mock.Mock() context.project_id = '12345' with mock.patch.object(cert_parser, 'get_host_names') as cp: with mock.patch.object(cert_parser, '_map_cert_tls_container'): cp.return_value = {'cn': 'fakeCN'} cert_parser.load_certificates_data(client, listener, context) # Ensure upload_cert is called three times calls_cert_mngr = [ mock.call.get_cert(context, 'cont_id_1', check_only=True), mock.call.get_cert(context, 'cont_id_2', check_only=True), mock.call.get_cert(context, 'cont_id_3', check_only=True) ] client.assert_has_calls(calls_cert_mngr) # Test asking for nothing listener = sample_configs_combined.sample_listener_tuple( tls=False, sni=False, client_ca_cert=False) client = mock.MagicMock() with mock.patch.object(cert_parser, '_map_cert_tls_container') as mock_map: result = cert_parser.load_certificates_data(client, listener) mock_map.assert_not_called() ref_empty_dict = {'tls_cert': None, 'sni_certs': []} self.assertEqual(ref_empty_dict, result) mock_oslo.assert_called() def test_load_certificates_get_cert_errors(self): mock_cert_mngr = mock.MagicMock() mock_obj = mock.MagicMock() mock_sni_container = mock.MagicMock() mock_sni_container.tls_container_id = 2 mock_cert_mngr.get_cert.side_effect = [Exception, Exception] # Test tls_certificate_id error mock_obj.tls_certificate_id = 1 self.assertRaises(exceptions.CertificateRetrievalException, cert_parser.load_certificates_data, mock_cert_mngr, mock_obj) # Test sni_containers error mock_obj.tls_certificate_id = None mock_obj.sni_containers = [mock_sni_container] self.assertRaises(exceptions.CertificateRetrievalException, cert_parser.load_certificates_data, mock_cert_mngr, mock_obj) @mock.patch('octavia.certificates.common.cert.Cert') def test_map_cert_tls_container(self, cert_mock):
def test_build_pem(self): expected = b'imacert\nimakey\nimainter\nimainter2\n' tls_tuple = sample_configs_combined.sample_tls_container_tuple( certificate=b'imacert', private_key=b'imakey', intermediates=[b'imainter', b'imainter2']) self.assertEqual(expected, cert_parser.build_pem(tls_tuple)) def test_get_primary_cn(self): cert = sample_certs.X509_CERT with mock.patch.object(cert_parser, 'get_host_names') as cp: cp.return_value = {'cn': 'fakeCN'} cn = cert_parser.get_primary_cn(cert) self.assertEqual('fakeCN', cn) def test_get_cert_expiration(self): exp_date = cert_parser.get_cert_expiration(sample_certs.X509_EXPIRED) self.assertEqual(datetime.datetime(2016, 9, 25, 18, 1, 54), exp_date) # test the exception self.assertRaises(exceptions.UnreadableCert, cert_parser.get_cert_expiration, 'bad-cert-file')
tls = data_models.TLSContainer( id=sample_certs.X509_CERT_SHA1, primary_cn=sample_certs.X509_CERT_CN, certificate=sample_certs.X509_CERT, private_key=sample_certs.X509_CERT_KEY_ENCRYPTED, passphrase=sample_certs.X509_CERT_KEY_PASSPHRASE, intermediates=sample_certs.X509_IMDS_LIST) cert_mock.get_private_key.return_value = tls.private_key cert_mock.get_certificate.return_value = tls.certificate cert_mock.get_intermediates.return_value = tls.intermediates cert_mock.get_private_key_passphrase.return_value = tls.passphrase with mock.patch.object(cert_parser, 'get_host_names') as cp: cp.return_value = {'cn': sample_certs.X509_CERT_CN} self.assertEqual( tls.id, cert_parser._map_cert_tls_container( cert_mock).id) self.assertEqual( tls.primary_cn, cert_parser._map_cert_tls_container( cert_mock).primary_cn) self.assertEqual( tls.certificate, cert_parser._map_cert_tls_container( cert_mock).certificate) self.assertEqual( sample_certs.X509_CERT_KEY, cert_parser._map_cert_tls_container( cert_mock).private_key) self.assertEqual( tls.intermediates, cert_parser._map_cert_tls_container( cert_mock).intermediates)
0015_auto_20160914_1640.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2016-09-14 23:40 from __future__ import unicode_literals from django.db import migrations, models class
(migrations.Migration): dependencies = [ ('contentcuration', '0014_channel_language'), ] operations = [ migrations.AlterField( model_name='channel', name='thumbnail', field=models.TextField(blank=True, null=True), ), ]
Migration
models.py
from collections import namedtuple from enum import Enum class EncryptionMethod(Enum): def __str__(self):
MD5 = 'md5' SHA512 = 'sha512' UNKNOWN = 'unknown' DeviceInfo = namedtuple( "DeviceInfo", [ "mac_address", "serial_number", "manufacturer", "model_name", "model_number", "software_version", "hardware_version", "uptime", "reboot_count", "router_name", "bootloader_version" ]) Device = namedtuple( "Device", [ "mac_address", "ip_address", "ipv4_addresses", "ipv6_addresses", "name", "address_source", "interface", "active", "user_friendly_name", "detected_device_type", "user_device_type" ])
return str(self.value)
retinaface.py
import torch import torch.nn as nn import torchvision.models.detection.backbone_utils as backbone_utils import torchvision.models._utils as _utils import torch.nn.functional as F from collections import OrderedDict from retina_models.net import MobileNetV1 as MobileNetV1 from retina_models.net import FPN as FPN from retina_models.net import SSH as SSH class ClassHead(nn.Module): def __init__(self,inchannels=512,num_anchors=3): super(ClassHead,self).__init__() self.num_anchors = num_anchors self.conv1x1 = nn.Conv2d(inchannels,self.num_anchors*2,kernel_size=(1,1),stride=1,padding=0) def forward(self,x): out = self.conv1x1(x) out = out.permute(0,2,3,1).contiguous() return out.view(out.shape[0], -1, 2) class BboxHead(nn.Module): def __init__(self,inchannels=512,num_anchors=3): super(BboxHead,self).__init__() self.conv1x1 = nn.Conv2d(inchannels,num_anchors*4,kernel_size=(1,1),stride=1,padding=0) def forward(self,x): out = self.conv1x1(x) out = out.permute(0,2,3,1).contiguous() return out.view(out.shape[0], -1, 4) class LandmarkHead(nn.Module): def __init__(self,inchannels=512,num_anchors=3): super(LandmarkHead,self).__init__() self.conv1x1 = nn.Conv2d(inchannels,num_anchors*10,kernel_size=(1,1),stride=1,padding=0) def forward(self,x): out = self.conv1x1(x) out = out.permute(0,2,3,1).contiguous() return out.view(out.shape[0], -1, 10) class RetinaFace(nn.Module): def
(self, cfg = None, phase = 'train'): """ :param cfg: Network related settings. :param phase: train or test. """ super(RetinaFace,self).__init__() self.phase = phase backbone = None if cfg['name'] == 'mobilenet0.25': backbone = MobileNetV1() if cfg['pretrain']: checkpoint = torch.load("./Pytorch_Retinaface/weights/mobilenetV1X0.25_pretrain.tar", map_location=torch.device('cpu')) from collections import OrderedDict new_state_dict = OrderedDict() for k, v in checkpoint['state_dict'].items(): name = k[7:] # remove module. new_state_dict[name] = v # load params backbone.load_state_dict(new_state_dict) elif cfg['name'] == 'Resnet50': import torchvision.models as models backbone = models.resnet50(pretrained=cfg['pretrain']) self.body = _utils.IntermediateLayerGetter(backbone, cfg['return_layers']) in_channels_stage2 = cfg['in_channel'] in_channels_list = [ in_channels_stage2 * 2, in_channels_stage2 * 4, in_channels_stage2 * 8, ] out_channels = cfg['out_channel'] self.fpn = FPN(in_channels_list,out_channels) self.ssh1 = SSH(out_channels, out_channels) self.ssh2 = SSH(out_channels, out_channels) self.ssh3 = SSH(out_channels, out_channels) self.ClassHead = self._make_class_head(fpn_num=3, inchannels=cfg['out_channel']) self.BboxHead = self._make_bbox_head(fpn_num=3, inchannels=cfg['out_channel']) self.LandmarkHead = self._make_landmark_head(fpn_num=3, inchannels=cfg['out_channel']) def _make_class_head(self,fpn_num=3,inchannels=64,anchor_num=2): classhead = nn.ModuleList() for i in range(fpn_num): classhead.append(ClassHead(inchannels,anchor_num)) return classhead def _make_bbox_head(self,fpn_num=3,inchannels=64,anchor_num=2): bboxhead = nn.ModuleList() for i in range(fpn_num): bboxhead.append(BboxHead(inchannels,anchor_num)) return bboxhead def _make_landmark_head(self,fpn_num=3,inchannels=64,anchor_num=2): landmarkhead = nn.ModuleList() for i in range(fpn_num): landmarkhead.append(LandmarkHead(inchannels,anchor_num)) return landmarkhead def forward(self,inputs): out = self.body(inputs) # FPN fpn = self.fpn(out) # SSH feature1 = self.ssh1(fpn[0]) feature2 = self.ssh2(fpn[1]) feature3 = self.ssh3(fpn[2]) features = [feature1, feature2, feature3] bbox_regressions = torch.cat([self.BboxHead[i](feature) for i, feature in enumerate(features)], dim=1) classifications = torch.cat([self.ClassHead[i](feature) for i, feature in enumerate(features)],dim=1) ldm_regressions = torch.cat([self.LandmarkHead[i](feature) for i, feature in enumerate(features)], dim=1) if self.phase == 'train': output = (bbox_regressions, classifications, ldm_regressions) else: output = (bbox_regressions, F.softmax(classifications, dim=-1), ldm_regressions) return output
__init__
edition-lint-paths.rs
// aux-build:edition-lint-paths.rs // run-rustfix #![feature(rust_2018_preview)] #![deny(absolute_paths_not_starting_with_crate)] #![allow(unused)] extern crate edition_lint_paths;
//~| WARN this is accepted in the current edition //~| ERROR absolute //~| WARN this is accepted in the current edition use super::bar::Bar2; use crate::bar::Bar3; use bar; //~^ ERROR absolute //~| WARN this is accepted in the current edition use crate::bar as something_else; use {main, Bar as SomethingElse}; //~^ ERROR absolute //~| WARN this is accepted in the current edition //~| ERROR absolute //~| WARN this is accepted in the current edition //~| ERROR absolute //~| WARN this is accepted in the current edition use crate::{main as another_main, Bar as SomethingElse2}; pub fn test() {} pub trait SomeTrait {} } use bar::Bar; //~^ ERROR absolute //~| WARN this is accepted in the current edition //~| ERROR absolute //~| WARN this is accepted in the current edition pub mod bar { use edition_lint_paths as foo; pub struct Bar; pub type Bar2 = Bar; pub type Bar3 = Bar; } mod baz { use *; //~^ ERROR absolute //~| WARN this is accepted in the current edition } impl ::foo::SomeTrait for u32 {} //~^ ERROR absolute //~| WARN this is accepted in the current edition //~| ERROR absolute //~| WARN this is accepted in the current edition fn main() { let x = ::bar::Bar; //~^ ERROR absolute //~| WARN this is accepted in the current edition let x = bar::Bar; let x = crate::bar::Bar; let x = self::bar::Bar; foo::test(); { use edition_lint_paths as bar; edition_lint_paths::foo(); bar::foo(); ::edition_lint_paths::foo(); } }
pub mod foo { use edition_lint_paths; use bar::Bar; //~^ ERROR absolute
get_aws_iam_external_id_responses.go
// Code generated by go-swagger; DO NOT EDIT. package a_w_s_credentials_configuration // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" "github.com/Kissy/go-dynatrace/dynatrace" ) // GetAwsIamExternalIDReader is a Reader for the GetAwsIamExternalID structure. type GetAwsIamExternalIDReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetAwsIamExternalIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetAwsIamExternalIDOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewGetAwsIamExternalIDOK creates a GetAwsIamExternalIDOK with default headers values func NewGetAwsIamExternalIDOK() *GetAwsIamExternalIDOK { return &GetAwsIamExternalIDOK{} } /*GetAwsIamExternalIDOK handles this case with default header values. successful operation */ type GetAwsIamExternalIDOK struct { Payload *dynatrace.AwsIamToken } func (o *GetAwsIamExternalIDOK) Error() string { return fmt.Sprintf("[GET /aws/iamExternalId][%d] getAwsIamExternalIdOK %+v", 200, o.Payload) } func (o *GetAwsIamExternalIDOK) GetPayload() *dynatrace.AwsIamToken { return o.Payload } func (o *GetAwsIamExternalIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(dynatrace.AwsIamToken) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF
return nil }
{ return err }
vector_hasher.rs
use crate::datatypes::UInt64Chunked; use crate::prelude::*; use crate::utils::arrow::array::Array; use crate::POOL; use ahash::{CallHasher, RandomState}; use arrow::bitmap::utils::get_bit_unchecked; use hashbrown::{hash_map::RawEntryMut, HashMap}; use polars_arrow::utils::CustomIterTools; use rayon::prelude::*; use std::convert::TryInto; use std::hash::{BuildHasher, BuildHasherDefault, Hash, Hasher}; // Read more: // https://www.cockroachlabs.com/blog/vectorized-hash-joiner/ // http://myeyesareblind.com/2017/02/06/Combine-hash-values/ pub trait VecHash { /// Compute the hash for all values in the array. /// /// This currently only works with the AHash RandomState hasher builder. fn vec_hash(&self, _random_state: RandomState) -> Vec<u64> { unimplemented!() } fn vec_hash_combine(&self, _random_state: RandomState, _hashes: &mut [u64]) { unimplemented!() } } pub(crate) fn get_null_hash_value(random_state: RandomState) -> u64 { // we just start with a large prime number and hash that twice // to get a constant hash value for null/None let mut hasher = random_state.build_hasher(); 3188347919usize.hash(&mut hasher); let first = hasher.finish(); let mut hasher = random_state.build_hasher(); first.hash(&mut hasher); hasher.finish() } impl<T> VecHash for ChunkedArray<T> where T: PolarsIntegerType, T::Native: Hash + CallHasher, { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { // Note that we don't use the no null branch! This can break in unexpected ways. // for instance with threading we split an array in n_threads, this may lead to // splits that have no nulls and splits that have nulls. Then one array is hashed with // Option<T> and the other array with T. // Meaning that they cannot be compared. By always hashing on Option<T> the random_state is // the only deterministic seed. let mut av = Vec::with_capacity(self.len()); self.downcast_iter().for_each(|arr| { av.extend( arr.values() .as_slice() .iter() .map(|v| T::Native::get_hash(v, &random_state)), ); }); let null_h = get_null_hash_value(random_state); let hashes = av.as_mut_slice(); let mut offset = 0; self.downcast_iter().for_each(|arr| { if let Some(validity) = arr.validity() { let (slice, byte_offset, _) = validity.as_slice(); (0..validity.len()) .map(|i| unsafe { get_bit_unchecked(slice, i + byte_offset) }) .zip(&mut hashes[offset..]) .for_each(|(valid, h)| { *h = [null_h, *h][valid as usize]; }) } offset += arr.len(); }); av } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { let null_h = get_null_hash_value(random_state.clone()); let mut offset = 0; self.downcast_iter().for_each(|arr| { match arr.null_count() { 0 => arr .values() .as_slice() .iter() .zip(&mut hashes[offset..]) .for_each(|(v, h)| { let l = T::Native::get_hash(v, &random_state); *h = boost_hash_combine(l, *h) }), _ => { let validity = arr.validity().unwrap(); let (slice, byte_offset, _) = validity.as_slice(); (0..validity.len()) .map(|i| unsafe { get_bit_unchecked(slice, i + byte_offset) }) .zip(&mut hashes[offset..]) .zip(arr.values().as_slice()) .for_each(|((valid, h), l)| { *h = boost_hash_combine( [null_h, T::Native::get_hash(l, &random_state)][valid as usize], *h, ) }); } } offset += arr.len(); }); } } impl VecHash for Utf8Chunked { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { let null_h = get_null_hash_value(random_state.clone()); let mut av = Vec::with_capacity(self.len()); self.downcast_iter().for_each(|arr| { av.extend(arr.into_iter().map(|opt_v| match opt_v { Some(v) => str::get_hash(v, &random_state), None => null_h, })) }); av } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { let null_h = get_null_hash_value(random_state.clone()); self.apply_to_slice( |opt_v, h| { let l = match opt_v {
}; boost_hash_combine(l, *h) }, hashes, ) } } impl VecHash for BooleanChunked { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { let mut av = Vec::with_capacity(self.len()); self.downcast_iter().for_each(|arr| { av.extend(arr.into_iter().map(|opt_v| { let mut hasher = random_state.build_hasher(); opt_v.hash(&mut hasher); hasher.finish() })) }); av } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { self.apply_to_slice( |opt_v, h| { let mut hasher = random_state.build_hasher(); opt_v.hash(&mut hasher); boost_hash_combine(hasher.finish(), *h) }, hashes, ) } } impl VecHash for Float32Chunked { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { self.bit_repr_small().vec_hash(random_state) } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { self.bit_repr_small().vec_hash_combine(random_state, hashes) } } impl VecHash for Float64Chunked { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { self.bit_repr_large().vec_hash(random_state) } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { self.bit_repr_large().vec_hash_combine(random_state, hashes) } } #[cfg(feature = "object")] impl<T> VecHash for ObjectChunked<T> where T: PolarsObject, { fn vec_hash(&self, random_state: RandomState) -> Vec<u64> { // Note that we don't use the no null branch! This can break in unexpected ways. // for instance with threading we split an array in n_threads, this may lead to // splits that have no nulls and splits that have nulls. Then one array is hashed with // Option<T> and the other array with T. // Meaning that they cannot be compared. By always hashing on Option<T> the random_state is // the only deterministic seed. let mut av = Vec::with_capacity(self.len()); self.downcast_iter().for_each(|arr| { av.extend(arr.into_iter().map(|opt_v| { let mut hasher = random_state.build_hasher(); opt_v.hash(&mut hasher); hasher.finish() })) }); av } fn vec_hash_combine(&self, random_state: RandomState, hashes: &mut [u64]) { self.apply_to_slice( |opt_v, h| { let mut hasher = random_state.build_hasher(); opt_v.hash(&mut hasher); boost_hash_combine(hasher.finish(), *h) }, hashes, ) } } // Used to to get a u64 from the hashing keys // We need to modify the hashing algorithm to use the hash for this and only compute the hash once. pub(crate) trait AsU64 { #[allow(clippy::wrong_self_convention)] fn as_u64(self) -> u64; } impl AsU64 for u32 { #[inline] fn as_u64(self) -> u64 { self as u64 } } impl AsU64 for u64 { #[inline] fn as_u64(self) -> u64 { self } } impl AsU64 for i32 { #[inline] fn as_u64(self) -> u64 { let asu32: u32 = unsafe { std::mem::transmute(self) }; dbg!(asu32 as u64) } } impl AsU64 for i64 { #[inline] fn as_u64(self) -> u64 { unsafe { dbg!(std::mem::transmute(self)) } } } impl AsU64 for Option<u32> { #[inline] fn as_u64(self) -> u64 { match self { Some(v) => v as u64, // just a number safe from overflow None => u64::MAX >> 2, } } } impl AsU64 for Option<u64> { #[inline] fn as_u64(self) -> u64 { self.unwrap_or(u64::MAX >> 2) } } impl AsU64 for [u8; 9] { #[inline] fn as_u64(self) -> u64 { // the last byte includes the null information. // that one is skipped. Worst thing that could happen is unbalanced partition. u64::from_ne_bytes(self[..8].try_into().unwrap()) } } const BUILD_HASHER: RandomState = RandomState::with_seeds(0, 0, 0, 0); impl AsU64 for [u8; 17] { #[inline] fn as_u64(self) -> u64 { <[u8]>::get_hash(&self, &BUILD_HASHER) } } impl AsU64 for [u8; 13] { #[inline] fn as_u64(self) -> u64 { <[u8]>::get_hash(&self, &BUILD_HASHER) } } #[derive(Default)] pub struct IdHasher { hash: u64, } impl Hasher for IdHasher { fn finish(&self) -> u64 { self.hash } fn write(&mut self, _bytes: &[u8]) { unreachable!("IdHasher should only be used for integer keys <= 64 bit precision") } fn write_u32(&mut self, i: u32) { self.write_u64(i as u64) } fn write_u64(&mut self, i: u64) { self.hash = i; } fn write_i32(&mut self, i: i32) { // Safety: // same number of bits unsafe { self.write_u32(std::mem::transmute::<i32, u32>(i)) } } fn write_i64(&mut self, i: i64) { // Safety: // same number of bits unsafe { self.write_u64(std::mem::transmute::<i64, u64>(i)) } } } pub type IdBuildHasher = BuildHasherDefault<IdHasher>; #[derive(Debug)] /// Contains an idx of a row in a DataFrame and the precomputed hash of that row. /// That hash still needs to be used to create another hash to be able to resize hashmaps without /// accidental quadratic behavior. So do not use an Identity function! pub(crate) struct IdxHash { // idx in row of Series, DataFrame pub(crate) idx: IdxSize, // precomputed hash of T hash: u64, } impl Hash for IdxHash { fn hash<H: Hasher>(&self, state: &mut H) { state.write_u64(self.hash) } } impl IdxHash { #[inline] pub(crate) fn new(idx: IdxSize, hash: u64) -> Self { IdxHash { idx, hash } } } /// Contains a ptr to the string slice an the precomputed hash of that string. /// During rehashes, we will rehash the hash instead of the string, that makes rehashing /// cheap and allows cache coherent small hash tables. #[derive(Eq, Copy, Clone)] pub(crate) struct StrHash<'a> { str: Option<&'a str>, hash: u64, } impl<'a> Hash for StrHash<'a> { fn hash<H: Hasher>(&self, state: &mut H) { state.write_u64(self.hash) } } impl<'a> StrHash<'a> { pub(crate) fn new(s: Option<&'a str>, hash: u64) -> Self { Self { str: s, hash } } } impl<'a> PartialEq for StrHash<'a> { fn eq(&self, other: &Self) -> bool { (self.hash == other.hash) && (self.str == other.str) } } impl<'a> AsU64 for StrHash<'a> { fn as_u64(self) -> u64 { self.hash } } #[inline] /// For partitions that are a power of 2 we can use a bitshift instead of a modulo. pub(crate) fn this_partition(h: u64, thread_no: u64, n_partitions: u64) -> bool { debug_assert!(n_partitions.is_power_of_two()); // n % 2^i = n & (2^i - 1) (h.wrapping_add(thread_no)) & n_partitions.wrapping_sub(1) == 0 } pub(crate) fn prepare_hashed_relation_threaded<T, I>( iters: Vec<I>, ) -> Vec<HashMap<T, (bool, Vec<IdxSize>), RandomState>> where I: Iterator<Item = T> + Send + TrustedLen, T: Send + Hash + Eq + Sync + Copy, { let n_partitions = iters.len(); assert!(n_partitions.is_power_of_two()); let (hashes_and_keys, build_hasher) = create_hash_and_keys_threaded_vectorized(iters, None); // We will create a hashtable in every thread. // We use the hash to partition the keys to the matching hashtable. // Every thread traverses all keys/hashes and ignores the ones that doesn't fall in that partition. POOL.install(|| { (0..n_partitions).into_par_iter().map(|partition_no| { let build_hasher = build_hasher.clone(); let hashes_and_keys = &hashes_and_keys; let partition_no = partition_no as u64; let mut hash_tbl: HashMap<T, (bool, Vec<IdxSize>), RandomState> = HashMap::with_hasher(build_hasher); let n_threads = n_partitions as u64; let mut offset = 0; for hashes_and_keys in hashes_and_keys { let len = hashes_and_keys.len(); hashes_and_keys .iter() .enumerate() .for_each(|(idx, (h, k))| { let idx = idx as IdxSize; // partition hashes by thread no. // So only a part of the hashes go to this hashmap if this_partition(*h, partition_no, n_threads) { let idx = idx + offset; let entry = hash_tbl .raw_entry_mut() // uses the key to check equality to find and entry .from_key_hashed_nocheck(*h, k); match entry { RawEntryMut::Vacant(entry) => { entry.insert_hashed_nocheck(*h, *k, (false, vec![idx])); } RawEntryMut::Occupied(mut entry) => { let (_k, v) = entry.get_key_value_mut(); v.1.push(idx); } } } }); offset += len as IdxSize; } hash_tbl }) }) .collect() } pub(crate) fn create_hash_and_keys_threaded_vectorized<I, T>( iters: Vec<I>, build_hasher: Option<RandomState>, ) -> (Vec<Vec<(u64, T)>>, RandomState) where I: IntoIterator<Item = T> + Send, I::IntoIter: TrustedLen, T: Send + Hash + Eq, { let build_hasher = build_hasher.unwrap_or_default(); let hashes = POOL.install(|| { iters .into_par_iter() .map(|iter| { // create hashes and keys iter.into_iter() .map(|val| { let mut hasher = build_hasher.build_hasher(); val.hash(&mut hasher); (hasher.finish(), val) }) .collect_trusted::<Vec<_>>() }) .collect() }); (hashes, build_hasher) } // hash combine from c++' boost lib #[inline] pub(crate) fn boost_hash_combine(l: u64, r: u64) -> u64 { l ^ r.wrapping_add(0x9e3779b9u64.wrapping_add(l << 6).wrapping_add(r >> 2)) } pub(crate) fn df_rows_to_hashes_threaded( keys: &[DataFrame], hasher_builder: Option<RandomState>, ) -> (Vec<UInt64Chunked>, RandomState) { let hasher_builder = hasher_builder.unwrap_or_default(); let hashes = POOL.install(|| { keys.into_par_iter() .map(|df| { let hb = hasher_builder.clone(); let (ca, _) = df_rows_to_hashes(df, Some(hb)); ca }) .collect() }); (hashes, hasher_builder) } pub(crate) fn df_rows_to_hashes( keys: &DataFrame, build_hasher: Option<RandomState>, ) -> (UInt64Chunked, RandomState) { let build_hasher = build_hasher.unwrap_or_default(); let mut iter = keys.iter(); let first = iter.next().expect("at least one key"); let mut hashes = first.vec_hash(build_hasher.clone()); let hslice = hashes.as_mut_slice(); for keys in iter { keys.vec_hash_combine(build_hasher.clone(), hslice); } let chunks = vec![Box::new(PrimitiveArray::from_data( ArrowDataType::UInt64, hashes.into(), None, )) as ArrayRef]; (UInt64Chunked::from_chunks("", chunks), build_hasher) }
Some(v) => str::get_hash(v, &random_state), None => null_h,
day22.go
package day22 import ( "io" "io/ioutil" ) type Grid struct { b []byte p, w, x, y int } func ParseGrid(r io.Reader) *Grid { b, err := ioutil.ReadAll(r) if err != nil { panic(err) } g := &Grid{ b: make([]byte, 0, len(b)), y: -1, } for i := 0; i < len(b); i++ { switch b[i] { case '\n': if g.w == 0 { g.w = i } default: g.b = append(g.b, b[i]) } } g.p = (g.w * (g.w / 2)) + g.w/2 return g } // Grow allocates a new Grid, three times larger than the current Grid, with the // original Grid copied into the exact centre of the new Grid. The Cursor // position is also transposed onto the new Grid. // // A more elegant solution might first crop unused sides of the grid and only // preallocate extra capacity in the direction of the cursor. func (g *Grid) Grow() { n := g.w * 3 b := make([]byte, n*n) for i := 0; i < len(b); i++ { b[i] = '.' } j := g.w*g.w*3 + g.w for i := 0; i < len(g.b); i++ { b[j] = g.b[i] if i%g.w == g.w-1
j++ } g.p = (g.w * g.w * 3) + (g.p/g.w)*(g.w*3) + g.w + (g.p % g.w) g.w = n g.b = b } // Infect is my solution to Part One. It takes n steps over the infinite Grid, // toggling nodes between clean and infected. The number of infections that are // created during these steps is returned. func (g *Grid) Infect(n int) int { count := 0 for i := 0; i < n; i++ { switch g.b[g.p] { case '.': g.b[g.p] = '#' count++ // turn left switch g.x { case 1: g.x, g.y = 0, -1 case -1: g.x, g.y = 0, 1 case 0: switch g.y { case 1: g.x, g.y = 1, 0 case -1: g.x, g.y = -1, 0 } } case '#': g.b[g.p] = '.' // turn right switch g.x { case 1: g.x, g.y = 0, 1 case -1: g.x, g.y = 0, -1 case 0: switch g.y { case 1: g.x, g.y = -1, 0 case -1: g.x, g.y = 1, 0 } } } // grow if cursor on boundary if g.p < g.w || g.p/g.w == g.w-1 || g.p%g.w == 0 || g.p%g.w == g.w-1 { g.Grow() } // move cursor g.p += g.y*g.w + g.x } return count } // InfectEvolved is my solution to Part Two. It takes n steps over the infinite // Grid, toggling nodes between clean, weakened, infected and flagged. The // number of infections that are created during these steps is returned. func (g *Grid) InfectEvolved(n int) int { count := 0 for i := 0; i < n; i++ { switch g.b[g.p] { case '.': g.b[g.p] = 'W' // turn left switch g.x { case 1: g.x, g.y = 0, -1 case -1: g.x, g.y = 0, 1 case 0: switch g.y { case 1: g.x, g.y = 1, 0 case -1: g.x, g.y = -1, 0 } } case '#': g.b[g.p] = 'F' // turn right switch g.x { case 1: g.x, g.y = 0, 1 case -1: g.x, g.y = 0, -1 case 0: switch g.y { case 1: g.x, g.y = -1, 0 case -1: g.x, g.y = 1, 0 } } case 'W': g.b[g.p] = '#' count++ case 'F': g.b[g.p] = '.' g.x = -g.x g.y = -g.y } // grow if cursor on boundary if g.p < g.w || g.p/g.w == g.w-1 || g.p%g.w == 0 || g.p%g.w == g.w-1 { g.Grow() } // move cursor g.p += g.y*g.w + g.x } return count }
{ j += 2 * g.w }
passphrase_test.go
package passphrase import ( "bufio" "bytes" "io/ioutil" "testing" "github.com/stretchr/testify/require" ) var input = []struct { in string valid bool }{ {"aa bb cc dd ee", true}, {"aa bb cc dd aa", false}, {"aa bb cc dd aaa", true}, } func TestPassphase(t *testing.T) { assert := require.New(t) for _, in := range input { assert.Equal(in.valid, Passphrase(in.in)) } } func TestSolvePassphrase(t *testing.T)
var stinput = []struct { in string valid bool }{ {"abcde fghij", true}, {"abcde xyz ecdab ", false}, {"a ab abc abd abf abj", true}, {"iiii oiii ooii oooi oooo", true}, {"oiii ioii iioi iiio ", false}, } func TestStrongPassphase(t *testing.T) { assert := require.New(t) for _, in := range stinput { assert.Equal(in.valid, StrongPasshrase(in.in)) } } func TestSolveStrongPasshrase(t *testing.T) { assert := require.New(t) dat, _ := ioutil.ReadFile("./input.txt") n := 0 scanner := bufio.NewScanner(bytes.NewReader(dat)) for scanner.Scan() { if StrongPasshrase(scanner.Text()) { n++ } } assert.Equal(208, n) }
{ assert := require.New(t) dat, _ := ioutil.ReadFile("./input.txt") n := 0 scanner := bufio.NewScanner(bytes.NewReader(dat)) for scanner.Scan() { if Passphrase(scanner.Text()) { n++ } } assert.Equal(386, n) }
test.js
'use strict'; require('mocha'); const assert = require('assert').strict; const pascalcase = require('.'); describe('pascalcase', () => { it('should uppercase a single character string', () => { assert.equal(pascalcase('a'), 'A'); assert.equal(pascalcase('Z'), 'Z'); }); it('should work with spaces', () => { assert.equal(pascalcase('foo bar baz'), 'FooBarBaz'); assert.equal(pascalcase('foo baz'), 'FooBaz'); assert.equal(pascalcase(' foo bar baz '), 'FooBarBaz'); }); it('should work with numbers', () => { assert.equal(pascalcase(3), '3'); assert.equal(pascalcase('foo2bar5baz'), 'Foo2bar5baz'); assert.equal(pascalcase('foo 2 bar 5 baz'), 'Foo2Bar5Baz'); }); it('should not lowercase existing camelcasing', () => { assert.equal(pascalcase('fooBarBaz'), 'FooBarBaz'); assert.equal(pascalcase('FooBarBaz'), 'FooBarBaz'); assert.equal(pascalcase(' FooBarBaz'), 'FooBarBaz'); assert.equal(pascalcase(' fooBarBaz'), 'FooBarBaz'); }); it('should remove non-word-characters', () => { assert.equal(pascalcase('foo_bar-baz'), 'FooBarBaz'); assert.equal(pascalcase('foo.bar.baz'), 'FooBarBaz'); assert.equal(pascalcase('foo/bar/baz'), 'FooBarBaz'); assert.equal(pascalcase('foo[bar)baz'), 'FooBarBaz'); assert.equal(pascalcase('#foo+bar*baz'), 'FooBarBaz'); assert.equal(pascalcase('$foo~bar`baz'), 'FooBarBaz'); assert.equal(pascalcase('_foo_bar-baz-'), 'FooBarBaz'); assert.equal(pascalcase('_A_B_c-'), 'ABC'); }); it('should return empty string when value null or undefined', () => { assert.equal(pascalcase(null), '');
it('should call .toString() when value is not a primitive', () => { assert.equal(pascalcase(['one', 'two', 'three']), 'OneTwoThree'); assert.equal(pascalcase([]), ''); assert.equal(pascalcase(function foo_bar() {}), 'FunctionFooBar'); assert.equal(pascalcase({}), 'ObjectObject'); assert.equal(pascalcase(/foo/), 'Foo'); }); });
assert.equal(pascalcase(), ''); });
schedutil.py
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2019, ARM Limited and contributors. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from math import ceil import os import pandas as pd from lisa.wlgen.rta import Ramp from lisa.tests.base import TestBundle, ResultBundle, Result, RTATestBundle from lisa.target import Target from lisa.trace import requires_events, FtraceCollector, FtraceConf from lisa.datautils import df_merge, series_mean from lisa.utils import ArtifactPath from lisa.analysis.frequency import FrequencyAnalysis from lisa.analysis.load_tracking import LoadTrackingAnalysis from lisa.analysis.rta import RTAEventsAnalysis class RampBoostTestBase(RTATestBundle): """ Test schedutil's ramp boost feature. """ def __init__(self, res_dir, plat_info, cpu): super().__init__(res_dir, plat_info) self.cpu = cpu @requires_events('cpu_idle', 'cpu_frequency', 'sched_wakeup') def estimate_nrg(self): return self.plat_info['nrg-model'].estimate_from_trace(self.trace).sum(axis=1) def get_avg_slack(self, only_negative=False): analysis = self.trace.analysis.rta def get_slack(task): series = analysis.df_rtapp_stats(task)['slack'] if only_negative: series = series[series < 0] if series.empty: return 0 else: # average negative slack across all activations return series.mean() return { task: get_slack(task) for task in self.trace.analysis.rta.rtapp_tasks } @LoadTrackingAnalysis.df_cpus_signal.used_events @requires_events('schedutil_em') def df_ramp_boost(self): """ Return a dataframe with schedutil-related signals, sampled at the frequency decisions timestamps for the CPU this bundle was executed on. .. note:: The computed columns only take into account the CPU the test was executing on. It currently does not handle multi-task workloads. """ trace = self.trace cpu = self.cpu # schedutil_df also has a 'util' column that would conflict schedutil_df = trace.df_events('schedutil_em')[['cpu', 'cost_margin']] schedutil_df['from_schedutil'] = True df_list = [ schedutil_df, trace.analysis.load_tracking.df_cpus_signal('util'), trace.analysis.load_tracking.df_cpus_signal('util_est_enqueued'), ] df = df_merge(df_list, filter_columns={'cpu': cpu}) df['from_schedutil'].fillna(value=False, inplace=True) df.ffill(inplace=True) df.dropna(inplace=True) # Reconstitute how schedutil sees signals by subsampling the # "master" dataframe, so we can look at signals coming from other # dataframes df = df[df['from_schedutil'] == True] df.drop(columns=['from_schedutil'], inplace=True) # If there are some NaN at the beginning, just drop some data rather # than using fake data df.dropna(inplace=True) boost_points = ( # util_est_enqueued is the same as last freq update (df['util_est_enqueued'].diff() == 0) & # util_avg is increasing (df['util'].diff() >= 0) & # util_avg > util_est_enqueued (df['util'] > df['util_est_enqueued']) ) df['boost_points'] = boost_points df['expected_cost_margin'] = (df['util'] - df['util_est_enqueued']).where( cond=boost_points, other=0, ) # cost_margin values range from 0 to 1024 ENERGY_SCALE = 1024 for col in ('expected_cost_margin', 'cost_margin'): df[col] *= 100 / ENERGY_SCALE # We cannot know if the first row is supposed to be boosted or not # because we lack history, so we just drop it return df.iloc[1:]
analysis = self.trace.analysis.frequency fig, axis = analysis.setup_plot(interactive=False) df['cost_margin'].plot(ax=axis, drawstyle='steps-post', color='r') df['boost_points'].astype('int', copy=False).plot(ax=axis, drawstyle='steps-post', color='black') df['expected_cost_margin'].plot(ax=axis, drawstyle='steps-post', color='blue') self.trace.analysis.tasks.plot_task_activation(task, axis=axis, overlay=True) axis.legend() analysis.save_plot(fig, filepath=os.path.join(self.res_dir, 'ramp_boost.svg')) return axis @requires_events('sched_switch') def trace_window(self, trace): """ Skip the first phase in the trace, since it is heavily influenced by what was immediately preceding it. """ profile = self.rtapp_profile phase_duration = max( task.phases[0].duration_s for task in profile.values() ) start, end = super().trace_window(trace) return (start + phase_duration, end) @RTAEventsAnalysis.plot_slack_histogram.used_events @RTAEventsAnalysis.plot_perf_index_histogram.used_events @RTAEventsAnalysis.plot_latency.used_events @df_ramp_boost.used_events def test_ramp_boost(self, nrg_threshold_pct=0.1, bad_samples_threshold_pct=0.1) -> ResultBundle: """ Test that the energy boost feature is triggering as expected. """ # If there was no cost_margin sample to look at, that means boosting # was not exhibited by that test so we cannot conclude anything df = self.df_ramp_boost() self._plot_test_boost(df) if df.empty: return ResultBundle(Result.UNDECIDED) # Make sure the boost is always positive (negative cannot really happen # since the kernel is using unsigned arithmetic, but still check in # case there are some dataframe handling issues) assert not (df['expected_cost_margin'] < 0).any() assert not (df['cost_margin'] < 0).any() # "rect" method is accurate here since the signal is really following # "post" steps expected_boost_nrg = series_mean(df['expected_cost_margin']) actual_boost_nrg = series_mean(df['cost_margin']) # Check that the total amount of boost is close to expectations lower = max(0, expected_boost_nrg - nrg_threshold_pct) higher = expected_boost_nrg passed_overhead = lower <= actual_boost_nrg <= higher # Check the shape of the signal: actual boost must be lower or equal # than the expected one. good_shape_nr = (df['cost_margin'] <= df['expected_cost_margin']).sum() df_len = len(df) bad_shape_nr = df_len - good_shape_nr bad_shape_pct = bad_shape_nr / df_len * 100 # Tolerate a few bad samples that added too much boost passed_shape = bad_shape_pct < bad_samples_threshold_pct passed = passed_overhead and passed_shape res = ResultBundle.from_bool(passed) res.add_metric('expected boost energy overhead', expected_boost_nrg, '%') res.add_metric('boost energy overhead', actual_boost_nrg, '%') res.add_metric('bad boost samples', bad_shape_pct, '%') # Add some slack metrics and plots analysis = self.trace.analysis.rta for task in self.rtapp_tasks: analysis.plot_slack_histogram(task) analysis.plot_perf_index_histogram(task) analysis.plot_latency(task) res.add_metric('avg slack', self.get_avg_slack(), 'us') res.add_metric('avg negative slack', self.get_avg_slack(only_negative=True), 'us') return res class LargeStepUp(RampBoostTestBase): """ A single task whose utilization rises extremely quickly """ task_name = "step_up" def __init__(self, res_dir, plat_info, cpu, nr_steps): super().__init__(res_dir, plat_info, cpu=cpu) self.nr_steps = nr_steps @property def rtapp_profile(self): return self.get_rtapp_profile(self.plat_info, self.cpu, self.nr_steps) @classmethod def _from_target(cls, target:Target, *, res_dir:ArtifactPath=None, ftrace_coll:FtraceCollector=None, cpu=None, nr_steps=1) -> 'LargeStepUp': plat_info = target.plat_info # Use a big CPU by default to allow maximum range of utilization cpu = cpu if cpu is not None else plat_info["capacity-classes"][-1][0] rtapp_profile = cls.get_rtapp_profile(plat_info, cpu, nr_steps) # Ensure accurate duty cycle and idle state misprediction on some # boards. This helps having predictable execution. with target.disable_idle_states(): with target.cpufreq.use_governor("schedutil"): cls._run_rtapp(target, res_dir, rtapp_profile, ftrace_coll=ftrace_coll) return cls(res_dir, plat_info, cpu, nr_steps) @classmethod def get_rtapp_profile(cls, plat_info, cpu, nr_steps, min_util=5, max_util=75): start_pct = cls.unscaled_utilization(plat_info, cpu, min_util) end_pct = cls.unscaled_utilization(plat_info, cpu, max_util) delta_pct = ceil((end_pct - start_pct) / nr_steps) rtapp_profile = { cls.task_name : Ramp( start_pct=start_pct, end_pct=end_pct, delta_pct=delta_pct, time_s=0.3, loops=20, period_ms=cls.TASK_PERIOD_MS, # Make sure we run on one CPU only, so that we only stress # frequency scaling and not placement. cpus=[cpu], ) } return rtapp_profile
def _plot_test_boost(self, df): task = self.rtapp_tasks[0]
request.go
package parser import ( "encoding/json" "errors" "github.com/TomChv/jsonrpc2/common" "github.com/TomChv/jsonrpc2/server/validator" ) var ( ErrInvalidBody = errors.New("http request invalid body") ) // Request convert an array of byte into a valid Request object. // // If the request does not match JSON RPC specification, it returns // an error // In any case, Request will return a request struct (null or filled) to // let server returns an identifier if one is found func Request(body []byte) (*common.Request, error) { var req common.Request if err := json.Unmarshal(body, &req); err != nil {
} if err := validator.JsonRPCRequest(&req); err != nil { return &req, err } return &req, nil }
return nil, ErrInvalidBody
app.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './Components/App'; import * as serviceWorker from './serviceWorker'; import Axios from "axios"; import '../css/404.css'; import '../css/app.css'; window.laravel.csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); window.laravel.user = JSON.parse(window.laravel.user); window.axios = Axios;
'Authorization' : 'Bearer '+ window.laravel.user.api_token, 'Accept' : 'application/json' }; ReactDOM.render(<App />, document.getElementById('app')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
window.axios.defaults.baseURL = window.laravel.env.baseUrl+'/api/v1'; window.axios.defaults.headers.common = { 'X-CSRF-TOKEN': window.laravel.csrfToken, 'X-Requested-With': 'XMLHttpRequest',
error_worker.py
from aceinna.devices.base import UpgradeWorkerBase class ErrorWorker(UpgradeWorkerBase): def __init__(self): super(ErrorWorker, self).__init__() self._total = 1024*1024 # 1M size def get_upgrade_content_size(self): return self._total def work(self): current = 0 step = 200 while current < self._total: if self._is_stopped: break if current > 2000: self.emit('error', self._key, 'upgrade failed') current += step self.emit('progress', self._key, current, self._total) if current >= step: self.emit('finish', self._key) def
(self): self._is_stopped = True
stop
filter.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! FilterExec evaluates a boolean predicate against all input batches to determine which rows to //! include in its output batches. use std::sync::{Arc, Mutex}; use crate::error::{ExecutionError, Result}; use crate::execution::physical_plan::{ExecutionPlan, Partition, PhysicalExpr}; use arrow::array::BooleanArray; use arrow::compute::filter; use arrow::datatypes::{DataType, SchemaRef}; use arrow::error::Result as ArrowResult; use arrow::record_batch::{RecordBatch, RecordBatchReader}; /// FilterExec evaluates a boolean predicate against all input batches to determine which rows to /// include in its output batches. #[derive(Debug)] pub struct FilterExec { /// The expression to filter on. This expression must evaluate to a boolean value. predicate: Arc<dyn PhysicalExpr>, /// The input plan input: Arc<dyn ExecutionPlan>, } impl FilterExec { /// Create a FilterExec on an input pub fn try_new( predicate: Arc<dyn PhysicalExpr>, input: Arc<dyn ExecutionPlan>, ) -> Result<Self> { match predicate.data_type(input.schema().as_ref())? { DataType::Boolean => Ok(Self { predicate: predicate.clone(), input: input.clone(), }), other => Err(ExecutionError::General(format!( "Filter predicate must return boolean values, not {:?}", other ))), } } } impl ExecutionPlan for FilterExec { /// Get the schema for this execution plan fn schema(&self) -> SchemaRef { // The filter operator does not make any changes to the schema of its input self.input.schema() } /// Get the partitions for this execution plan fn partitions(&self) -> Result<Vec<Arc<dyn Partition>>> { let partitions: Vec<Arc<dyn Partition>> = self .input .partitions()? .iter() .map(|p| { let expr = self.predicate.clone(); let partition: Arc<dyn Partition> = Arc::new(FilterExecPartition { schema: self.input.schema(), predicate: expr, input: p.clone() as Arc<dyn Partition>, }); partition }) .collect(); Ok(partitions) } } /// Represents a single partition of a filter execution plan #[derive(Debug)] struct FilterExecPartition { /// Output schema, which is the same as the input schema for this operator schema: SchemaRef, /// The expression to filter on. This expression must evaluate to a boolean value. predicate: Arc<dyn PhysicalExpr>, /// The input partition to filter. input: Arc<dyn Partition>,
} impl Partition for FilterExecPartition { /// Execute the filter fn execute(&self) -> Result<Arc<Mutex<dyn RecordBatchReader + Send + Sync>>> { Ok(Arc::new(Mutex::new(FilterExecIter { schema: self.schema.clone(), predicate: self.predicate.clone(), input: self.input.execute()?, }))) } } /// The FilterExec iterator wraps the input iterator and applies the predicate expression to /// determine which rows to include in its output batches struct FilterExecIter { /// Output schema, which is the same as the input schema for this operator schema: SchemaRef, /// The expression to filter on. This expression must evaluate to a boolean value. predicate: Arc<dyn PhysicalExpr>, /// The input partition to filter. input: Arc<Mutex<dyn RecordBatchReader + Send + Sync>>, } impl RecordBatchReader for FilterExecIter { /// Get the schema fn schema(&self) -> SchemaRef { self.schema.clone() } /// Get the next batch fn next_batch(&mut self) -> ArrowResult<Option<RecordBatch>> { let mut input = self.input.lock().unwrap(); match input.next_batch()? { Some(batch) => { // evaluate the filter predicate to get a boolean array indicating which rows // to include in the output let result = self .predicate .evaluate(&batch) .map_err(ExecutionError::into_arrow_external_error)?; if let Some(f) = result.as_any().downcast_ref::<BooleanArray>() { // filter each array let mut filtered_arrays = Vec::with_capacity(batch.num_columns()); for i in 0..batch.num_columns() { let array = batch.column(i); let filtered_array = filter(array.as_ref(), f)?; filtered_arrays.push(filtered_array); } Ok(Some(RecordBatch::try_new( batch.schema().clone(), filtered_arrays, )?)) } else { Err(ExecutionError::InternalError( "Filter predicate evaluated to non-boolean value".to_string(), ) .into_arrow_external_error()) } } None => Ok(None), } } } #[cfg(test)] mod tests { use super::*; use crate::execution::physical_plan::csv::{CsvExec, CsvReadOptions}; use crate::execution::physical_plan::expressions::*; use crate::execution::physical_plan::ExecutionPlan; use crate::logicalplan::{Operator, ScalarValue}; use crate::test; use std::iter::Iterator; #[test] fn simple_predicate() -> Result<()> { let schema = test::aggr_test_schema(); let partitions = 4; let path = test::create_partitioned_csv("aggregate_test_100.csv", partitions)?; let csv = CsvExec::try_new(&path, CsvReadOptions::new().schema(&schema), None, 1024)?; let predicate: Arc<dyn PhysicalExpr> = binary( binary(col("c2"), Operator::Gt, lit(ScalarValue::UInt32(1))), Operator::And, binary(col("c2"), Operator::Lt, lit(ScalarValue::UInt32(4))), ); let filter: Arc<dyn ExecutionPlan> = Arc::new(FilterExec::try_new(predicate, Arc::new(csv))?); let results = test::execute(filter.as_ref())?; results .iter() .for_each(|batch| assert_eq!(13, batch.num_columns())); let row_count: usize = results.iter().map(|batch| batch.num_rows()).sum(); assert_eq!(41, row_count); Ok(()) } }
struct_cluster.go
package cassandra //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //
// Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // Cluster is a nested struct in cassandra response type Cluster struct { ClusterId string `json:"ClusterId" xml:"ClusterId"` PayType string `json:"PayType" xml:"PayType"` MaintainStartTime string `json:"MaintainStartTime" xml:"MaintainStartTime"` AutoRenewPeriod int `json:"AutoRenewPeriod" xml:"AutoRenewPeriod"` MajorVersion string `json:"MajorVersion" xml:"MajorVersion"` CreatedTime string `json:"CreatedTime" xml:"CreatedTime"` IsLatestVersion bool `json:"IsLatestVersion" xml:"IsLatestVersion"` AutoRenewal bool `json:"AutoRenewal" xml:"AutoRenewal"` MinorVersion string `json:"MinorVersion" xml:"MinorVersion"` MaintainEndTime string `json:"MaintainEndTime" xml:"MaintainEndTime"` ExpireTime string `json:"ExpireTime" xml:"ExpireTime"` ClusterName string `json:"ClusterName" xml:"ClusterName"` DataCenterCount int `json:"DataCenterCount" xml:"DataCenterCount"` Status string `json:"Status" xml:"Status"` LockMode string `json:"LockMode" xml:"LockMode"` Tags TagsInDescribeCluster `json:"Tags" xml:"Tags"` }
test_dump_kws_two_targets.py
#! /usr/bin/python3 # # Copyright (c) 2017 Intel Corporation # # SPDX-License-Identifier: Apache-2.0 # # pylint: disable = missing-docstring """Testcase using two targets -------------------------- Note n this case the target group names are listing two targets and each target obejct has different values. .. literalinclude:: /examples/test_dump_kws_two_targets.py :language: python :pyobject: _test Execute :download:`the testcase <../examples/test_dump_kws_two_targets.py>` with:: $ tcf run -vv /usr/share/tcf/examples/test_dump_kws_twp_targets.py INFO0/ato4B /usr/share/tcf/examples/test_dump_kws_two_targets.py#_test @2psg: Keywords for testcase: {'cwd': '/home/inaky/z/s/local', ...} INFO0/ato4B /usr/share/tcf/examples/test_dump_kws_two_targets.py#_test @2psg|localhost/qz33b-arm: Keywords for target 0: {u'board': u'qemu_cortex_m3', 'bsp': u'arm', u'bsp_models': {u'arm': [u'arm']}, u'bsps': {u'arm': {u'board': u'qemu_cortex_m3', u'console': u'arm', u'kernelname': u'zephyr.elf', ... u'zephyr_board': u'qemu_cortex_m3', u'zephyr_kernelname': u'zephyr.elf'} INFO0/ato4B /usr/share/tcf/examples/test_dump_kws_two_targets.py#_test @2psg|localhost/qz31a-x86: Keywords for target 1: {u'board': u'qemu_x86', 'bsp': u'x86', u'bsp_models': {u'x86': [u'x86']}, u'bsps': {u'x86': {u'board': u'qemu_x86', u'console': u'x86', u'kernelname': u'zephyr.elf', u'quark_se_stub': False, ... u'zephyr_board': u'qemu_x86', u'zephyr_kernelname': u'zephyr.elf'} PASS0/ toplevel @local: 1 tests (1 passed, 0 error, 0 failed, 0 blocked, 0 skipped, in 0:00:00.417956) - passed (depending on your installation method, location might be *~/.local/share/tcf/examples*) """ import pprint import tcfl.tc @tcfl.tc.target() @tcfl.tc.target() @tcfl.tc.tags(build_only = True, ignore_example = True) class _test(tcfl.tc.tc_c): def build(self, target, target1): self.report_info("Keywords for testcase:\n%s" % pprint.pformat(self.kws), level = 0)
% pprint.pformat(target.kws), level = 0) target1.report_info("Keywords for target 1:\n%s" % pprint.pformat(target1.kws), level = 0)
target.report_info("Keywords for target 0:\n%s"
mod.rs
use crate::types::command::create_alias_command; use crate::utils::pckg; use duckscript::types::command::Command; use duckscript::types::error::ScriptError; #[cfg(test)] #[path = "./mod_test.rs"] mod mod_test; pub(crate) fn create(package: &str) -> Result<Box<dyn Command>, ScriptError>
{ let name = pckg::concat(package, "ArrayConcat"); let command = create_alias_command( name, vec!["array_concat".to_string()], include_str!("help.md").to_string(), "array_concat".to_string(), include_str!("script.ds").to_string(), 0, )?; Ok(Box::new(command)) }
tweetconsumer.py
#!/usr/bin/env python import threading, logging, time import io import avro.schema import avro.io import pprint import kudu from kudu.client import Partitioning from kafka import KafkaConsumer pp = pprint.PrettyPrinter(indent=4,width=80) twitter_schema=''' {"namespace": "example.avro", "type": "record", "name": "StatusTweet", "fields": [ {"name": "tweet_id" , "type": "long"}, {"name": "followers_count", "type": "int"}, {"name": "statuses_count" , "type": "int"}, {"name": "id_str" , "type": "string"}, {"name": "friends_count" , "type": "int"}, {"name": "text" , "type": "string"}, {"name": "tweet_ts" , "type": "long"}, {"name": "screen_name" , "type": "string"} ] } ''' class Consumer(threading.Thread): daemon = True def __init__(self, name, partition_list ): threading.Thread.__init__(self) self.name = name self.partitions = partition_list self.client = kudu.connect(host='ip-172-31-6-171', port=7051) # Open a table self.table = self.client.table('impala::DEFAULT.STATUS_TWEETS')
# Create a new session so that we can apply write operations self.session = self.client.new_session() def run(self): consumer = KafkaConsumer(bootstrap_servers='ip-172-31-10-235:9092', auto_offset_reset='earliest', enable_auto_commit=True) consumer.subscribe(['twitterstream']) print "in run" for message in consumer: schema = avro.schema.parse(twitter_schema) bytes_reader = io.BytesIO(message.value) decoder = avro.io.BinaryDecoder(bytes_reader) reader = avro.io.DatumReader(schema) data = reader.read(decoder) print ("%s:%d:%d: key=%s %s" % (message.topic, message.partition,message.offset, message.key, data['text'][1:77] )) op = self.table.new_insert({ 'id_str' : data['id_str'] , 'tweet_ts' : data['tweet_ts'] , 'tweet_id' : data['tweet_id'] , 'followers_count' : data['followers_count'] , 'statuses_count' : data['statuses_count'] , 'friends_count' : data['friends_count'] , 'text' : data['text'] , 'screen_name' : data['screen_name'] }) self.session.apply(op) # Flush write operations, if failures occur, capture print them. try: self.session.flush() except kudu.KuduBadStatus as e: print(self.session.get_pending_errors()) def main(): threads = [ Consumer("three",(3)) ] for t in threads: t.start() time.sleep(100) if __name__ == "__main__": logging.basicConfig( format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s', level=logging.INFO ) main()
variable_statement.rs
use span::Span; use crate::variable_declaration::VariableDeclaration; #[derive(Debug, Clone)] pub struct VariableStatement {
pub declarations: Vec<VariableDeclaration>, }
pub span: Span,
event.go
package weixin import "github.com/arstd/log" // EventType 事件类型 type EventType string // RecvEvent 事件消息 type RecvEvent interface { RecvMsg } // EventBase 事件基础类 type EventBase struct { RecvMsg ToUserName string // 开发者微信号 FromUserName string // 发送方帐号(一个OpenID) CreateTime string // 消息创建时间(整型) MsgType MsgType // 消息类型,event Event EventType // 事件类型 } // NewRecvEvent 把通用 struct 转化成相应类型的 struct func NewRecvEvent(msg *Message) RecvEvent { switch msg.Event { case EventTypeSubscribe: return NewEventSubscribe(msg)
TypeUnsubscribe: return NewEventSubscribe(msg) case EventTypeLocation: return NewEventLocation(msg) case EventTypeClick: return NewEventClick(msg) case EventTypeView: return NewEventView(msg) case EventTypeScancodePush: return NewEventScancodePush(msg) case EventTypeScancodeWaitmsg: return NewEventScancodeWaitmsg(msg) case EventTypePicSysphoto: return NewEventPicSysphoto(msg) case EventTypePicPhotoOrAlbum: return NewEventPicPhotoOrAlbum(msg) case EventTypePicWeixin: return NewEventPicWeixin(msg) case EventTypeLocationSelect: return NewEventLocationSelect(msg) case EventTypeQualificationVerifySuccess: return NewEventQualificationVerifySuccess(msg) case EventTypeQualificationVerifyFail: return NewEventQualificationVerifyFail(msg) case EventTypeNamingVerifySuccess: return NewEventNamingVerifySuccess(msg) case EventTypeNamingVerifyFail: return NewEventNamingVerifyFail(msg) case EventTypeAnnualRenew: return NewEventAnnualRenew(msg) case EventTypeVerifyExpired: return NewEventVerifyExpired(msg) default: log.Errorf("unexpected receive EventType: %s", msg.Event) return nil } }
case Event
issue-25145.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass
} static STUFF: [u8; S::N] = [0; S::N]; fn main() { assert_eq!(STUFF, [0; 3]); }
struct S; impl S { const N: usize = 3;
AnalyticsMatch.js
import React, { Component, createElement } from 'react'; import { Match } from 'react-router'; import ReactGA from 'react-ga'; import { COLLECT_ANALYTICS } from '../constants'; export default class AnalyticsMatch extends Component { render() { const { path, pattern, exactly, component } = this.props; return ( <Match pattern={ pattern } exactly={ exactly } render={ (matchProps) => { if (typeof window !== 'undefined' && COLLECT_ANALYTICS) { try { ReactGA.pageview(path || window.location.pathname); } catch (err) { console.warn('can\'t contact GA'); } } return createElement(component, matchProps); } }
); } }
/>
scala_library.bzl
load("@io_bazel_rules_scala//scala:providers.bzl", "create_scala_provider") load( "@io_bazel_rules_scala//scala/private:common.bzl", "collect_jars", "collect_srcjars", "sanitize_string_for_usage", "write_manifest", ) load( "@io_bazel_rules_scala//scala/private:common_attributes.bzl", "common_attrs", "common_attrs_for_plugin_bootstrapping", "implicit_deps", "resolve_deps", ) load("@io_bazel_rules_scala//scala/private:common_outputs.bzl", "common_outputs") load( "@io_bazel_rules_scala//scala/private:coverage_replacements_provider.bzl", _coverage_replacements_provider = "coverage_replacements_provider", ) load( "@io_bazel_rules_scala//scala/private:rule_impls.bzl", "collect_jars_from_common_ctx", "compile_or_empty", "get_scalac_provider", "get_unused_dependency_checker_mode", "merge_jars", "pack_source_jars", ) ## # Common stuff to _library rules ## _library_attrs = { "main_class": attr.string(), "exports": attr.label_list( allow_files = False, aspects = [_coverage_replacements_provider.aspect], ), } def _lib( ctx, base_classpath, non_macro_lib, unused_dependency_checker_mode, unused_dependency_checker_ignored_targets): # Build up information from dependency-like attributes # This will be used to pick up srcjars from non-scala library # targets (like thrift code generation) srcjars = collect_srcjars(ctx.attr.deps) unused_dependency_checker_is_off = unused_dependency_checker_mode == "off" jars = collect_jars_from_common_ctx( ctx, base_classpath, unused_dependency_checker_is_off = unused_dependency_checker_is_off, ) (cjars, transitive_rjars) = (jars.compile_jars, jars.transitive_runtime_jars) write_manifest(ctx) outputs = compile_or_empty( ctx, ctx.outputs.manifest, cjars, srcjars, non_macro_lib, jars.transitive_compile_jars, jars.jars2labels.jars_to_labels, [], unused_dependency_checker_ignored_targets = [ target.label for target in base_classpath + ctx.attr.exports + unused_dependency_checker_ignored_targets ], unused_dependency_checker_mode = unused_dependency_checker_mode, deps_providers = jars.deps_providers, ) transitive_rjars = depset(outputs.full_jars, transitive = [transitive_rjars]) merge_jars( actions = ctx.actions, deploy_jar = ctx.outputs.deploy_jar, singlejar_executable = ctx.executable._singlejar, jars_list = transitive_rjars.to_list(), main_class = getattr(ctx.attr, "main_class", ""), progress_message = "Merging Scala library jar: %s" % ctx.label, ) # Using transitive_files since transitive_rjars a depset and avoiding linearization runfiles = ctx.runfiles( transitive_files = transitive_rjars, collect_data = True, ) # Add information from exports (is key that AFTER all build actions/runfiles analysis) # Since after, will not show up in deploy_jar or old jars runfiles # Notice that compile_jars is intentionally transitive for exports exports_jars = collect_jars(ctx.attr.exports) transitive_rjars = depset( transitive = [transitive_rjars, exports_jars.transitive_runtime_jars], ) source_jars = pack_source_jars(ctx) + outputs.source_jars scalaattr = create_scala_provider( class_jar = outputs.class_jar, compile_jars = depset( outputs.ijars, transitive = [exports_jars.compile_jars], ), deploy_jar = ctx.outputs.deploy_jar, full_jars = outputs.full_jars, ijar = outputs.ijar, source_jars = source_jars, statsfile = ctx.outputs.statsfile, transitive_runtime_jars = transitive_rjars, ) return struct( files = depset([ctx.outputs.jar] + outputs.full_jars), # Here is the default output instrumented_files = outputs.coverage.instrumented_files, jars_to_labels = jars.jars2labels, providers = [outputs.merged_provider, jars.jars2labels] + outputs.coverage.providers, runfiles = runfiles, scala = scalaattr, ) ## # scala_library ## def _scala_library_impl(ctx): if ctx.attr.jvm_flags: print("'jvm_flags' for scala_library is deprecated. It does nothing today and will be removed from scala_library to avoid confusion.") scalac_provider = get_scalac_provider(ctx) unused_dependency_checker_mode = get_unused_dependency_checker_mode(ctx) return _lib( ctx, scalac_provider.default_classpath, True, unused_dependency_checker_mode, ctx.attr.unused_dependency_checker_ignored_targets, ) _scala_library_attrs = {} _scala_library_attrs.update(implicit_deps) _scala_library_attrs.update(common_attrs) _scala_library_attrs.update(_library_attrs) _scala_library_attrs.update(resolve_deps) scala_library = rule( attrs = _scala_library_attrs, fragments = ["java"], outputs = common_outputs, toolchains = ["@io_bazel_rules_scala//scala:toolchain_type"], implementation = _scala_library_impl, ) # Scala library suite generates a series of scala libraries # then it depends on them with a meta one which exports all the sub targets def scala_library_suite( name, srcs = [], exports = [], visibility = None, **kwargs): ts = [] for src_file in srcs: n = "%s_lib_%s" % (name, sanitize_string_for_usage(src_file)) scala_library( name = n, srcs = [src_file], visibility = visibility, exports = exports, unused_dependency_checker_mode = "off", **kwargs ) ts.append(n) scala_library( name = name, visibility = visibility, exports = exports + ts, deps = ts, ) ## # scala_library_for_plugin_bootstrapping ## def _scala_library_for_plugin_bootstrapping_impl(ctx): scalac_provider = get_scalac_provider(ctx) return _lib( ctx, scalac_provider.default_classpath, True, unused_dependency_checker_ignored_targets = [], unused_dependency_checker_mode = "off", ) # the scala compiler plugin used for dependency analysis is compiled using `scala_library`. # in order to avoid cyclic dependencies `scala_library_for_plugin_bootstrapping` was created for this purpose, # which does not contain plugin related attributes, and thus avoids the cyclic dependency issue _scala_library_for_plugin_bootstrapping_attrs = {} _scala_library_for_plugin_bootstrapping_attrs.update(implicit_deps) _scala_library_for_plugin_bootstrapping_attrs.update(_library_attrs) _scala_library_for_plugin_bootstrapping_attrs.update(resolve_deps) _scala_library_for_plugin_bootstrapping_attrs.update( common_attrs_for_plugin_bootstrapping, ) scala_library_for_plugin_bootstrapping = rule( attrs = _scala_library_for_plugin_bootstrapping_attrs, fragments = ["java"], outputs = common_outputs, toolchains = ["@io_bazel_rules_scala//scala:toolchain_type"], implementation = _scala_library_for_plugin_bootstrapping_impl, ) ## # scala_macro_library ## def _scala_macro_library_impl(ctx): scalac_provider = get_scalac_provider(ctx) unused_dependency_checker_mode = get_unused_dependency_checker_mode(ctx) return _lib( ctx, scalac_provider.default_macro_classpath, False, # don't build the ijar for macros unused_dependency_checker_mode, ctx.attr.unused_dependency_checker_ignored_targets, ) _scala_macro_library_attrs = { "main_class": attr.string(), "exports": attr.label_list(allow_files = False), } _scala_macro_library_attrs.update(implicit_deps) _scala_macro_library_attrs.update(common_attrs) _scala_macro_library_attrs.update(_library_attrs) _scala_macro_library_attrs.update(resolve_deps)
# Set unused_dependency_checker_mode default to off for scala_macro_library _scala_macro_library_attrs["unused_dependency_checker_mode"] = attr.string( default = "off", values = [ "warn", "error", "off", "", ], mandatory = False, ) scala_macro_library = rule( attrs = _scala_macro_library_attrs, fragments = ["java"], outputs = common_outputs, toolchains = ["@io_bazel_rules_scala//scala:toolchain_type"], implementation = _scala_macro_library_impl, )
restrict.ts
// Dependencies import { Telegraf, ContextMessageUpdate, Extra } from 'telegraf' import { strings } from '../helpers/strings' import { checkLock } from '../middlewares/checkLock' export function
(bot: Telegraf<ContextMessageUpdate>) { bot.command('restrict', checkLock, async ctx => { let chat = ctx.dbchat chat.restrict = !chat.restrict chat = await chat.save() ctx.replyWithMarkdown( strings(ctx.dbchat, chat.restrict ? 'restrict_true' : 'restrict_false'), Extra.inReplyTo(ctx.message.message_id) ) }) }
setupRestrict
lol_player_behavior_notification_source.rs
/* * * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * Generated by: https://openapi-generator.tech */ /// #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum
{ #[serde(rename = "Invalid")] Invalid, #[serde(rename = "Login")] Login, #[serde(rename = "ForcedShutdown")] ForcedShutdown, #[serde(rename = "Message")] Message, }
LolPlayerBehaviorNotificationSource
preprocess.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Data pre-processing: build vocabularies and binarize training data. """ import logging import os import shutil import sys from collections import Counter from itertools import zip_longest from multiprocessing import Pool from fairseq import options, tasks, utils from fairseq.binarizer import Binarizer from fairseq.data import indexed_dataset from fairseq.file_chunker_utils import find_offsets logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) logger = logging.getLogger("fairseq_cli.preprocess") def
(args): utils.import_user_module(args) os.makedirs(args.destdir, exist_ok=True) logger.addHandler( logging.FileHandler( filename=os.path.join(args.destdir, "preprocess.log"), ) ) logger.info(args) task = tasks.get_task(args.task) def train_path(lang): return "{}{}".format(args.trainpref, ("." + lang) if lang else "") def file_name(prefix, lang): fname = prefix if lang is not None: fname += ".{lang}".format(lang=lang) return fname def dest_path(prefix, lang): return os.path.join(args.destdir, file_name(prefix, lang)) def dict_path(lang): return dest_path("dict", lang) + ".txt" def build_dictionary(filenames, src=False, tgt=False): assert src ^ tgt return task.build_dictionary( filenames, workers=args.workers, threshold=args.thresholdsrc if src else args.thresholdtgt, nwords=args.nwordssrc if src else args.nwordstgt, padding_factor=args.padding_factor, ) target = not args.only_source if not args.srcdict and os.path.exists(dict_path(args.source_lang)): raise FileExistsError(dict_path(args.source_lang)) if target and not args.tgtdict and os.path.exists(dict_path(args.target_lang)): raise FileExistsError(dict_path(args.target_lang)) if args.joined_dictionary: assert ( not args.srcdict or not args.tgtdict ), "cannot use both --srcdict and --tgtdict with --joined-dictionary" if args.srcdict: src_dict = task.load_dictionary(args.srcdict) elif args.tgtdict: src_dict = task.load_dictionary(args.tgtdict) else: assert ( args.trainpref ), "--trainpref must be set if --srcdict is not specified" src_dict = build_dictionary( {train_path(lang) for lang in [args.source_lang, args.target_lang]}, src=True, ) tgt_dict = src_dict else: if args.srcdict: src_dict = task.load_dictionary(args.srcdict) else: assert ( args.trainpref ), "--trainpref must be set if --srcdict is not specified" src_dict = build_dictionary([train_path(args.source_lang)], src=True) if target: if args.tgtdict: tgt_dict = task.load_dictionary(args.tgtdict) else: assert ( args.trainpref ), "--trainpref must be set if --tgtdict is not specified" tgt_dict = build_dictionary([train_path(args.target_lang)], tgt=True) else: tgt_dict = None src_dict.save(dict_path(args.source_lang)) if target and tgt_dict is not None: tgt_dict.save(dict_path(args.target_lang)) if args.dict_only: return def make_binary_dataset(vocab, input_prefix, output_prefix, lang, num_workers): logger.info("[{}] Dictionary: {} types".format(lang, len(vocab))) n_seq_tok = [0, 0] replaced = Counter() def merge_result(worker_result): replaced.update(worker_result["replaced"]) n_seq_tok[0] += worker_result["nseq"] n_seq_tok[1] += worker_result["ntok"] input_file = "{}{}".format( input_prefix, ("." + lang) if lang is not None else "" ) offsets = find_offsets(input_file, num_workers) (first_chunk, *more_chunks) = zip(offsets, offsets[1:]) pool = None if num_workers > 1: pool = Pool(processes=num_workers - 1) for worker_id, (start_offset, end_offset) in enumerate( more_chunks, start=1 ): prefix = "{}{}".format(output_prefix, worker_id) pool.apply_async( binarize, ( args, input_file, vocab, prefix, lang, start_offset, end_offset, ), callback=merge_result, ) pool.close() ds = indexed_dataset.make_builder( dataset_dest_file(args, output_prefix, lang, "bin"), impl=args.dataset_impl, vocab_size=len(vocab), ) merge_result( Binarizer.binarize( input_file, vocab, lambda t: ds.add_item(t), offset=first_chunk[0], end=first_chunk[1], ) ) if num_workers > 1: pool.join() for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) temp_file_path = dataset_dest_prefix(args, prefix, lang) ds.merge_file_(temp_file_path) os.remove(indexed_dataset.data_file_path(temp_file_path)) os.remove(indexed_dataset.index_file_path(temp_file_path)) ds.finalize(dataset_dest_file(args, output_prefix, lang, "idx")) logger.info( "[{}] {}: {} sents, {} tokens, {:.3}% replaced by {}".format( lang, input_file, n_seq_tok[0], n_seq_tok[1], 100 * sum(replaced.values()) / n_seq_tok[1], vocab.unk_word, ) ) def make_binary_alignment_dataset(input_prefix, output_prefix, num_workers): nseq = [0] def merge_result(worker_result): nseq[0] += worker_result["nseq"] input_file = input_prefix offsets = find_offsets(input_file, num_workers) (first_chunk, *more_chunks) = zip(offsets, offsets[1:]) pool = None if num_workers > 1: pool = Pool(processes=num_workers - 1) for worker_id, (start_offset, end_offset) in enumerate( more_chunks, start=1 ): prefix = "{}{}".format(output_prefix, worker_id) pool.apply_async( binarize_alignments, ( args, input_file, utils.parse_alignment, prefix, start_offset, end_offset, ), callback=merge_result, ) pool.close() ds = indexed_dataset.make_builder( dataset_dest_file(args, output_prefix, None, "bin"), impl=args.dataset_impl ) merge_result( Binarizer.binarize_alignments( input_file, utils.parse_alignment, lambda t: ds.add_item(t), offset=first_chunk[0], end=first_chunk[1], ) ) if num_workers > 1: pool.join() for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) temp_file_path = dataset_dest_prefix(args, prefix, None) ds.merge_file_(temp_file_path) os.remove(indexed_dataset.data_file_path(temp_file_path)) os.remove(indexed_dataset.index_file_path(temp_file_path)) ds.finalize(dataset_dest_file(args, output_prefix, None, "idx")) logger.info("[alignments] {}: parsed {} alignments".format(input_file, nseq[0])) def make_dataset(vocab, input_prefix, output_prefix, lang, num_workers=1): if args.dataset_impl == "raw": # Copy original text file to destination folder output_text_file = dest_path( output_prefix + ".{}-{}".format(args.source_lang, args.target_lang), lang, ) shutil.copyfile(file_name(input_prefix, lang), output_text_file) else: make_binary_dataset(vocab, input_prefix, output_prefix, lang, num_workers) def make_all(lang, vocab): if args.trainpref: make_dataset(vocab, args.trainpref, "train", lang, num_workers=args.workers) if args.validpref: for k, validpref in enumerate(args.validpref.split(",")): outprefix = "valid{}".format(k) if k > 0 else "valid" make_dataset( vocab, validpref, outprefix, lang, num_workers=args.workers ) if args.testpref: for k, testpref in enumerate(args.testpref.split(",")): outprefix = "test{}".format(k) if k > 0 else "test" make_dataset(vocab, testpref, outprefix, lang, num_workers=args.workers) def make_all_alignments(): if args.trainpref and os.path.exists(args.trainpref + "." + args.align_suffix): make_binary_alignment_dataset( args.trainpref + "." + args.align_suffix, "train.align", num_workers=args.workers, ) if args.validpref and os.path.exists(args.validpref + "." + args.align_suffix): make_binary_alignment_dataset( args.validpref + "." + args.align_suffix, "valid.align", num_workers=args.workers, ) if args.testpref and os.path.exists(args.testpref + "." + args.align_suffix): make_binary_alignment_dataset( args.testpref + "." + args.align_suffix, "test.align", num_workers=args.workers, ) make_all(args.source_lang, src_dict) if target: make_all(args.target_lang, tgt_dict) if args.align_suffix: make_all_alignments() logger.info("Wrote preprocessed data to {}".format(args.destdir)) if args.alignfile: assert args.trainpref, "--trainpref must be set if --alignfile is specified" src_file_name = train_path(args.source_lang) tgt_file_name = train_path(args.target_lang) freq_map = {} with open(args.alignfile, "r", encoding="utf-8") as align_file: with open(src_file_name, "r", encoding="utf-8") as src_file: with open(tgt_file_name, "r", encoding="utf-8") as tgt_file: for a, s, t in zip_longest(align_file, src_file, tgt_file): si = src_dict.encode_line(s, add_if_not_exist=False) ti = tgt_dict.encode_line(t, add_if_not_exist=False) ai = list(map(lambda x: tuple(x.split("-")), a.split())) for sai, tai in ai: srcidx = si[int(sai)] tgtidx = ti[int(tai)] if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk(): assert srcidx != src_dict.pad() assert srcidx != src_dict.eos() assert tgtidx != tgt_dict.pad() assert tgtidx != tgt_dict.eos() if srcidx not in freq_map: freq_map[srcidx] = {} if tgtidx not in freq_map[srcidx]: freq_map[srcidx][tgtidx] = 1 else: freq_map[srcidx][tgtidx] += 1 align_dict = {} for srcidx in freq_map.keys(): align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get) with open( os.path.join( args.destdir, "alignment.{}-{}.txt".format(args.source_lang, args.target_lang), ), "w", encoding="utf-8", ) as f: for k, v in align_dict.items(): print("{} {}".format(src_dict[k], tgt_dict[v]), file=f) def binarize(args, filename, vocab, output_prefix, lang, offset, end, append_eos=True): ds = indexed_dataset.make_builder( dataset_dest_file(args, output_prefix, lang, "bin"), impl=args.dataset_impl, vocab_size=len(vocab), ) def consumer(tensor): ds.add_item(tensor) res = Binarizer.binarize( filename, vocab, consumer, append_eos=append_eos, offset=offset, end=end ) ds.finalize(dataset_dest_file(args, output_prefix, lang, "idx")) return res def binarize_alignments(args, filename, parse_alignment, output_prefix, offset, end): ds = indexed_dataset.make_builder( dataset_dest_file(args, output_prefix, None, "bin"), impl=args.dataset_impl, vocab_size=None, ) def consumer(tensor): ds.add_item(tensor) res = Binarizer.binarize_alignments( filename, parse_alignment, consumer, offset=offset, end=end ) ds.finalize(dataset_dest_file(args, output_prefix, None, "idx")) return res def dataset_dest_prefix(args, output_prefix, lang): base = "{}/{}".format(args.destdir, output_prefix) if lang is not None: lang_part = ".{}-{}.{}".format(args.source_lang, args.target_lang, lang) elif args.only_source: lang_part = "" else: lang_part = ".{}-{}".format(args.source_lang, args.target_lang) return "{}{}".format(base, lang_part) def dataset_dest_file(args, output_prefix, lang, extension): base = dataset_dest_prefix(args, output_prefix, lang) return "{}.{}".format(base, extension) def cli_main(): parser = options.get_preprocessing_parser() args = parser.parse_args() main(args) if __name__ == "__main__": cli_main()
main
__init__.py
import os def getEnv(name,default=None): value = os.environ.get(name,None)
if default == None: value = input("Env variable not found, please enter {}: ".format(name)) else: value = default return value
if value == None:
mainwindow.py
# -*- coding: utf-8 -*- """ twikoto3 - Twitter Client Copyright (C) 2012 azyobuzin This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from PyQt4 import QtCore, QtGui import twikoto3 from twikoto3.extension import * from twikoto3.twittertext import validator class TweetTextEdit(QtGui.QTextEdit): def
(self, parent = None): super(TweetTextEdit, self).__init__(parent) self.tweetaction = None def keyPressEvent(self, e): if e.key() == QtCore.Qt.Key_Return and (e.modifiers() and QtCore.Qt.ControlModifier): self.tweetaction() else: super(TweetTextEdit, self).keyPressEvent(e) class MainWindow(QtGui.QMainWindow): def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.setWindowTitle("ついこと 3") self.layout = QtGui.QVBoxLayout() self.textedit_tweet = TweetTextEdit() self.textedit_tweet.setMinimumHeight(46) self.textedit_tweet.textChanged.connect(self.textedit_tweet_textChanged) self.textedit_tweet.tweetaction = self.button_tweet_clicked self.layout.addWidget(self.textedit_tweet) self.layout_tweetbutton = QtGui.QHBoxLayout() self.layout.addLayout(self.layout_tweetbutton) self.label_textcount = QtGui.QLabel("140") self.layout_tweetbutton.addWidget(self.label_textcount) self.button_tweet = QtGui.QPushButton("Tweet") self.button_tweet.clicked.connect(self.button_tweet_clicked) self.layout_tweetbutton.addWidget(self.button_tweet) self.centralWidget = QtGui.QWidget() self.centralWidget.setLayout(self.layout) self.setCentralWidget(self.centralWidget) def button_tweet_clicked(self): status = self.textedit_tweet.toPlainText() if status | noneoremptystr(): return self.button_tweet.setEnabled(False) thread = twikoto3.twitter.updatestatus(status) def finished(): self.button_tweet.setEnabled(True) if thread.response is not None: self.textedit_tweet.setPlainText("") else: QtGui.QMessageBox.critical(self, "投稿失敗", str(thread.exception)) thread.finished.connect(finished) thread.start() def textedit_tweet_textChanged(self): self.label_textcount.setText(str(validator.MAX_TWEET_LENGTH - validator.getTweetLength(self.textedit_tweet.toPlainText()))) instance = None def getinstance(): if MainWindow.instance is None: MainWindow.instance = MainWindow() return MainWindow.instance
__init__
getApplicationSecurityGroup.ts
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../../types"; import * as utilities from "../../utilities"; /** * An application security group in a resource group. * Latest API Version: 2020-08-01. */ /** @deprecated The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:network:getApplicationSecurityGroup'. */ export function
(args: GetApplicationSecurityGroupArgs, opts?: pulumi.InvokeOptions): Promise<GetApplicationSecurityGroupResult> { pulumi.log.warn("getApplicationSecurityGroup is deprecated: The 'latest' version is deprecated. Please migrate to the function in the top-level module: 'azure-native:network:getApplicationSecurityGroup'.") if (!opts) { opts = {} } if (!opts.version) { opts.version = utilities.getVersion(); } return pulumi.runtime.invoke("azure-native:network/latest:getApplicationSecurityGroup", { "applicationSecurityGroupName": args.applicationSecurityGroupName, "resourceGroupName": args.resourceGroupName, }, opts); } export interface GetApplicationSecurityGroupArgs { /** * The name of the application security group. */ readonly applicationSecurityGroupName: string; /** * The name of the resource group. */ readonly resourceGroupName: string; } /** * An application security group in a resource group. */ export interface GetApplicationSecurityGroupResult { /** * A unique read-only string that changes whenever the resource is updated. */ readonly etag: string; /** * Resource ID. */ readonly id?: string; /** * Resource location. */ readonly location?: string; /** * Resource name. */ readonly name: string; /** * The provisioning state of the application security group resource. */ readonly provisioningState: string; /** * The resource GUID property of the application security group resource. It uniquely identifies a resource, even if the user changes its name or migrate the resource across subscriptions or resource groups. */ readonly resourceGuid: string; /** * Resource tags. */ readonly tags?: {[key: string]: string}; /** * Resource type. */ readonly type: string; }
getApplicationSecurityGroup
train.py
import requests import urllib.parse import base64 import json import io import numpy as np from PIL import Image import cv2.cv2 as cv from solve import * def
(): imgTop = np.empty((50, 0)) imgBottom = np.empty((50, 0)) for char in alphabet[:16]: imgTop = np.append(imgTop, np.min(trained_key[char], axis=0), axis=1) for char in alphabet[16:]: imgBottom = np.append(imgBottom, np.min(trained_key[char], axis=0), axis=1) img = np.rot90(np.append(np.rot90(imgTop), np.rot90(imgBottom), axis=1), 3) cv.imshow("alphabet", img) combine_and_show_alphabet() lastchar = 0 count = 0 cheat_amount = 0 while True: captcha = get_captcha() solution = list(captcha[2]) captcha_no_overlay = remove_overlay(captcha) chars = [] for i in range(5): chars.append(captcha_no_overlay[:, i * 40 : (i + 1) * 40]) while len(chars) != 0: cv.imshow("character", chars[0]) if cheat_amount <= 0: key = cv.waitKey(0) else: key = ord(solution[0].lower()) if key not in [ord(char) for char in alphabet.lower()] + [8, 13, 27, 225]: continue if key == 8: # backspace trained_key[lastchar].pop() combine_and_show_alphabet() elif key == 27: # escape for char in alphabet: cv.imwrite("training/%s.png" % char, np.min(trained_key[char], axis=0)) cv.destroyAllWindows() exit() elif key == 13: # enter for char in alphabet: cv.imwrite("training/%s.png" % char, np.min(trained_key[char], axis=0)) elif key == 225: # left shift key = ord(solution[0].lower()) cheat_amount = 10 if key not in [8, 13, 27, 225]: trained_key[chr(key).upper()].append(chars[0]) chars.pop(0) solution.pop(0) lastchar = chr(key).upper() combine_and_show_alphabet() count += 1 cheat_amount -= 1 print(count)
combine_and_show_alphabet
logger.go
package engine import ( "github.com/didi/nightingale/v5/src/models" "github.com/toolkits/pkg/logger" ) func
(event *models.AlertCurEvent, location string, err ...error) { status := "triggered" if event.IsRecovered { status = "recovered" } message := "" if len(err) > 0 && err[0] != nil { message = "error_message: " + err[0].Error() } logger.Infof( "event(%s %s) %s: rule_id=%d %v%s@%d %s", event.Hash, status, location, event.RuleId, event.TagsJSON, event.TriggerValue, event.TriggerTime, message, ) }
LogEvent
jakfp_dataset.py
import os import pandas as pd from chemreader.writers import GraphWriter from chemreader.readers import Smiles from rdkit.Chem import MolFromSmiles from slgnn.models.gcn.utils import get_filtered_fingerprint from tqdm import tqdm def _is_active(value): if value < 1000: return 1 elif value >= 10000: return -1 else: return 0 def filter_(path):
def write_graphs(inpath, outpath, prefix=None): """ Convert JAK dataset to graphs """ smiles = list() fps = list() pb = tqdm() with open(inpath, "r") as inf: line = inf.readline() while line: _, sm, _ = line.strip().split(",") if MolFromSmiles(sm) is None: line = inf.readline() continue smiles.append(Smiles(sm)) fps.append(",".join(map(str, get_filtered_fingerprint(sm)))) pb.update(1) line = inf.readline() writer = GraphWriter(smiles) writer.write(outpath, prefix=prefix, graph_labels=fps) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("-p", "--path", help="Path to the JAK file") args = parser.parse_args() filter_(args.path) inpath = os.path.join( os.path.dirname(args.path), "filtered_" + os.path.basename(args.path) ) pre = os.path.basename(args.path).split(".")[0] + "FP" write_graphs(inpath, os.path.join(os.path.dirname(args.path), "graphs"), prefix=pre)
""" Filter JAK dataset """ jak = pd.read_csv(path) jak.dropna(subset=["Standard Relation", "Standard Value"], inplace=True) not_eq = jak["Standard Relation"] != "'='" lt_10um = jak["Standard Value"] < 100000 filtered = jak.drop(jak.loc[not_eq & lt_10um].index) gt = jak["Standard Relation"] == "'>'" eq_1um = jak["Standard Value"] >= 1000 add_back = jak.loc[gt & eq_1um] filtered = filtered.append(add_back) filtered["Activity"] = filtered["Standard Value"].apply(_is_active) out_path = os.path.join(os.path.dirname(path), "filtered_" + os.path.basename(path)) filtered[["Smiles", "Activity"]].to_csv(out_path)
_subscriptions_operations_async.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class SubscriptionsOperations: """SubscriptionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.resource.subscriptions.v2016_06_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def list_locations( self, subscription_id: str, **kwargs ) -> AsyncIterable["models.LocationListResult"]: """Gets all available geo-locations. This operation provides all the locations that are available for resource providers; however, each resource provider may support a subset of this list. :param subscription_id: The ID of the target subscription. :type subscription_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either LocationListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.v2016_06_01.models.LocationListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.LocationListResult"] error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = "2016-06-01" def prepare_request(next_link=None): if not next_link: # Construct URL url = self.list_locations.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') else: url = next_link query_parameters = {} # type: Dict[str, Any] # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('LocationListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_locations.metadata = {'url': '/subscriptions/{subscriptionId}/locations'} # type: ignore async def get( self, subscription_id: str, **kwargs ) -> "models.Subscription": """Gets details about a specified subscription. :param subscription_id: The ID of the target subscription. :type subscription_id: str :keyword callable cls: A custom type or function that will be passed the direct response :return: Subscription, or the result of cls(response) :rtype: ~azure.mgmt.resource.subscriptions.v2016_06_01.models.Subscription :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.Subscription"] error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = "2016-06-01" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("subscription_id", subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json'
# Construct and send request request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize('Subscription', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}'} # type: ignore def list( self, **kwargs ) -> AsyncIterable["models.SubscriptionListResult"]: """Gets all subscriptions for a tenant. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either SubscriptionListResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.resource.subscriptions.v2016_06_01.models.SubscriptionListResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["models.SubscriptionListResult"] error_map = {404: ResourceNotFoundError, 409: ResourceExistsError} error_map.update(kwargs.pop('error_map', {})) api_version = "2016-06-01" def prepare_request(next_link=None): if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') else: url = next_link query_parameters = {} # type: Dict[str, Any] # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = 'application/json' # Construct and send request request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('SubscriptionListResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions'} # type: ignore
mod.rs
use diesel::*; use schema::TestBackend; #[test] fn
() { use schema::users::dsl::*; let sql = debug_query::<TestBackend, _>(&users.count()).to_string(); if cfg!(feature = "postgres") { assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#); } else { assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []"); } } #[test] fn test_debug_output() { use schema::users::dsl::*; let command = update(users.filter(id.eq(1))).set(name.eq("new_name")); let sql = debug_query::<TestBackend, _>(&command).to_string(); if cfg!(feature = "postgres") { assert_eq!( sql, r#"UPDATE "users" SET "name" = $1 WHERE "users"."id" = $2 -- binds: ["new_name", 1]"# ) } else { assert_eq!( sql, r#"UPDATE `users` SET `name` = ? WHERE `users`.`id` = ? -- binds: ["new_name", 1]"# ) } }
test_debug_count_output
index.tsx
import React from "react"; import { Container, Link, Box, Text, Flex, Badge, Center, Heading, Divider, } from "@chakra-ui/layout"; import { Button } from "@chakra-ui/button"; import { Link as IconLink } from "react-feather"; import { motion } from "framer-motion"; import { Cell } from "react-table"; import axios from "axios"; import { useQuery } from "react-query"; import { isEmpty } from "ramda"; import { serverSideTranslations } from "next-i18next/serverSideTranslations"; import { useTranslation } from "next-i18next"; import type { NextPage } from "next"; import constants from "../lib/constants"; import utils from "../lib/utils"; import PayPal from "../icons/PayPal"; import Remitly from "../icons/Remitly"; import WesternUnion from "../icons/WesternUnion"; import SmallWorld from "../icons/SmallWorld"; import Wise from "../icons/Wise"; import NotFoundIllustrations from "../illustrations/NotFound"; import SearchIllustrations from "../illustrations/Search"; import Table from "../components/misc/Table"; import Search from "../components/Search"; import Layout from "../components/Layout"; import Faq from "../components/Faq"; import Features from "../components/Features"; import Footer from "../components/Footer"; const Home: NextPage = () => { const { t } = useTranslation("common"); const columns = React.useMemo( () => [
}, { Header: t("transfer-fee"), accessor: "fee", Cell: function scoreCell(props: Cell) { return ( <Text fontWeight="bold">{utils.formatNumber(props.value)} EUR</Text> ); }, }, { Header: "Trust pilot", accessor: "trustPilotScore", Cell: function scoreCell(props: Cell) { return getScoreBadge(props.value); }, }, { Header: t("recipient-gets"), accessor: "recipientGets", Cell: function recipientGetsCell(props: { value: number; row: { original: { url: string } }; }) { return ( <Flex flexDirection="column"> <Text mb="2" fontWeight="bold" fontSize="md"> {utils.formatNumber(props.value)} BAM </Text> <Link href={props.row.original.url} isExternal> <Button as={motion.button} whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }} size="sm" leftIcon={<IconLink size={16} />} > {t("send-money")} </Button> </Link> </Flex> ); }, }, ], [t] ); const exchangeRatesQuery = useQuery("rates", () => axios.get("/api/latest"), { enabled: constants.IS_PROD, }); const [amount, setAmount] = React.useState(""); const exchangeRate = exchangeRatesQuery.data?.data.rates.BAM || constants.DEFAULT_EXCHANGE_RATE; function calculateRecipientGets(fee: number) { return parseFloat(amount) * exchangeRate - fee; } function getScoreBadge(score: number) { if (score >= 4) { return <Badge colorScheme="green">{score}</Badge>; } else if (score >= 3) { return <Badge colorScheme="yellow">{score}</Badge>; } return <Badge colorScheme="red">{score}</Badge>; } const data = [ { icon: ( <Box maxWidth="8em"> <Wise /> </Box> ), provider: constants.PROVIDERS.WISE.NAME, trustPilotScore: constants.PROVIDERS.WISE.TRUST_PILOT, fee: constants.PROVIDERS.WISE.FEE, recipientGets: calculateRecipientGets(constants.PROVIDERS.WISE.FEE), url: constants.PROVIDERS.WISE.URL, }, { icon: ( <Box maxWidth="8em"> <Remitly /> </Box> ), provider: constants.PROVIDERS.REMITLY.NAME, trustPilotScore: constants.PROVIDERS.REMITLY.TRUST_PILOT, fee: constants.PROVIDERS.REMITLY.FEE, recipientGets: calculateRecipientGets(constants.PROVIDERS.REMITLY.FEE), url: constants.PROVIDERS.REMITLY.URL, }, { icon: ( <Box maxWidth="8em"> <SmallWorld /> </Box> ), provider: constants.PROVIDERS.SMALL_WORLD.NAME, trustPilotScore: constants.PROVIDERS.SMALL_WORLD.TRUST_PILOT, fee: constants.PROVIDERS.SMALL_WORLD.FEE, recipientGets: calculateRecipientGets( constants.PROVIDERS.SMALL_WORLD.FEE ), url: constants.PROVIDERS.SMALL_WORLD.URL, }, { icon: ( <Box maxWidth="8em"> <WesternUnion /> </Box> ), provider: constants.PROVIDERS.WESTERN_UNION.NAME, trustPilotScore: constants.PROVIDERS.WESTERN_UNION.TRUST_PILOT, fee: constants.PROVIDERS.WESTERN_UNION.FEE, recipientGets: calculateRecipientGets( constants.PROVIDERS.WESTERN_UNION.FEE ), url: constants.PROVIDERS.WESTERN_UNION.URL, }, { icon: ( <Box maxWidth="8em"> <PayPal /> </Box> ), provider: constants.PROVIDERS.PAYPAL.NAME, trustPilotScore: constants.PROVIDERS.PAYPAL.TRUST_PILOT, fee: constants.PROVIDERS.PAYPAL.FEE, recipientGets: calculateRecipientGets(constants.PROVIDERS.PAYPAL.FEE), url: constants.PROVIDERS.PAYPAL.URL, }, ]; const ref = React.useRef<HTMLInputElement>(null); function handleOnEnterAmount() { if (ref.current) { ref.current.focus(); } } function renderBody() { if (isEmpty(amount)) { return ( <Container maxW="container.sm"> <Center mb="4"> <Box maxW="sm" width="100%"> <SearchIllustrations /> </Box> </Center> <Center> <Button colorScheme="blue" onClick={handleOnEnterAmount}> {t("enter-amount")} </Button> </Center> </Container> ); } if (parseFloat(amount) > 1000000) { return ( <Container maxW="container.sm"> <Center mb="4"> <Box maxW="sm" width="100%"> <NotFoundIllustrations /> </Box> </Center> <Text mb="2" textAlign="center"> {t("we-are-sorry-we-dont-have-comparisons-for-large-amount")} </Text> <Text mb="2" textAlign="center"> {t("we-are-sorry-we-dont-have-comparisons-for-large-amount-desc", { amount: constants.MAX_AMOUNT, })} </Text> <Center> <Button onClick={() => setAmount(String(constants.MAX_AMOUNT))}> {t("compare-sending", { amount: constants.MAX_AMOUNT })} </Button> </Center> </Container> ); } return <Table columns={columns} data={data} />; } return ( <Layout> <Box minHeight="calc(100vh - 80px)"> <Center> <Heading mb="4">{t("compare-and-save")}</Heading> </Center> <Search amount={amount} amountInputRef={ref} setAmount={setAmount} /> {renderBody()} </Box> <Features /> <Divider marginY="16" /> <Faq /> <Footer /> </Layout> ); }; export default Home; export const getStaticProps = async ({ locale }: { locale: string }) => ({ props: { ...(await serverSideTranslations(locale, ["common"])), }, });
{ Header: t("provider"), accessor: "icon",
693.binary-number-with-alternating-bits.py
# # @lc app=leetcode id=693 lang=python3 # # [693] Binary Number with Alternating Bits # # https://leetcode.com/problems/binary-number-with-alternating-bits/description/ # # algorithms # Easy (58.47%) # Likes: 359 # Dislikes: 74 # Total Accepted: 52.4K # Total Submissions: 89.1K # Testcase Example: '5' # # Given a positive integer, check whether it has alternating bits: namely, if # two adjacent bits will always have different values. # # Example 1: # # Input: 5 # Output: True # Explanation: # The binary representation of 5 is: 101 # # # # Example 2: # # Input: 7 # Output: False # Explanation: # The binary representation of 7 is: 111. # # # # Example 3: # # Input: 11 # Output: False # Explanation: # The binary representation of 11 is: 1011. # # # # Example 4: # # Input: 10 # Output: True # Explanation: # The binary representation of 10 is: 1010. # # # # @lc code=start class Solution:
# @lc code=end
def hasAlternatingBits(self, n: int) -> bool: b = list(bin(n)[2:]) if len(b)<2: return True else: return b[0]!=b[1] and len(set(b[::2]))==1 and len(set(b[1::2]))==1
useTableContext.ts
/** * Copyright Zendesk, Inc. * * Use of this source code is governed under the Apache License, Version 2.0 * found at http://www.apache.org/licenses/LICENSE-2.0. */ import React, { useContext } from 'react'; import { ITableProps } from '../types'; interface ITableContext { size: NonNullable<ITableProps['size']>; isReadOnly: NonNullable<ITableProps['isReadOnly']>; }
}); export const useTableContext = () => { return useContext(TableContext); };
export const TableContext = React.createContext<ITableContext>({ size: 'medium', isReadOnly: false
tx_pool_test.go
// Copyright 2015 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package evmcore import ( "crypto/ecdsa" "errors" "fmt" "io/ioutil" "math/big" "math/rand" "os" "testing" "time" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/rawdb" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" notify "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/params" ) // testTxPoolConfig is a transaction pool configuration without stateful disk // sideeffects used during testing. var testTxPoolConfig TxPoolConfig func init() { testTxPoolConfig = DefaultTxPoolConfig() testTxPoolConfig.Journal = "" } type testBlockChain struct { statedb *state.StateDB gasLimit uint64 chainHeadFeed *notify.Feed } func (bc *testBlockChain) MinGasPrice() *big.Int { return common.Big0 } func (bc *testBlockChain) MaxGasLimit() uint64 { return bc.CurrentBlock().GasLimit } func (bc *testBlockChain) CurrentBlock() *EvmBlock { b := &EvmBlock{} b.Number = big.NewInt(0) b.GasLimit = bc.gasLimit return b } func (bc *testBlockChain) GetBlock(hash common.Hash, number uint64) *EvmBlock { return bc.CurrentBlock() } func (bc *testBlockChain) StateAt(common.Hash) (*state.StateDB, error) { return bc.statedb, nil } func (bc *testBlockChain) SubscribeNewBlock(ch chan<- ChainHeadNotify) notify.Subscription { return bc.chainHeadFeed.Subscribe(ch) } func transaction(nonce uint64, gaslimit uint64, key *ecdsa.PrivateKey) *types.Transaction { return pricedTransaction(nonce, gaslimit, big.NewInt(1), key) } func pricedTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey) *types.Transaction { tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(100), gaslimit, gasprice, nil), types.HomesteadSigner{}, key) return tx } func pricedDataTransaction(nonce uint64, gaslimit uint64, gasprice *big.Int, key *ecdsa.PrivateKey, bytes uint64) *types.Transaction { data := make([]byte, bytes) rand.Read(data) tx, _ := types.SignTx(types.NewTransaction(nonce, common.Address{}, big.NewInt(0), gaslimit, gasprice, data), types.HomesteadSigner{}, key) return tx } func setupTxPool() (*TxPool, *ecdsa.PrivateKey) { statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 10000000, new(notify.Feed)} key, _ := crypto.GenerateKey() pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) return pool, key } // validateTxPoolInternals checks various consistency invariants within the pool. func validateTxPoolInternals(pool *TxPool) error { pool.mu.RLock() defer pool.mu.RUnlock() // Ensure the total transaction set is consistent with pending + queued pending, queued := pool.stats() if total := pool.all.Count(); total != pending+queued { return fmt.Errorf("total transaction count %d != %d pending + %d queued", total, pending, queued) } if priced := pool.priced.items.Len() - pool.priced.stales; priced != pending+queued { return fmt.Errorf("total priced transaction count %d != %d pending + %d queued", priced, pending, queued) } // Ensure the next nonce to assign is the correct one for addr, txs := range pool.pending { // Find the last transaction var last uint64 for nonce := range txs.txs.items { if last < nonce { last = nonce } } if nonce := pool.pendingNonces.get(addr); nonce != last+1 { return fmt.Errorf("pending nonce mismatch: have %v, want %v", nonce, last+1) } } return nil } // validateEvents checks that the correct number of transaction addition events // were fired on the pool's event feed. func validateEvents(events chan NewTxsNotify, count int) error { var received []*types.Transaction for len(received) < count { select { case ev := <-events: received = append(received, ev.Txs...) case <-time.After(time.Second): return fmt.Errorf("event #%d not fired", len(received)) } } if len(received) > count { return fmt.Errorf("more than %d events fired: %v", count, received[count:]) } select { case ev := <-events: return fmt.Errorf("more than %d events fired: %v", count, ev.Txs) case <-time.After(50 * time.Millisecond): // This branch should be "default", but it's a data race between goroutines, // reading the event channel and pushing into it, so better wait a bit ensuring // really nothing gets injected. } return nil } func deriveSender(tx *types.Transaction) (common.Address, error) { return types.Sender(types.HomesteadSigner{}, tx) } type testChain struct { *testBlockChain address common.Address trigger *bool } // testChain.State() is used multiple times to reset the pending state. // when simulate is true it will create a state that indicates // that tx0 and tx1 are included in the chain. func (c *testChain) State() (*state.StateDB, error) { // delay "state change" by one. The tx pool fetches the // state multiple times and by delaying it a bit we simulate // a state change between those fetches. stdb := c.statedb if *c.trigger { c.statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) // simulate that the new head block included tx0 and tx1 c.statedb.SetNonce(c.address, 2) c.statedb.SetBalance(c.address, new(big.Int).SetUint64(params.Ether)) *c.trigger = false } return stdb, nil } // This test simulates a scenario where a new block is imported during a // state reset and tests whether the pending state is in sync with the // block head event that initiated the resetState(). func TestStateChangeDuringTransactionPoolReset(t *testing.T) { t.Parallel() var ( key, _ = crypto.GenerateKey() address = crypto.PubkeyToAddress(key.PublicKey) statedb, _ = state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) trigger = false ) // setup pool with 2 transaction in it statedb.SetBalance(address, new(big.Int).SetUint64(params.Ether)) blockchain := &testChain{&testBlockChain{statedb, 1000000000, new(notify.Feed)}, address, &trigger} tx0 := transaction(0, 100000, key) tx1 := transaction(1, 100000, key) pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() nonce := pool.Nonce(address) if nonce != 0 { t.Fatalf("Invalid nonce, want 0, got %d", nonce) } pool.AddRemotesSync([]*types.Transaction{tx0, tx1}) nonce = pool.Nonce(address) if nonce != 2 { t.Fatalf("Invalid nonce, want 2, got %d", nonce) } // trigger state change in the background trigger = true <-pool.requestReset(nil, nil) _, err := pool.Pending() if err != nil { t.Fatalf("Could not fetch pending transactions: %v", err) } nonce = pool.Nonce(address) if nonce != 2 { t.Fatalf("Invalid nonce, want 2, got %d", nonce) } } func TestInvalidTransactions(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() tx := transaction(0, 100, key) from, _ := deriveSender(tx) pool.currentState.AddBalance(from, big.NewInt(1)) if err := pool.AddRemote(tx); err != ErrInsufficientFunds { t.Error("expected", ErrInsufficientFunds) } balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(new(big.Int).SetUint64(tx.Gas()), tx.GasPrice())) pool.currentState.AddBalance(from, balance) if err := pool.AddRemote(tx); !errors.Is(err, ErrIntrinsicGas) { t.Error("expected", ErrIntrinsicGas, "got", err) } pool.currentState.SetNonce(from, 1) pool.currentState.AddBalance(from, big.NewInt(0xffffffffffffff)) tx = transaction(0, 100000, key) if err := pool.AddRemote(tx); err != ErrNonceTooLow { t.Error("expected", ErrNonceTooLow) } tx = transaction(1, 100000, key) pool.gasPrice = big.NewInt(1000) if err := pool.AddRemote(tx); err != ErrUnderpriced { t.Error("expected", ErrUnderpriced, "got", err) } if err := pool.AddLocal(tx); err != nil { t.Error("expected", nil, "got", err) } } func TestTransactionQueue(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() tx := transaction(0, 100, key) from, _ := deriveSender(tx) pool.currentState.AddBalance(from, big.NewInt(1000)) <-pool.requestReset(nil, nil) pool.enqueueTx(tx.Hash(), tx) <-pool.requestPromoteExecutables(newAccountSet(pool.signer, from)) if len(pool.pending) != 1 { t.Error("expected valid txs to be 1 is", len(pool.pending)) } tx = transaction(1, 100, key) from, _ = deriveSender(tx) pool.currentState.SetNonce(from, 2) pool.enqueueTx(tx.Hash(), tx) <-pool.requestPromoteExecutables(newAccountSet(pool.signer, from)) if _, ok := pool.pending[from].txs.items[tx.Nonce()]; ok { t.Error("expected transaction to be in tx pool") } if len(pool.queue) > 0 { t.Error("expected transaction queue to be empty. is", len(pool.queue)) } } func TestTransactionQueue2(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() tx1 := transaction(0, 100, key) tx2 := transaction(10, 100, key) tx3 := transaction(11, 100, key) from, _ := deriveSender(tx1) pool.currentState.AddBalance(from, big.NewInt(1000)) pool.reset(nil, nil) pool.enqueueTx(tx1.Hash(), tx1) pool.enqueueTx(tx2.Hash(), tx2) pool.enqueueTx(tx3.Hash(), tx3) pool.promoteExecutables([]common.Address{from}) if len(pool.pending) != 1 { t.Error("expected pending length to be 1, got", len(pool.pending)) } if pool.queue[from].Len() != 2 { t.Error("expected len(queue) == 2, got", pool.queue[from].Len()) } } func TestTransactionNegativeValue(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() tx, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(-1), 100, big.NewInt(1), nil), types.HomesteadSigner{}, key) from, _ := deriveSender(tx) pool.currentState.AddBalance(from, big.NewInt(1)) if err := pool.AddRemote(tx); err != ErrNegativeValue { t.Error("expected", ErrNegativeValue, "got", err) } } func TestTransactionChainFork(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() addr := crypto.PubkeyToAddress(key.PublicKey) resetState := func() { statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) statedb.AddBalance(addr, big.NewInt(100000000000000)) pool.chain = &testBlockChain{statedb, 1000000, new(notify.Feed)} <-pool.requestReset(nil, nil) } resetState() tx := transaction(0, 100000, key) if _, err := pool.add(tx, false); err != nil { t.Error("didn't expect error", err) } pool.removeTx(tx.Hash(), true) // reset the pool's internal state resetState() if _, err := pool.add(tx, false); err != nil { t.Error("didn't expect error", err) } } func TestTransactionDoubleNonce(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() addr := crypto.PubkeyToAddress(key.PublicKey) resetState := func() { statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) statedb.AddBalance(addr, big.NewInt(100000000000000)) pool.chain = &testBlockChain{statedb, 1000000, new(notify.Feed)} <-pool.requestReset(nil, nil) } resetState() signer := types.HomesteadSigner{} tx1, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 100000, big.NewInt(1), nil), signer, key) tx2, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(2), nil), signer, key) tx3, _ := types.SignTx(types.NewTransaction(0, common.Address{}, big.NewInt(100), 1000000, big.NewInt(1), nil), signer, key) // Add the first two transaction, ensure higher priced stays only if replace, err := pool.add(tx1, false); err != nil || replace { t.Errorf("first transaction insert failed (%v) or reported replacement (%v)", err, replace) } if replace, err := pool.add(tx2, false); err != nil || !replace { t.Errorf("second transaction insert failed (%v) or not reported replacement (%v)", err, replace) } <-pool.requestPromoteExecutables(newAccountSet(signer, addr)) if pool.pending[addr].Len() != 1 { t.Error("expected 1 pending transactions, got", pool.pending[addr].Len()) } if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() { t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash()) } // Add the third transaction and ensure it's not saved (smaller price) pool.add(tx3, false) <-pool.requestPromoteExecutables(newAccountSet(signer, addr)) if pool.pending[addr].Len() != 1 { t.Error("expected 1 pending transactions, got", pool.pending[addr].Len()) } if tx := pool.pending[addr].txs.items[0]; tx.Hash() != tx2.Hash() { t.Errorf("transaction mismatch: have %x, want %x", tx.Hash(), tx2.Hash()) } // Ensure the total transaction count is correct if pool.all.Count() != 1 { t.Error("expected 1 total transactions, got", pool.all.Count()) } } func TestTransactionMissingNonce(t *testing.T) { t.Parallel() pool, key := setupTxPool() defer pool.Stop() addr := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(addr, big.NewInt(100000000000000)) tx := transaction(1, 100000, key) if _, err := pool.add(tx, false); err != nil { t.Error("didn't expect error", err) } if len(pool.pending) != 0 { t.Error("expected 0 pending transactions, got", len(pool.pending)) } if pool.queue[addr].Len() != 1 { t.Error("expected 1 queued transaction, got", pool.queue[addr].Len()) } if pool.all.Count() != 1 { t.Error("expected 1 total transactions, got", pool.all.Count()) } } func TestTransactionNonceRecovery(t *testing.T) { t.Parallel() const n = 10 pool, key := setupTxPool() defer pool.Stop() addr := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.SetNonce(addr, n) pool.currentState.AddBalance(addr, big.NewInt(100000000000000)) <-pool.requestReset(nil, nil) tx := transaction(n, 100000, key) if err := pool.AddRemote(tx); err != nil { t.Error(err) } // simulate some weird re-order of transactions and missing nonce(s) pool.currentState.SetNonce(addr, n-1) <-pool.requestReset(nil, nil) if fn := pool.Nonce(addr); fn != n-1 { t.Errorf("expected nonce to be %d, got %d", n-1, fn) } } // Tests that if an account runs out of funds, any pending and queued transactions // are dropped. func TestTransactionDropping(t *testing.T) { t.Parallel() // Create a test account and fund it pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000)) // Add some pending and some queued transactions var ( tx0 = transaction(0, 100, key) tx1 = transaction(1, 200, key) tx2 = transaction(2, 300, key) tx10 = transaction(10, 100, key) tx11 = transaction(11, 200, key) tx12 = transaction(12, 300, key) ) pool.promoteTx(account, tx0.Hash(), tx0) pool.promoteTx(account, tx1.Hash(), tx1) pool.promoteTx(account, tx2.Hash(), tx2) pool.enqueueTx(tx10.Hash(), tx10) pool.enqueueTx(tx11.Hash(), tx11) pool.enqueueTx(tx12.Hash(), tx12) // Check that pre and post validations leave the pool as is if pool.pending[account].Len() != 3 { t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3) } if pool.queue[account].Len() != 3 { t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3) } if pool.all.Count() != 6 { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6) } <-pool.requestReset(nil, nil) if pool.pending[account].Len() != 3 { t.Errorf("pending transaction mismatch: have %d, want %d", pool.pending[account].Len(), 3) } if pool.queue[account].Len() != 3 { t.Errorf("queued transaction mismatch: have %d, want %d", pool.queue[account].Len(), 3) } if pool.all.Count() != 6 { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 6) } // Reduce the balance of the account, and check that invalidated transactions are dropped pool.currentState.AddBalance(account, big.NewInt(-650)) <-pool.requestReset(nil, nil) if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok { t.Errorf("funded pending transaction missing: %v", tx0) } if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; !ok { t.Errorf("funded pending transaction missing: %v", tx0) } if _, ok := pool.pending[account].txs.items[tx2.Nonce()]; ok { t.Errorf("out-of-fund pending transaction present: %v", tx1) } if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok { t.Errorf("funded queued transaction missing: %v", tx10) } if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; !ok { t.Errorf("funded queued transaction missing: %v", tx10) } if _, ok := pool.queue[account].txs.items[tx12.Nonce()]; ok { t.Errorf("out-of-fund queued transaction present: %v", tx11) } if pool.all.Count() != 4 { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 4) } // Reduce the block gas limit, check that invalidated transactions are dropped pool.chain.(*testBlockChain).gasLimit = 100 <-pool.requestReset(nil, nil) if _, ok := pool.pending[account].txs.items[tx0.Nonce()]; !ok { t.Errorf("funded pending transaction missing: %v", tx0) } if _, ok := pool.pending[account].txs.items[tx1.Nonce()]; ok { t.Errorf("over-gased pending transaction present: %v", tx1) } if _, ok := pool.queue[account].txs.items[tx10.Nonce()]; !ok { t.Errorf("funded queued transaction missing: %v", tx10) } if _, ok := pool.queue[account].txs.items[tx11.Nonce()]; ok { t.Errorf("over-gased queued transaction present: %v", tx11) } if pool.all.Count() != 2 { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), 2) } } // Tests that if a transaction is dropped from the current pending pool (e.g. out // of fund), all consecutive (still valid, but not executable) transactions are // postponed back into the future queue to prevent broadcasting them. func TestTransactionPostponing(t *testing.T) { t.Parallel() // Create the pool to test the postponing with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Create two test accounts to produce different gap profiles with keys := make([]*ecdsa.PrivateKey, 2) accs := make([]common.Address, len(keys)) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() accs[i] = crypto.PubkeyToAddress(keys[i].PublicKey) pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(50100)) } // Add a batch consecutive pending transactions for validation txs := []*types.Transaction{} for i, key := range keys { for j := 0; j < 100; j++ { var tx *types.Transaction if (i+j)%2 == 0 { tx = transaction(uint64(j), 25000, key) } else { tx = transaction(uint64(j), 50000, key) } txs = append(txs, tx) } } for i, err := range pool.AddRemotesSync(txs) { if err != nil { t.Fatalf("tx %d: failed to add transactions: %v", i, err) } } // Check that pre and post validations leave the pool as is if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) { t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs)) } if len(pool.queue) != 0 { t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0) } if pool.all.Count() != len(txs) { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)) } <-pool.requestReset(nil, nil) if pending := pool.pending[accs[0]].Len() + pool.pending[accs[1]].Len(); pending != len(txs) { t.Errorf("pending transaction mismatch: have %d, want %d", pending, len(txs)) } if len(pool.queue) != 0 { t.Errorf("queued accounts mismatch: have %d, want %d", len(pool.queue), 0) } if pool.all.Count() != len(txs) { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)) } // Reduce the balance of the account, and check that transactions are reorganised for _, addr := range accs { pool.currentState.AddBalance(addr, big.NewInt(-1)) } <-pool.requestReset(nil, nil) // The first account's first transaction remains valid, check that subsequent // ones are either filtered out, or queued up for later. if _, ok := pool.pending[accs[0]].txs.items[txs[0].Nonce()]; !ok { t.Errorf("tx %d: valid and funded transaction missing from pending pool: %v", 0, txs[0]) } if _, ok := pool.queue[accs[0]].txs.items[txs[0].Nonce()]; ok { t.Errorf("tx %d: valid and funded transaction present in future queue: %v", 0, txs[0]) } for i, tx := range txs[1:100] { if i%2 == 1 { if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok { t.Errorf("tx %d: valid but future transaction present in pending pool: %v", i+1, tx) } if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; !ok { t.Errorf("tx %d: valid but future transaction missing from future queue: %v", i+1, tx) } } else { if _, ok := pool.pending[accs[0]].txs.items[tx.Nonce()]; ok { t.Errorf("tx %d: out-of-fund transaction present in pending pool: %v", i+1, tx) } if _, ok := pool.queue[accs[0]].txs.items[tx.Nonce()]; ok { t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", i+1, tx) } } } // The second account's first transaction got invalid, check that all transactions // are either filtered out, or queued up for later. if pool.pending[accs[1]] != nil { t.Errorf("invalidated account still has pending transactions") } for i, tx := range txs[100:] { if i%2 == 1 { if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; !ok { t.Errorf("tx %d: valid but future transaction missing from future queue: %v", 100+i, tx) } } else { if _, ok := pool.queue[accs[1]].txs.items[tx.Nonce()]; ok { t.Errorf("tx %d: out-of-fund transaction present in future queue: %v", 100+i, tx) } } } if pool.all.Count() != len(txs)/2 { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), len(txs)/2) } } // Tests that if the transaction pool has both executable and non-executable // transactions from an origin account, filling the nonce gap moves all queued // ones into the pending pool. func TestTransactionGapFilling(t *testing.T) { t.Parallel() // Create a test account and fund it pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, testTxPoolConfig.AccountQueue+5) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Create a pending and a queued transaction with a nonce-gap in between pool.AddRemotesSync([]*types.Transaction{ transaction(0, 100000, key), transaction(2, 100000, key), }) pending, queued := pool.Stats() if pending != 1 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1) } if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } if err := validateEvents(events, 1); err != nil { t.Fatalf("original event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Fill the nonce gap and ensure all transactions become pending if err := pool.addRemoteSync(transaction(1, 100000, key)); err != nil { t.Fatalf("failed to add gapped transaction: %v", err) } pending, queued = pool.Stats() if pending != 3 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateEvents(events, 2); err != nil { t.Fatalf("gap-filling event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that if the transaction count belonging to a single account goes above // some threshold, the higher transactions are dropped to prevent DOS attacks. func TestTransactionQueueAccountLimiting(t *testing.T) { t.Parallel() // Create a test account and fund it pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) // Keep queuing up transactions and make sure all above a limit are dropped for i := uint64(1); i <= testTxPoolConfig.AccountQueue+5; i++ { if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil { t.Fatalf("tx %d: failed to add transaction: %v", i, err) } if len(pool.pending) != 0 { t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, len(pool.pending), 0) } if i <= testTxPoolConfig.AccountQueue { if pool.queue[account].Len() != int(i) { t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), i) } } else { if pool.queue[account].Len() != int(testTxPoolConfig.AccountQueue) { t.Errorf("tx %d: queue limit mismatch: have %d, want %d", i, pool.queue[account].Len(), testTxPoolConfig.AccountQueue) } } } if pool.all.Count() != int(testTxPoolConfig.AccountQueue) { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue) } } // Tests that if the transaction count belonging to multiple accounts go above // some threshold, the higher transactions are dropped to prevent DOS attacks. // // This logic should not hold for local transactions, unless the local tracking // mechanism is disabled. func TestTransactionQueueGlobalLimiting(t *testing.T) { testTransactionQueueGlobalLimiting(t, false) } func TestTransactionQueueGlobalLimitingNoLocals(t *testing.T) { testTransactionQueueGlobalLimiting(t, true) } func testTransactionQueueGlobalLimiting(t *testing.T, nolocals bool) { t.Parallel() // Create the pool to test the limit enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.NoLocals = nolocals config.GlobalQueue = config.AccountQueue*3 - 1 // reduce the queue limits to shorten test time (-1 to make it non divisible) pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Create a number of test accounts and fund them (last one will be the local) keys := make([]*ecdsa.PrivateKey, 5) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } local := keys[len(keys)-1] // Generate and queue a batch of transactions nonces := make(map[common.Address]uint64) txs := make(types.Transactions, 0, 3*config.GlobalQueue) for len(txs) < cap(txs) { key := keys[rand.Intn(len(keys)-1)] // skip adding transactions with the local account addr := crypto.PubkeyToAddress(key.PublicKey) txs = append(txs, transaction(nonces[addr]+1, 100000, key)) nonces[addr]++ } // Import the batch and verify that limits have been enforced pool.AddRemotesSync(txs) queued := 0 for addr, list := range pool.queue { if list.Len() > int(config.AccountQueue) { t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue) } queued += list.Len() } if queued > int(config.GlobalQueue) { t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue) } // Generate a batch of transactions from the local account and import them txs = txs[:0] for i := uint64(0); i < 3*config.GlobalQueue; i++ { txs = append(txs, transaction(i+1, 100000, local)) } pool.AddLocals(txs) // If locals are disabled, the previous eviction algorithm should apply here too if nolocals { queued := 0 for addr, list := range pool.queue { if list.Len() > int(config.AccountQueue) { t.Errorf("addr %x: queued accounts overflown allowance: %d > %d", addr, list.Len(), config.AccountQueue) } queued += list.Len() } if queued > int(config.GlobalQueue) { t.Fatalf("total transactions overflow allowance: %d > %d", queued, config.GlobalQueue) } } else { // Local exemptions are enabled, make sure the local account owned the queue if len(pool.queue) != 1 { t.Errorf("multiple accounts in queue: have %v, want %v", len(pool.queue), 1) } // Also ensure no local transactions are ever dropped, even if above global limits if queued := pool.queue[crypto.PubkeyToAddress(local.PublicKey)].Len(); uint64(queued) != 3*config.GlobalQueue { t.Fatalf("local account queued transaction count mismatch: have %v, want %v", queued, 3*config.GlobalQueue) } } } // Tests that if an account remains idle for a prolonged amount of time, any // non-executable transactions queued up are dropped to prevent wasting resources // on shuffling them around. // // This logic should not hold for local transactions, unless the local tracking // mechanism is disabled. func TestTransactionQueueTimeLimiting(t *testing.T) { testTransactionQueueTimeLimiting(t, false) } func TestTransactionQueueTimeLimitingNoLocals(t *testing.T) { testTransactionQueueTimeLimiting(t, true) } func testTransactionQueueTimeLimiting(t *testing.T, nolocals bool) { // Reduce the eviction interval to a testable amount defer func(old time.Duration) { evictionInterval = old }(evictionInterval) evictionInterval = time.Millisecond * 100 // Create the pool to test the non-expiration enforcement statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.Lifetime = time.Second config.NoLocals = nolocals pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Create two test accounts to ensure remotes expire but locals do not local, _ := crypto.GenerateKey() remote, _ := crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000)) pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000)) // Add the two transactions and ensure they both are queued up if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add local transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(1, 100000, big.NewInt(1), remote)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } pending, queued := pool.Stats() if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } if queued != 2 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Allow the eviction interval to run time.Sleep(2 * evictionInterval) // Transactions should not be evicted from the queue yet since lifetime duration has not passed pending, queued = pool.Stats() if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } if queued != 2 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Wait a bit for eviction to run and clean up any leftovers, and ensure only the local remains time.Sleep(2 * config.Lifetime) pending, queued = pool.Stats() if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } if nolocals { if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } } else { if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // remove current transactions and increase nonce to prepare for a reset and cleanup statedb.SetNonce(crypto.PubkeyToAddress(remote.PublicKey), 2) statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2) <-pool.requestReset(nil, nil) // make sure queue, pending are cleared pending, queued = pool.Stats() if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Queue gapped transactions if err := pool.AddLocal(pricedTransaction(4, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(4, 100000, big.NewInt(1), remote)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } time.Sleep(5 * evictionInterval) // A half lifetime pass // Queue executable transactions, the life cycle should be restarted. if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(1), remote)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } time.Sleep(6 * evictionInterval) // All gapped transactions shouldn't be kicked out pending, queued = pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if queued != 2 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // The whole life time pass after last promotion, kick out stale transactions time.Sleep(2 * config.Lifetime) pending, queued = pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if nolocals { if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } } else { if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that even if the transaction count belonging to a single account goes // above some threshold, as long as the transactions are executable, they are // accepted. func TestTransactionPendingLimiting(t *testing.T) { t.Parallel() // Create a test account and fund it pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, testTxPoolConfig.AccountQueue+5) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Keep queuing up transactions and make sure all above a limit are dropped for i := uint64(0); i < testTxPoolConfig.AccountQueue+5; i++ { if err := pool.addRemoteSync(transaction(i, 100000, key)); err != nil { t.Fatalf("tx %d: failed to add transaction: %v", i, err) } if pool.pending[account].Len() != int(i)+1 { t.Errorf("tx %d: pending pool size mismatch: have %d, want %d", i, pool.pending[account].Len(), i+1) } if len(pool.queue) != 0 { t.Errorf("tx %d: queue size mismatch: have %d, want %d", i, pool.queue[account].Len(), 0) } } if pool.all.Count() != int(testTxPoolConfig.AccountQueue+5) { t.Errorf("total transaction mismatch: have %d, want %d", pool.all.Count(), testTxPoolConfig.AccountQueue+5) } if err := validateEvents(events, int(testTxPoolConfig.AccountQueue+5)); err != nil { t.Fatalf("event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that if the transaction count belonging to multiple accounts go above // some hard threshold, the higher transactions are dropped to prevent DOS // attacks. func TestTransactionPendingGlobalLimiting(t *testing.T) { t.Parallel() // Create the pool to test the limit enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.GlobalSlots = config.AccountSlots * 10 pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 5) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Generate and queue a batch of transactions nonces := make(map[common.Address]uint64) txs := types.Transactions{} for _, key := range keys { addr := crypto.PubkeyToAddress(key.PublicKey) for j := 0; j < int(config.GlobalSlots)/len(keys)*2; j++ { txs = append(txs, transaction(nonces[addr], 100000, key)) nonces[addr]++ } } // Import the batch and verify that limits have been enforced pool.AddRemotesSync(txs) pending := 0 for _, list := range pool.pending { pending += list.Len() } if pending > int(config.GlobalSlots) { t.Fatalf("total pending transactions overflow allowance: %d > %d", pending, config.GlobalSlots) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Test the limit on transaction size is enforced correctly. // This test verifies every transaction having allowed size // is added to the pool, and longer transactions are rejected. func TestTransactionAllowedTxSize(t *testing.T) { t.Parallel() // Create a test account and fund it pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000000)) // Compute maximal data size for transactions (lower bound). // // It is assumed the fields in the transaction (except of the data) are: // - nonce <= 32 bytes // - gasPrice <= 32 bytes // - gasLimit <= 32 bytes // - recipient == 20 bytes // - value <= 32 bytes // - signature == 65 bytes // All those fields are summed up to at most 213 bytes. baseSize := uint64(213) dataSize := txMaxSize - baseSize // Try adding a transaction with maximal allowed size tx := pricedDataTransaction(0, pool.currentMaxGas, big.NewInt(1), key, dataSize) if err := pool.addRemoteSync(tx); err != nil { t.Fatalf("failed to add transaction of size %d, close to maximal: %v", int(tx.Size()), err) } // Try adding a transaction with random allowed size if err := pool.addRemoteSync(pricedDataTransaction(1, pool.currentMaxGas, big.NewInt(1), key, uint64(rand.Intn(int(dataSize))))); err != nil { t.Fatalf("failed to add transaction of random allowed size: %v", err) } // Try adding a transaction of minimal not allowed size if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, txMaxSize)); err == nil { t.Fatalf("expected rejection on slightly oversize transaction") } // Try adding a transaction of random not allowed size if err := pool.addRemoteSync(pricedDataTransaction(2, pool.currentMaxGas, big.NewInt(1), key, dataSize+1+uint64(rand.Intn(int(10*txMaxSize))))); err == nil { t.Fatalf("expected rejection on oversize transaction") } // Run some sanity checks on the pool internals pending, queued := pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that if transactions start being capped, transactions are also removed from 'all' func TestTransactionCapClearsFromAll(t *testing.T) { t.Parallel() // Create the pool to test the limit enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.AccountSlots = 2 config.AccountQueue = 2 config.GlobalSlots = 8 pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Create a number of test accounts and fund them key, _ := crypto.GenerateKey() addr := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(addr, big.NewInt(1000000)) txs := types.Transactions{} for j := 0; j < int(config.GlobalSlots)*2; j++ { txs = append(txs, transaction(uint64(j), 100000, key)) } // Import the batch and verify that limits have been enforced pool.AddRemotes(txs) if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that if the transaction count belonging to multiple accounts go above // some hard threshold, if they are under the minimum guaranteed slot count then // the transactions are still kept. func TestTransactionPendingMinimumAllowance(t *testing.T) { t.Parallel() // Create the pool to test the limit enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.GlobalSlots = 1 pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 5) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Generate and queue a batch of transactions nonces := make(map[common.Address]uint64) txs := types.Transactions{} for _, key := range keys { addr := crypto.PubkeyToAddress(key.PublicKey) for j := 0; j < int(config.AccountSlots)*2; j++ { txs = append(txs, transaction(nonces[addr], 100000, key)) nonces[addr]++ } } // Import the batch and verify that limits have been enforced pool.AddRemotesSync(txs) for addr, list := range pool.pending { if list.Len() != int(config.AccountSlots) { t.Errorf("addr %x: total pending transactions mismatch: have %d, want %d", addr, list.Len(), config.AccountSlots) } } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that setting the transaction pool gas price to a higher value correctly // discards everything cheaper than that and moves any gapped transactions back // from the pending pool to the queue. // // Note, local transactions are never allowed to be dropped. func TestTransactionPoolRepricing(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, 32) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 4) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Generate and queue a batch of transactions, both pending and queued txs := types.Transactions{} txs = append(txs, pricedTransaction(0, 100000, big.NewInt(2), keys[0])) txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[0])) txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[0])) txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[1])) txs = append(txs, pricedTransaction(2, 100000, big.NewInt(2), keys[1])) txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[2])) txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) txs = append(txs, pricedTransaction(3, 100000, big.NewInt(2), keys[2])) ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[3]) // Import the batch and that both pending and queued transactions match up pool.AddRemotesSync(txs) pool.AddLocal(ltx) pending, queued := pool.Stats() if pending != 7 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 7) } if queued != 3 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 3) } if err := validateEvents(events, 7); err != nil { t.Fatalf("original event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Reprice the pool and check that underpriced transactions get dropped pool.SetGasPrice(big.NewInt(2)) pending, queued = pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if queued != 5 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 5) } if err := validateEvents(events, 0); err != nil { t.Fatalf("reprice event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Check that we can't add the old transactions back if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(1), keys[0])); err != ErrUnderpriced { t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) } if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced { t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) } if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), keys[2])); err != ErrUnderpriced { t.Fatalf("adding underpriced queued transaction error mismatch: have %v, want %v", err, ErrUnderpriced) } if err := validateEvents(events, 0); err != nil { t.Fatalf("post-reprice event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // However we can add local underpriced transactions tx := pricedTransaction(1, 100000, big.NewInt(1), keys[3]) if err := pool.AddLocal(tx); err != nil { t.Fatalf("failed to add underpriced local transaction: %v", err) } if pending, _ = pool.Stats(); pending != 3 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) } if err := validateEvents(events, 1); err != nil { t.Fatalf("post-reprice local event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // And we can fill gaps with properly priced transactions if err := pool.AddRemote(pricedTransaction(1, 100000, big.NewInt(2), keys[0])); err != nil { t.Fatalf("failed to add pending transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), keys[1])); err != nil { t.Fatalf("failed to add pending transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), keys[2])); err != nil { t.Fatalf("failed to add queued transaction: %v", err) } if err := validateEvents(events, 5); err != nil { t.Fatalf("post-reprice event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that setting the transaction pool gas price to a higher value does not // remove local transactions. func TestTransactionPoolRepricingKeepsLocals(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 3) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000*1000000)) } // Create transaction (both pending and queued) with a linearly growing gasprice for i := uint64(0); i < 500; i++ { // Add pending transaction. pendingTx := pricedTransaction(i, 100000, big.NewInt(int64(i)), keys[2]) if err := pool.AddLocal(pendingTx); err != nil { t.Fatal(err) } // Add queued transaction. queuedTx := pricedTransaction(i+501, 100000, big.NewInt(int64(i)), keys[2]) if err := pool.AddLocal(queuedTx); err != nil { t.Fatal(err) } } pending, queued := pool.Stats() expPending, expQueued := 500, 500 validate := func() { pending, queued = pool.Stats() if pending != expPending { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, expPending) } if queued != expQueued { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, expQueued) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } validate() // Reprice the pool and check that nothing is dropped pool.SetGasPrice(big.NewInt(2)) validate() pool.SetGasPrice(big.NewInt(2)) pool.SetGasPrice(big.NewInt(4)) pool.SetGasPrice(big.NewInt(8)) pool.SetGasPrice(big.NewInt(100)) validate() } // Tests that when the pool reaches its global transaction limit, underpriced // transactions are gradually shifted out for more expensive ones and any gapped // pending transactions are moved into the queue. // // Note, local transactions are never allowed to be dropped. func TestTransactionPoolUnderpricing(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.GlobalSlots = 2 config.GlobalQueue = 2 pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, 32) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 4) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Generate and queue a batch of transactions, both pending and queued txs := types.Transactions{} txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) txs = append(txs, pricedTransaction(1, 100000, big.NewInt(2), keys[0])) txs = append(txs, pricedTransaction(1, 100000, big.NewInt(1), keys[1])) ltx := pricedTransaction(0, 100000, big.NewInt(1), keys[2]) // Import the batch and that both pending and queued transactions match up pool.AddRemotesSync(txs) pool.AddLocal(ltx) pending, queued := pool.Stats() if pending != 3 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) } if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } if err := validateEvents(events, 3); err != nil { t.Fatalf("original event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Ensure that adding an underpriced transaction on block limit fails if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), keys[1])); err != ErrUnderpriced { t.Fatalf("adding underpriced pending transaction error mismatch: have %v, want %v", err, ErrUnderpriced) } // Ensure that adding high priced transactions drops cheap ones, but not own if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil { // +K1:0 => -K1:1 => Pend K0:0, K0:1, K1:0, K2:0; Que - t.Fatalf("failed to add well priced transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(2, 100000, big.NewInt(4), keys[1])); err != nil { // +K1:2 => -K0:0 => Pend K1:0, K2:0; Que K0:1 K1:2 t.Fatalf("failed to add well priced transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(3, 100000, big.NewInt(5), keys[1])); err != nil { // +K1:3 => -K0:1 => Pend K1:0, K2:0; Que K1:2 K1:3 t.Fatalf("failed to add well priced transaction: %v", err) } pending, queued = pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if queued != 2 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) } if err := validateEvents(events, 1); err != nil { t.Fatalf("additional event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Ensure that adding local transactions can push out even higher priced ones ltx = pricedTransaction(1, 100000, big.NewInt(0), keys[2]) if err := pool.AddLocal(ltx); err != nil { t.Fatalf("failed to append underpriced local transaction: %v", err) } ltx = pricedTransaction(0, 100000, big.NewInt(0), keys[3]) if err := pool.AddLocal(ltx); err != nil { t.Fatalf("failed to add new underpriced local transaction: %v", err) } pending, queued = pool.Stats() if pending != 3 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 3) } if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } if err := validateEvents(events, 2); err != nil { t.Fatalf("local event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that more expensive transactions push out cheap ones from the pool, but // without producing instability by creating gaps that start jumping transactions // back and forth between queued/pending. func TestTransactionPoolStableUnderpricing(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.GlobalSlots = 128 config.GlobalQueue = 0 pool := NewTxPool(config, params.TestChainConfig, blockchain) defer pool.Stop() // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, 32) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Create a number of test accounts and fund them keys := make([]*ecdsa.PrivateKey, 2) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Fill up the entire queue with the same transaction price points txs := types.Transactions{} for i := uint64(0); i < config.GlobalSlots; i++ { txs = append(txs, pricedTransaction(i, 100000, big.NewInt(1), keys[0])) } pool.AddRemotesSync(txs) pending, queued := pool.Stats() if pending != int(config.GlobalSlots) { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateEvents(events, int(config.GlobalSlots)); err != nil { t.Fatalf("original event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Ensure that adding high priced transactions drops a cheap, but doesn't produce a gap if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(3), keys[1])); err != nil { t.Fatalf("failed to add well priced transaction: %v", err) } pending, queued = pool.Stats() if pending != int(config.GlobalSlots) { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, config.GlobalSlots) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateEvents(events, 1); err != nil { t.Fatalf("additional event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that the pool rejects duplicate transactions. func TestTransactionDeduplication(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Create a test account to add transactions with key, _ := crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000)) // Create a batch of transactions and add a few of them txs := make([]*types.Transaction, 16) for i := 0; i < len(txs); i++ { txs[i] = pricedTransaction(uint64(i), 100000, big.NewInt(1), key) } var firsts []*types.Transaction for i := 0; i < len(txs); i += 2 { firsts = append(firsts, txs[i]) } errs := pool.AddRemotesSync(firsts) if len(errs) != len(firsts) { t.Fatalf("first add mismatching result count: have %d, want %d", len(errs), len(firsts)) } for i, err := range errs { if err != nil { t.Errorf("add %d failed: %v", i, err) } } pending, queued := pool.Stats() if pending != 1 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 1) } if queued != len(txs)/2-1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, len(txs)/2-1) } // Try to add all of them now and ensure previous ones error out as knowns errs = pool.AddRemotesSync(txs) if len(errs) != len(txs) { t.Fatalf("all add mismatching result count: have %d, want %d", len(errs), len(txs)) } for i, err := range errs { if i%2 == 0 && err == nil { t.Errorf("add %d succeeded, should have failed as known", i) } if i%2 == 1 && err != nil { t.Errorf("add %d failed: %v", i, err) } } pending, queued = pool.Stats() if pending != len(txs) { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, len(txs)) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that the pool rejects replacement transactions that don't meet the minimum // price bump required. func TestTransactionReplacement(t *testing.T) { t.Parallel() // Create the pool to test the pricing enforcement with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Keep track of transaction events to ensure all executables get announced events := make(chan NewTxsNotify, 32) sub := pool.txFeed.Subscribe(events) defer sub.Unsubscribe() // Create a test account to add transactions with key, _ := crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(key.PublicKey), big.NewInt(1000000000)) // Add pending transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too) price := int64(100) threshold := (price * (100 + int64(testTxPoolConfig.PriceBump))) / 100 if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), key)); err != nil { t.Fatalf("failed to add original cheap pending transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced { t.Fatalf("original cheap pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) } if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(2), key)); err != nil { t.Fatalf("failed to replace original cheap pending transaction: %v", err) } if err := validateEvents(events, 2); err != nil { t.Fatalf("cheap replacement event firing failed: %v", err) } if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(price), key)); err != nil { t.Fatalf("failed to add original proper pending transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(0, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced { t.Fatalf("original proper pending transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) } if err := pool.AddRemote(pricedTransaction(0, 100000, big.NewInt(threshold), key)); err != nil { t.Fatalf("failed to replace original proper pending transaction: %v", err) } if err := validateEvents(events, 2); err != nil { t.Fatalf("proper replacement event firing failed: %v", err) } // Add queued transactions, ensuring the minimum price bump is enforced for replacement (for ultra low prices too) if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(1), key)); err != nil { t.Fatalf("failed to add original cheap queued transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(1), key)); err != ErrReplaceUnderpriced { t.Fatalf("original cheap queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) } if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(2), key)); err != nil { t.Fatalf("failed to replace original cheap queued transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(price), key)); err != nil { t.Fatalf("failed to add original proper queued transaction: %v", err) } if err := pool.AddRemote(pricedTransaction(2, 100001, big.NewInt(threshold-1), key)); err != ErrReplaceUnderpriced { t.Fatalf("original proper queued transaction replacement error mismatch: have %v, want %v", err, ErrReplaceUnderpriced) } if err := pool.AddRemote(pricedTransaction(2, 100000, big.NewInt(threshold), key)); err != nil { t.Fatalf("failed to replace original proper queued transaction: %v", err) } if err := validateEvents(events, 0); err != nil { t.Fatalf("queued replacement event firing failed: %v", err) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } } // Tests that local transactions are journaled to disk, but remote transactions // get discarded between restarts. func TestTransactionJournaling(t *testing.T) { testTransactionJournaling(t, false) } func TestTransactionJournalingNoLocals(t *testing.T) { testTransactionJournaling(t, true) } func testTransactionJournaling(t *testing.T, nolocals bool) { t.Parallel() // Create a temporary file for the journal file, err := ioutil.TempFile("", "") if err != nil { t.Fatalf("failed to create temporary journal: %v", err) } journal := file.Name() defer os.Remove(journal) // Clean up the temporary file, we only need the path for now file.Close() os.Remove(journal) // Create the original pool to inject transaction into the journal statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} config := testTxPoolConfig config.NoLocals = nolocals config.Journal = journal config.Rejournal = time.Second pool := NewTxPool(config, params.TestChainConfig, blockchain) // Create two test accounts to ensure remotes expire but locals do not local, _ := crypto.GenerateKey() remote, _ := crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(local.PublicKey), big.NewInt(1000000000)) pool.currentState.AddBalance(crypto.PubkeyToAddress(remote.PublicKey), big.NewInt(1000000000)) // Add three local and a remote transactions and ensure they are queued up if err := pool.AddLocal(pricedTransaction(0, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add local transaction: %v", err) } if err := pool.AddLocal(pricedTransaction(1, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add local transaction: %v", err) } if err := pool.AddLocal(pricedTransaction(2, 100000, big.NewInt(1), local)); err != nil { t.Fatalf("failed to add local transaction: %v", err) } if err := pool.addRemoteSync(pricedTransaction(0, 100000, big.NewInt(1), remote)); err != nil { t.Fatalf("failed to add remote transaction: %v", err) } pending, queued := pool.Stats() if pending != 4 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 4) } if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Terminate the old pool, bump the local nonce, create a new pool and ensure relevant transaction survive pool.Stop() statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1) blockchain = &testBlockChain{statedb, 1000000, new(notify.Feed)} pool = NewTxPool(config, params.TestChainConfig, blockchain) pending, queued = pool.Stats() if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } if nolocals { if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } } else { if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Bump the nonce temporarily and ensure the newly invalidated transaction is removed statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 2) <-pool.requestReset(nil, nil) time.Sleep(2 * config.Rejournal) pool.Stop() statedb.SetNonce(crypto.PubkeyToAddress(local.PublicKey), 1) blockchain = &testBlockChain{statedb, 1000000, new(notify.Feed)} pool = NewTxPool(config, params.TestChainConfig, blockchain) pending, queued = pool.Stats() if pending != 0 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 0) } if nolocals { if queued != 0 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 0) } } else { if queued != 1 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 1) } } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } pool.Stop() } // TestTransactionStatusCheck tests that the pool can correctly retrieve the // pending status of individual transactions. func TestTransactionStatusCheck(t *testing.T) { t.Parallel() // Create the pool to test the status retrievals with statedb, _ := state.New(common.Hash{}, state.NewDatabase(rawdb.NewMemoryDatabase()), nil) blockchain := &testBlockChain{statedb, 1000000, new(notify.Feed)} pool := NewTxPool(testTxPoolConfig, params.TestChainConfig, blockchain) defer pool.Stop() // Create the test accounts to check various transaction statuses with keys := make([]*ecdsa.PrivateKey, 3) for i := 0; i < len(keys); i++ { keys[i], _ = crypto.GenerateKey() pool.currentState.AddBalance(crypto.PubkeyToAddress(keys[i].PublicKey), big.NewInt(1000000)) } // Generate and queue a batch of transactions, both pending and queued txs := types.Transactions{} txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[0])) // Pending only txs = append(txs, pricedTransaction(0, 100000, big.NewInt(1), keys[1])) // Pending and queued txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[1])) txs = append(txs, pricedTransaction(2, 100000, big.NewInt(1), keys[2])) // Queued only // Import the transaction and ensure they are correctly added pool.AddRemotesSync(txs) pending, queued := pool.Stats() if pending != 2 { t.Fatalf("pending transactions mismatched: have %d, want %d", pending, 2) } if queued != 2 { t.Fatalf("queued transactions mismatched: have %d, want %d", queued, 2) } if err := validateTxPoolInternals(pool); err != nil { t.Fatalf("pool internal state corrupted: %v", err) } // Retrieve the status of each transaction and validate them hashes := make([]common.Hash, len(txs)) for i, tx := range txs { hashes[i] = tx.Hash() } hashes = append(hashes, common.Hash{}) statuses := pool.Status(hashes) expect := []TxStatus{TxStatusPending, TxStatusPending, TxStatusQueued, TxStatusQueued, TxStatusUnknown} for i := 0; i < len(statuses); i++ { if statuses[i] != expect[i] { t.Errorf("transaction %d: status mismatch: have %v, want %v", i, statuses[i], expect[i]) } } } // Test the transaction slots consumption is computed correctly func TestTransactionSlotCount(t *testing.T) { t.Parallel() key, _ := crypto.GenerateKey() // Check that an empty transaction consumes a single slot smallTx := pricedDataTransaction(0, 0, big.NewInt(0), key, 0) if slots := numSlots(smallTx); slots != 1 { t.Fatalf("small transactions slot count mismatch: have %d want %d", slots, 1) } // Check that a large transaction consumes the correct number of slots bigTx := pricedDataTransaction(0, 0, big.NewInt(0), key, uint64(10*txSlotSize)) if slots := numSlots(bigTx); slots != 11 { t.Fatalf("big transactions slot count mismatch: have %d want %d", slots, 11) } } // Benchmarks the speed of validating the contents of the pending queue of the // transaction pool. func BenchmarkPendingDemotion100(b *testing.B) { benchmarkPendingDemotion(b, 100) } func BenchmarkPendingDemotion1000(b *testing.B) { benchmarkPendingDemotion(b, 1000) } func BenchmarkPendingDemotion10000(b *testing.B) { benchmarkPendingDemotion(b, 10000) } func benchmarkPendingDemotion(b *testing.B, size int) { // Add a batch of transactions to a pool one by one pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) for i := 0; i < size; i++ { tx := transaction(uint64(i), 100000, key) pool.promoteTx(account, tx.Hash(), tx) } // Benchmark the speed of pool validation b.ResetTimer() for i := 0; i < b.N; i++ { pool.demoteUnexecutables() } } // Benchmarks the speed of scheduling the contents of the future queue of the // transaction pool. func BenchmarkFuturePromotion100(b *testing.B) { benchmarkFuturePromotion(b, 100) } func BenchmarkFuturePromotion1000(b *testing.B) { benchmarkFuturePromotion(b, 1000) } func BenchmarkFuturePromotion10000(b *testing.B) { benchmarkFuturePromotion(b, 10000) } func benchmarkFuturePromotion(b *testing.B, size int) { // Add a batch of transactions to a pool one by one pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) for i := 0; i < size; i++ { tx := transaction(uint64(1+i), 100000, key) pool.enqueueTx(tx.Hash(), tx) } // Benchmark the speed of pool validation b.ResetTimer() for i := 0; i < b.N; i++ { pool.promoteExecutables(nil) } } // Benchmarks the speed of batched transaction insertion. func BenchmarkPoolBatchInsert100(b *testing.B) { benchmarkPoolBatchInsert(b, 100, false) } func BenchmarkPoolBatchInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000, false) } func BenchmarkPoolBatchInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000, false) } func
(b *testing.B) { benchmarkPoolBatchInsert(b, 100, true) } func BenchmarkPoolBatchLocalInsert1000(b *testing.B) { benchmarkPoolBatchInsert(b, 1000, true) } func BenchmarkPoolBatchLocalInsert10000(b *testing.B) { benchmarkPoolBatchInsert(b, 10000, true) } func benchmarkPoolBatchInsert(b *testing.B, size int, local bool) { // Generate a batch of transactions to enqueue into the pool pool, key := setupTxPool() defer pool.Stop() account := crypto.PubkeyToAddress(key.PublicKey) pool.currentState.AddBalance(account, big.NewInt(1000000)) batches := make([]types.Transactions, b.N) for i := 0; i < b.N; i++ { batches[i] = make(types.Transactions, size) for j := 0; j < size; j++ { batches[i][j] = transaction(uint64(size*i+j), 100000, key) } } // Benchmark importing the transactions into the queue b.ResetTimer() for _, batch := range batches { if local { pool.AddLocals(batch) } else { pool.AddRemotes(batch) } } }
BenchmarkPoolBatchLocalInsert100
index.js
import customBth from './customBth'
// (function(Vue) { // Vue.directive('otherRender', customBth) // })()
ptr.rs
#[doc = "Register `PTR` reader"] pub struct R(crate::R<PTR_SPEC>); impl core::ops::Deref for R { type Target = crate::R<PTR_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<PTR_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<PTR_SPEC>) -> Self { R(reader) } } #[doc = "Register `PTR` writer"] pub struct W(crate::W<PTR_SPEC>); impl core::ops::Deref for W { type Target = crate::W<PTR_SPEC>; #[inline(always)]
fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<PTR_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<PTR_SPEC>) -> Self { W(writer) } } #[doc = "Field `PTR` reader - Beginning address in RAM of this sequence"] pub struct PTR_R(crate::FieldReader<u32, u32>); impl PTR_R { #[inline(always)] pub(crate) fn new(bits: u32) -> Self { PTR_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PTR_R { type Target = crate::FieldReader<u32, u32>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PTR` writer - Beginning address in RAM of this sequence"] pub struct PTR_W<'a> { w: &'a mut W, } impl<'a> PTR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = value; self.w } } impl R { #[doc = "Bits 0:31 - Beginning address in RAM of this sequence"] #[inline(always)] pub fn ptr(&self) -> PTR_R { PTR_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - Beginning address in RAM of this sequence"] #[inline(always)] pub fn ptr(&mut self) -> PTR_W { PTR_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Description cluster\\[n\\]: Beginning address in RAM of this sequence\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ptr](index.html) module"] pub struct PTR_SPEC; impl crate::RegisterSpec for PTR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [ptr::R](R) reader structure"] impl crate::Readable for PTR_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [ptr::W](W) writer structure"] impl crate::Writable for PTR_SPEC { type Writer = W; } #[doc = "`reset()` method sets PTR to value 0"] impl crate::Resettable for PTR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
http_errors.go
package errors import ( "io/ioutil" "net/http" ) // HTTPError is an interface for errors which can be returned. type HTTPError interface { error Details() []byte Path() string } // CreateFromResponse converts http.Response with non 2** status code // to Error with HTTPError interface. func CreateFromResponse(response *http.Response) HTTPError
{ body, err := ioutil.ReadAll(response.Body) if err != nil { panic(err) } path := response.Request.URL.Path var error HTTPError switch status := response.StatusCode; { case status == 401: error = createUnauthorized(path, body) case status == 403: error = createForbidden(path, body) case status == 404: error = createNotFound(path, body) case status == 422: error = createUnprocessableEntity(path, body) case status == 429: error = createTooManyRequests(path, body) case status >= 500: error = createServerError(status, path, body) default: error = createUnexpected(status, path, body) } return error }
markdown_test.go
package markdown import ( "testing" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer/html" "github.com/FooSoft/goldsmith" "github.com/FooSoft/goldsmith-components/harness" ) func Test(self *testing.T)
{ harness.Validate( self, func(gs *goldsmith.Goldsmith) { gs.Chain(NewWithGoldmark(goldmark.New( goldmark.WithExtensions(extension.GFM, extension.Typographer, extension.DefinitionList), goldmark.WithParserOptions(parser.WithAutoHeadingID()), goldmark.WithRendererOptions(html.WithUnsafe()), ))) }, ) }
recommender-gen.go
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated file. DO NOT EDIT. // Package recommender provides access to the Recommender API. // // For product documentation, see: https://cloud.google.com/recommender/docs/ // // Creating a client // // Usage example: // // import "google.golang.org/api/recommender/v1beta1" // ... // ctx := context.Background() // recommenderService, err := recommender.NewService(ctx) // // In this example, Google Application Default Credentials are used for authentication. // // For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials. // // Other authentication options // // To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey: // // recommenderService, err := recommender.NewService(ctx, option.WithAPIKey("AIza...")) // // To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource: // // config := &oauth2.Config{...} // // ... // token, err := config.Exchange(ctx, ...) // recommenderService, err := recommender.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token))) // // See https://godoc.org/google.golang.org/api/option/ for details on options. package recommender // import "google.golang.org/api/recommender/v1beta1" import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" googleapi "google.golang.org/api/googleapi" gensupport "google.golang.org/api/internal/gensupport" option "google.golang.org/api/option" internaloption "google.golang.org/api/option/internaloption" htransport "google.golang.org/api/transport/http" ) // Always reference these packages, just in case the auto-generated code // below doesn't. var _ = bytes.NewBuffer var _ = strconv.Itoa var _ = fmt.Sprintf var _ = json.NewDecoder var _ = io.Copy var _ = url.Parse var _ = gensupport.MarshalJSON var _ = googleapi.Version var _ = errors.New var _ = strings.Replace var _ = context.Canceled var _ = internaloption.WithDefaultEndpoint const apiId = "recommender:v1beta1" const apiName = "recommender" const apiVersion = "v1beta1" const basePath = "https://recommender.googleapis.com/" const mtlsBasePath = "https://recommender.mtls.googleapis.com/" // OAuth2 scopes used by this API. const ( // View and manage your data across Google Cloud Platform services CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform" ) // NewService creates a new Service. func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { scopesOption := option.WithScopes( "https://www.googleapis.com/auth/cloud-platform", ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) opts = append(opts, internaloption.WithDefaultEndpoint(basePath)) opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath)) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err } s, err := New(client) if err != nil { return nil, err } if endpoint != "" { s.BasePath = endpoint } return s, nil } // New creates a new Service. It uses the provided http.Client for requests. // // Deprecated: please use NewService instead. // To provide a custom HTTP client, use option.WithHTTPClient. // If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead. func New(client *http.Client) (*Service, error) { if client == nil { return nil, errors.New("client is nil") } s := &Service{client: client, BasePath: basePath} s.Projects = NewProjectsService(s) return s, nil } type Service struct { client *http.Client BasePath string // API endpoint base URL UserAgent string // optional additional User-Agent fragment Projects *ProjectsService } func (s *Service) userAgent() string { if s.UserAgent == "" { return googleapi.UserAgent } return googleapi.UserAgent + " " + s.UserAgent } func NewProjectsService(s *Service) *ProjectsService { rs := &ProjectsService{s: s} rs.Locations = NewProjectsLocationsService(s) return rs } type ProjectsService struct { s *Service Locations *ProjectsLocationsService } func NewProjectsLocationsService(s *Service) *ProjectsLocationsService { rs := &ProjectsLocationsService{s: s} rs.InsightTypes = NewProjectsLocationsInsightTypesService(s) rs.Recommenders = NewProjectsLocationsRecommendersService(s) return rs } type ProjectsLocationsService struct { s *Service InsightTypes *ProjectsLocationsInsightTypesService Recommenders *ProjectsLocationsRecommendersService } func NewProjectsLocationsInsightTypesService(s *Service) *ProjectsLocationsInsightTypesService
type ProjectsLocationsInsightTypesService struct { s *Service Insights *ProjectsLocationsInsightTypesInsightsService } func NewProjectsLocationsInsightTypesInsightsService(s *Service) *ProjectsLocationsInsightTypesInsightsService { rs := &ProjectsLocationsInsightTypesInsightsService{s: s} return rs } type ProjectsLocationsInsightTypesInsightsService struct { s *Service } func NewProjectsLocationsRecommendersService(s *Service) *ProjectsLocationsRecommendersService { rs := &ProjectsLocationsRecommendersService{s: s} rs.Recommendations = NewProjectsLocationsRecommendersRecommendationsService(s) return rs } type ProjectsLocationsRecommendersService struct { s *Service Recommendations *ProjectsLocationsRecommendersRecommendationsService } func NewProjectsLocationsRecommendersRecommendationsService(s *Service) *ProjectsLocationsRecommendersRecommendationsService { rs := &ProjectsLocationsRecommendersRecommendationsService{s: s} return rs } type ProjectsLocationsRecommendersRecommendationsService struct { s *Service } // GoogleCloudRecommenderV1beta1CostProjection: Contains metadata about // how much money a recommendation can save or incur. type GoogleCloudRecommenderV1beta1CostProjection struct { // Cost: An approximate projection on amount saved or amount incurred. // Negative cost units indicate cost savings and positive cost units // indicate increase. See google.type.Money documentation for // positive/negative units. Cost *GoogleTypeMoney `json:"cost,omitempty"` // Duration: Duration for which this cost applies. Duration string `json:"duration,omitempty"` // ForceSendFields is a list of field names (e.g. "Cost") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Cost") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1CostProjection) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1CostProjection raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1Impact: Contains the impact a // recommendation can have for a given category. type GoogleCloudRecommenderV1beta1Impact struct { // Category: Category that is being targeted. // // Possible values: // "CATEGORY_UNSPECIFIED" - Default unspecified category. Don't use // directly. // "COST" - Indicates a potential increase or decrease in cost. // "SECURITY" - Indicates a potential increase or decrease in // security. // "PERFORMANCE" - Indicates a potential increase or decrease in // performance. // "MANAGEABILITY" - Indicates a potential increase or decrease in // manageability. Category string `json:"category,omitempty"` // CostProjection: Use with CategoryType.COST CostProjection *GoogleCloudRecommenderV1beta1CostProjection `json:"costProjection,omitempty"` // ForceSendFields is a list of field names (e.g. "Category") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Category") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1Impact) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1Impact raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1Insight: An insight along with the // information used to derive the insight. The insight may have // associated recomendations as well. type GoogleCloudRecommenderV1beta1Insight struct { // AssociatedRecommendations: Recommendations derived from this insight. AssociatedRecommendations []*GoogleCloudRecommenderV1beta1InsightRecommendationReference `json:"associatedRecommendations,omitempty"` // Category: Category being targeted by the insight. // // Possible values: // "CATEGORY_UNSPECIFIED" - Unspecified category. // "COST" - The insight is related to cost. // "SECURITY" - The insight is related to security. // "PERFORMANCE" - The insight is related to performance. // "MANAGEABILITY" - This insight is related to manageability. Category string `json:"category,omitempty"` // Content: A struct of custom fields to explain the insight. Example: // "grantedPermissionsCount": "1000" Content googleapi.RawMessage `json:"content,omitempty"` // Description: Free-form human readable summary in English. The maximum // length is 500 characters. Description string `json:"description,omitempty"` // Etag: Fingerprint of the Insight. Provides optimistic locking when // updating states. Etag string `json:"etag,omitempty"` // InsightSubtype: Insight subtype. Insight content schema will be // stable for a given subtype. InsightSubtype string `json:"insightSubtype,omitempty"` // LastRefreshTime: Timestamp of the latest data used to generate the // insight. LastRefreshTime string `json:"lastRefreshTime,omitempty"` // Name: Name of the insight. Name string `json:"name,omitempty"` // ObservationPeriod: Observation period that led to the insight. The // source data used to generate the insight ends at last_refresh_time // and begins at (last_refresh_time - observation_period). ObservationPeriod string `json:"observationPeriod,omitempty"` // StateInfo: Information state and metadata. StateInfo *GoogleCloudRecommenderV1beta1InsightStateInfo `json:"stateInfo,omitempty"` // TargetResources: Fully qualified resource names that this insight is // targeting. TargetResources []string `json:"targetResources,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. // "AssociatedRecommendations") to unconditionally include in API // requests. By default, fields with empty values are omitted from API // requests. However, any non-pointer, non-interface field appearing in // ForceSendFields will be sent to the server regardless of whether the // field is empty or not. This may be used to include empty fields in // Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. // "AssociatedRecommendations") to include in API requests with the JSON // null value. By default, fields with empty values are omitted from API // requests. However, any field with an empty value appearing in // NullFields will be sent to the server as null. It is an error if a // field in this list has a non-empty value. This may be used to include // null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1Insight) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1Insight raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1InsightRecommendationReference: // Reference to an associated recommendation. type GoogleCloudRecommenderV1beta1InsightRecommendationReference struct { // Recommendation: Recommendation resource name, e.g. // projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMEND // ER_ID]/recommendations/[RECOMMENDATION_ID] Recommendation string `json:"recommendation,omitempty"` // ForceSendFields is a list of field names (e.g. "Recommendation") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Recommendation") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1InsightRecommendationReference) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1InsightRecommendationReference raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1InsightStateInfo: Information related to // insight state. type GoogleCloudRecommenderV1beta1InsightStateInfo struct { // State: Insight state. // // Possible values: // "STATE_UNSPECIFIED" - Unspecified state. // "ACTIVE" - Insight is active. Content for ACTIVE insights can be // updated by Google. ACTIVE insights can be marked DISMISSED OR // ACCEPTED. // "ACCEPTED" - Some action has been taken based on this insight. // Insights become accepted when a recommendation derived from the // insight has been marked CLAIMED, SUCCEEDED, or FAILED. ACTIVE // insights can also be marked ACCEPTED explicitly. Content for ACCEPTED // insights is immutable. ACCEPTED insights can only be marked ACCEPTED // (which may update state metadata). // "DISMISSED" - Insight is dismissed. Content for DISMISSED insights // can be updated by Google. DISMISSED insights can be marked as ACTIVE. State string `json:"state,omitempty"` // StateMetadata: A map of metadata for the state, provided by user or // automations systems. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "State") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "State") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1InsightStateInfo) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1InsightStateInfo raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1ListInsightsResponse: Response to the // `ListInsights` method. type GoogleCloudRecommenderV1beta1ListInsightsResponse struct { // Insights: The set of insights for the `parent` resource. Insights []*GoogleCloudRecommenderV1beta1Insight `json:"insights,omitempty"` // NextPageToken: A token that can be used to request the next page of // results. This field is empty if there are no additional results. NextPageToken string `json:"nextPageToken,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "Insights") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Insights") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1ListInsightsResponse) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1ListInsightsResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1ListRecommendationsResponse: Response to // the `ListRecommendations` method. type GoogleCloudRecommenderV1beta1ListRecommendationsResponse struct { // NextPageToken: A token that can be used to request the next page of // results. This field is empty if there are no additional results. NextPageToken string `json:"nextPageToken,omitempty"` // Recommendations: The set of recommendations for the `parent` // resource. Recommendations []*GoogleCloudRecommenderV1beta1Recommendation `json:"recommendations,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "NextPageToken") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "NextPageToken") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1ListRecommendationsResponse) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1ListRecommendationsResponse raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest: Request for // the `MarkInsightAccepted` method. type GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest struct { // Etag: Required. Fingerprint of the Insight. Provides optimistic // locking. Etag string `json:"etag,omitempty"` // StateMetadata: Optional. State properties user wish to include with // this state. Full replace of the current state_metadata. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "Etag") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Etag") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest: // Request for the `MarkRecommendationClaimed` Method. type GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest struct { // Etag: Required. Fingerprint of the Recommendation. Provides // optimistic locking. Etag string `json:"etag,omitempty"` // StateMetadata: State properties to include with this state. // Overwrites any existing `state_metadata`. Keys must match the regex // /^a-z0-9{0,62}$/. Values must match the regex // /^[a-zA-Z0-9_./-]{0,255}$/. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "Etag") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Etag") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest: Request // for the `MarkRecommendationFailed` Method. type GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest struct { // Etag: Required. Fingerprint of the Recommendation. Provides // optimistic locking. Etag string `json:"etag,omitempty"` // StateMetadata: State properties to include with this state. // Overwrites any existing `state_metadata`. Keys must match the regex // /^a-z0-9{0,62}$/. Values must match the regex // /^[a-zA-Z0-9_./-]{0,255}$/. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "Etag") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Etag") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest: // Request for the `MarkRecommendationSucceeded` Method. type GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest struct { // Etag: Required. Fingerprint of the Recommendation. Provides // optimistic locking. Etag string `json:"etag,omitempty"` // StateMetadata: State properties to include with this state. // Overwrites any existing `state_metadata`. Keys must match the regex // /^a-z0-9{0,62}$/. Values must match the regex // /^[a-zA-Z0-9_./-]{0,255}$/. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "Etag") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Etag") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1Operation: Contains an operation for a // resource loosely based on the JSON-PATCH format with support for: * // Custom filters for describing partial array patch. * Extended path // values for describing nested arrays. * Custom fields for describing // the resource for which the operation is being described. * Allows // extension to custom operations not natively supported by RFC6902. See // https://tools.ietf.org/html/rfc6902 for details on the original RFC. type GoogleCloudRecommenderV1beta1Operation struct { // Action: Type of this operation. Contains one of 'and', 'remove', // 'replace', 'move', 'copy', 'test' and 'custom' operations. This field // is case-insensitive and always populated. Action string `json:"action,omitempty"` // Path: Path to the target field being operated on. If the operation is // at the resource level, then path should be "/". This field is always // populated. Path string `json:"path,omitempty"` // PathFilters: Set of filters to apply if `path` refers to array // elements or nested array elements in order to narrow down to a single // unique element that is being tested/modified. This is intended to be // an exact match per filter. To perform advanced matching, use // path_value_matchers. * Example: { "/versions/*/name" : "it-123" // "/versions/*/targetSize/percent": 20 } * Example: { // "/bindings/*/role": "roles/admin" "/bindings/*/condition" : null } * // Example: { "/bindings/*/role": "roles/admin" "/bindings/*/members/*" // : ["[email protected]", "[email protected]"] } When both path_filters and // path_value_matchers are set, an implicit AND must be performed. PathFilters googleapi.RawMessage `json:"pathFilters,omitempty"` // PathValueMatchers: Similar to path_filters, this contains set of // filters to apply if `path` field referes to array elements. This is // meant to support value matching beyond exact match. To perform exact // match, use path_filters. When both path_filters and // path_value_matchers are set, an implicit AND must be performed. PathValueMatchers map[string]GoogleCloudRecommenderV1beta1ValueMatcher `json:"pathValueMatchers,omitempty"` // Resource: Contains the fully qualified resource name. This field is // always populated. ex: // //cloudresourcemanager.googleapis.com/projects/foo. Resource string `json:"resource,omitempty"` // ResourceType: Type of GCP resource being modified/tested. This field // is always populated. Example: // cloudresourcemanager.googleapis.com/Project, // compute.googleapis.com/Instance ResourceType string `json:"resourceType,omitempty"` // SourcePath: Can be set with action 'copy' or 'move' to indicate the // source field within resource or source_resource, ignored if provided // for other operation types. SourcePath string `json:"sourcePath,omitempty"` // SourceResource: Can be set with action 'copy' to copy resource // configuration across different resources of the same type. Example: A // resource clone can be done via action = 'copy', path = "/", from = // "/", source_resource = and resource_name = . This field is empty for // all other values of `action`. SourceResource string `json:"sourceResource,omitempty"` // Value: Value for the `path` field. Will be set for // actions:'add'/'replace'. Maybe set for action: 'test'. Either this or // `value_matcher` will be set for 'test' operation. An exact match must // be performed. Value interface{} `json:"value,omitempty"` // ValueMatcher: Can be set for action 'test' for advanced matching for // the value of 'path' field. Either this or `value` will be set for // 'test' operation. ValueMatcher *GoogleCloudRecommenderV1beta1ValueMatcher `json:"valueMatcher,omitempty"` // ForceSendFields is a list of field names (e.g. "Action") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Action") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1Operation) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1Operation raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1OperationGroup: Group of operations that // need to be performed atomically. type GoogleCloudRecommenderV1beta1OperationGroup struct { // Operations: List of operations across one or more resources that // belong to this group. Loosely based on RFC6902 and should be // performed in the order they appear. Operations []*GoogleCloudRecommenderV1beta1Operation `json:"operations,omitempty"` // ForceSendFields is a list of field names (e.g. "Operations") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Operations") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1OperationGroup) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1OperationGroup raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1Recommendation: A recommendation along // with a suggested action. E.g., a rightsizing recommendation for an // underutilized VM, IAM role recommendations, etc type GoogleCloudRecommenderV1beta1Recommendation struct { // AdditionalImpact: Optional set of additional impact that this // recommendation may have when trying to optimize for the primary // category. These may be positive or negative. AdditionalImpact []*GoogleCloudRecommenderV1beta1Impact `json:"additionalImpact,omitempty"` // AssociatedInsights: Insights that led to this recommendation. AssociatedInsights []*GoogleCloudRecommenderV1beta1RecommendationInsightReference `json:"associatedInsights,omitempty"` // Content: Content of the recommendation describing recommended changes // to resources. Content *GoogleCloudRecommenderV1beta1RecommendationContent `json:"content,omitempty"` // Description: Free-form human readable summary in English. The maximum // length is 500 characters. Description string `json:"description,omitempty"` // Etag: Fingerprint of the Recommendation. Provides optimistic locking // when updating states. Etag string `json:"etag,omitempty"` // LastRefreshTime: Last time this recommendation was refreshed by the // system that created it in the first place. LastRefreshTime string `json:"lastRefreshTime,omitempty"` // Name: Name of recommendation. Name string `json:"name,omitempty"` // PrimaryImpact: The primary impact that this recommendation can have // while trying to optimize for one category. PrimaryImpact *GoogleCloudRecommenderV1beta1Impact `json:"primaryImpact,omitempty"` // RecommenderSubtype: Contains an identifier for a subtype of // recommendations produced for the same recommender. Subtype is a // function of content and impact, meaning a new subtype might be added // when significant changes to `content` or `primary_impact.category` // are introduced. See the Recommenders section to see a list of // subtypes for a given Recommender. Examples: For recommender = // "google.iam.policy.Recommender", recommender_subtype can be one of // "REMOVE_ROLE"/"REPLACE_ROLE" RecommenderSubtype string `json:"recommenderSubtype,omitempty"` // StateInfo: Information for state. Contains state and metadata. StateInfo *GoogleCloudRecommenderV1beta1RecommendationStateInfo `json:"stateInfo,omitempty"` // ServerResponse contains the HTTP response code and headers from the // server. googleapi.ServerResponse `json:"-"` // ForceSendFields is a list of field names (e.g. "AdditionalImpact") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "AdditionalImpact") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1Recommendation) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1Recommendation raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1RecommendationContent: Contains what // resources are changing and how they are changing. type GoogleCloudRecommenderV1beta1RecommendationContent struct { // OperationGroups: Operations to one or more Google Cloud resources // grouped in such a way that, all operations within one group are // expected to be performed atomically and in an order. OperationGroups []*GoogleCloudRecommenderV1beta1OperationGroup `json:"operationGroups,omitempty"` // ForceSendFields is a list of field names (e.g. "OperationGroups") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "OperationGroups") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1RecommendationContent) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1RecommendationContent raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1RecommendationInsightReference: // Reference to an associated insight. type GoogleCloudRecommenderV1beta1RecommendationInsightReference struct { // Insight: Insight resource name, e.g. // projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_T // YPE_ID]/insights/[INSIGHT_ID] Insight string `json:"insight,omitempty"` // ForceSendFields is a list of field names (e.g. "Insight") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "Insight") to include in // API requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1RecommendationInsightReference) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1RecommendationInsightReference raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1RecommendationStateInfo: Information for // state. Contains state and metadata. type GoogleCloudRecommenderV1beta1RecommendationStateInfo struct { // State: The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED. // // Possible values: // "STATE_UNSPECIFIED" - Default state. Don't use directly. // "ACTIVE" - Recommendation is active and can be applied. // Recommendations content can be updated by Google. ACTIVE // recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. // "CLAIMED" - Recommendation is in claimed state. Recommendations // content is immutable and cannot be updated by Google. CLAIMED // recommendations can be marked as CLAIMED, SUCCEEDED, or FAILED. // "SUCCEEDED" - Recommendation is in succeeded state. Recommendations // content is immutable and cannot be updated by Google. SUCCEEDED // recommendations can be marked as SUCCEEDED, or FAILED. // "FAILED" - Recommendation is in failed state. Recommendations // content is immutable and cannot be updated by Google. FAILED // recommendations can be marked as SUCCEEDED, or FAILED. // "DISMISSED" - Recommendation is in dismissed state. Recommendation // content can be updated by Google. DISMISSED recommendations can be // marked as ACTIVE. State string `json:"state,omitempty"` // StateMetadata: A map of metadata for the state, provided by user or // automations systems. StateMetadata map[string]string `json:"stateMetadata,omitempty"` // ForceSendFields is a list of field names (e.g. "State") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "State") to include in API // requests with the JSON null value. By default, fields with empty // values are omitted from API requests. However, any field with an // empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1RecommendationStateInfo) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1RecommendationStateInfo raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleCloudRecommenderV1beta1ValueMatcher: Contains various matching // options for values for a GCP resource field. type GoogleCloudRecommenderV1beta1ValueMatcher struct { // MatchesPattern: To be used for full regex matching. The regular // expression is using the Google RE2 syntax // (https://github.com/google/re2/wiki/Syntax), so to be used with // RE2::FullMatch MatchesPattern string `json:"matchesPattern,omitempty"` // ForceSendFields is a list of field names (e.g. "MatchesPattern") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "MatchesPattern") to // include in API requests with the JSON null value. By default, fields // with empty values are omitted from API requests. However, any field // with an empty value appearing in NullFields will be sent to the // server as null. It is an error if a field in this list has a // non-empty value. This may be used to include null fields in Patch // requests. NullFields []string `json:"-"` } func (s *GoogleCloudRecommenderV1beta1ValueMatcher) MarshalJSON() ([]byte, error) { type NoMethod GoogleCloudRecommenderV1beta1ValueMatcher raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // GoogleTypeMoney: Represents an amount of money with its currency // type. type GoogleTypeMoney struct { // CurrencyCode: The 3-letter currency code defined in ISO 4217. CurrencyCode string `json:"currencyCode,omitempty"` // Nanos: Number of nano (10^-9) units of the amount. The value must be // between -999,999,999 and +999,999,999 inclusive. If `units` is // positive, `nanos` must be positive or zero. If `units` is zero, // `nanos` can be positive, zero, or negative. If `units` is negative, // `nanos` must be negative or zero. For example $-1.75 is represented // as `units`=-1 and `nanos`=-750,000,000. Nanos int64 `json:"nanos,omitempty"` // Units: The whole units of the amount. For example if `currencyCode` // is "USD", then 1 unit is one US dollar. Units int64 `json:"units,omitempty,string"` // ForceSendFields is a list of field names (e.g. "CurrencyCode") to // unconditionally include in API requests. By default, fields with // empty values are omitted from API requests. However, any non-pointer, // non-interface field appearing in ForceSendFields will be sent to the // server regardless of whether the field is empty or not. This may be // used to include empty fields in Patch requests. ForceSendFields []string `json:"-"` // NullFields is a list of field names (e.g. "CurrencyCode") to include // in API requests with the JSON null value. By default, fields with // empty values are omitted from API requests. However, any field with // an empty value appearing in NullFields will be sent to the server as // null. It is an error if a field in this list has a non-empty value. // This may be used to include null fields in Patch requests. NullFields []string `json:"-"` } func (s *GoogleTypeMoney) MarshalJSON() ([]byte, error) { type NoMethod GoogleTypeMoney raw := NoMethod(*s) return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields) } // method id "recommender.projects.locations.insightTypes.insights.get": type ProjectsLocationsInsightTypesInsightsGetCall struct { s *Service name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Gets the requested insight. Requires the recommender.*.get IAM // permission for the specified insight type. func (r *ProjectsLocationsInsightTypesInsightsService) Get(name string) *ProjectsLocationsInsightTypesInsightsGetCall { c := &ProjectsLocationsInsightTypesInsightsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsInsightTypesInsightsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsInsightTypesInsightsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLocationsInsightTypesInsightsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsInsightTypesInsightsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsInsightTypesInsightsGetCall) Context(ctx context.Context) *ProjectsLocationsInsightTypesInsightsGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsInsightTypesInsightsGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsInsightTypesInsightsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.insightTypes.insights.get" call. // Exactly one of *GoogleCloudRecommenderV1beta1Insight or error will be // non-nil. Any non-2xx status code is an error. Response headers are in // either *GoogleCloudRecommenderV1beta1Insight.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsInsightTypesInsightsGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Insight, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Insight{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Gets the requested insight. Requires the recommender.*.get IAM permission for the specified insight type.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/insightTypes/{insightTypesId}/insights/{insightsId}", // "httpMethod": "GET", // "id": "recommender.projects.locations.insightTypes.insights.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the insight.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/insightTypes/[^/]+/insights/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Insight" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "recommender.projects.locations.insightTypes.insights.list": type ProjectsLocationsInsightTypesInsightsListCall struct { s *Service parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Lists insights for a Cloud project. Requires the // recommender.*.list IAM permission for the specified insight type. func (r *ProjectsLocationsInsightTypesInsightsService) List(parent string) *ProjectsLocationsInsightTypesInsightsListCall { c := &ProjectsLocationsInsightTypesInsightsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // Filter sets the optional parameter "filter": Filter expression to // restrict the insights returned. Supported filter fields: state Eg: // `state:"DISMISSED" or state:"ACTIVE" func (c *ProjectsLocationsInsightTypesInsightsListCall) Filter(filter string) *ProjectsLocationsInsightTypesInsightsListCall { c.urlParams_.Set("filter", filter) return c } // PageSize sets the optional parameter "pageSize": The maximum number // of results to return from this request. Non-positive values are // ignored. If not specified, the server will determine the number of // results to return. func (c *ProjectsLocationsInsightTypesInsightsListCall) PageSize(pageSize int64) *ProjectsLocationsInsightTypesInsightsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": If present, // retrieves the next batch of results from the preceding call to this // method. `page_token` must be the value of `next_page_token` from the // previous response. The values of other method parameters must be // identical to those in the previous call. func (c *ProjectsLocationsInsightTypesInsightsListCall) PageToken(pageToken string) *ProjectsLocationsInsightTypesInsightsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsInsightTypesInsightsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsInsightTypesInsightsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLocationsInsightTypesInsightsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsInsightTypesInsightsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsInsightTypesInsightsListCall) Context(ctx context.Context) *ProjectsLocationsInsightTypesInsightsListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsInsightTypesInsightsListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsInsightTypesInsightsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/insights") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.insightTypes.insights.list" call. // Exactly one of *GoogleCloudRecommenderV1beta1ListInsightsResponse or // error will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1ListInsightsResponse.ServerResponse.Head // er or (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsInsightTypesInsightsListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1ListInsightsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1ListInsightsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Lists insights for a Cloud project. Requires the recommender.*.list IAM permission for the specified insight type.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/insightTypes/{insightTypesId}/insights", // "httpMethod": "GET", // "id": "recommender.projects.locations.insightTypes.insights.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "filter": { // "description": "Optional. Filter expression to restrict the insights returned. Supported filter fields: state Eg: `state:\"DISMISSED\" or state:\"ACTIVE\"", // "location": "query", // "type": "string" // }, // "pageSize": { // "description": "Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "Required. The container resource on which to execute the request. Acceptable formats: 1. \"projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]\", LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ INSIGHT_TYPE_ID refers to supported insight types: https://cloud.google.com/recommender/docs/insights/insight-types.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/insightTypes/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/insights", // "response": { // "$ref": "GoogleCloudRecommenderV1beta1ListInsightsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsLocationsInsightTypesInsightsListCall) Pages(ctx context.Context, f func(*GoogleCloudRecommenderV1beta1ListInsightsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "recommender.projects.locations.insightTypes.insights.markAccepted": type ProjectsLocationsInsightTypesInsightsMarkAcceptedCall struct { s *Service name string googlecloudrecommenderv1beta1markinsightacceptedrequest *GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // MarkAccepted: Marks the Insight State as Accepted. Users can use this // method to indicate to the Recommender API that they have applied some // action based on the insight. This stops the insight content from // being updated. MarkInsightAccepted can be applied to insights in // ACTIVE state. Requires the recommender.*.update IAM permission for // the specified insight. func (r *ProjectsLocationsInsightTypesInsightsService) MarkAccepted(name string, googlecloudrecommenderv1beta1markinsightacceptedrequest *GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest) *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall { c := &ProjectsLocationsInsightTypesInsightsMarkAcceptedCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.googlecloudrecommenderv1beta1markinsightacceptedrequest = googlecloudrecommenderv1beta1markinsightacceptedrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall) Fields(s ...googleapi.Field) *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall) Context(ctx context.Context) *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.googlecloudrecommenderv1beta1markinsightacceptedrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:markAccepted") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.insightTypes.insights.markAccepted" call. // Exactly one of *GoogleCloudRecommenderV1beta1Insight or error will be // non-nil. Any non-2xx status code is an error. Response headers are in // either *GoogleCloudRecommenderV1beta1Insight.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsInsightTypesInsightsMarkAcceptedCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Insight, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Insight{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Marks the Insight State as Accepted. Users can use this method to indicate to the Recommender API that they have applied some action based on the insight. This stops the insight content from being updated. MarkInsightAccepted can be applied to insights in ACTIVE state. Requires the recommender.*.update IAM permission for the specified insight.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/insightTypes/{insightTypesId}/insights/{insightsId}:markAccepted", // "httpMethod": "POST", // "id": "recommender.projects.locations.insightTypes.insights.markAccepted", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the insight.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/insightTypes/[^/]+/insights/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:markAccepted", // "request": { // "$ref": "GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest" // }, // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Insight" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "recommender.projects.locations.recommenders.recommendations.get": type ProjectsLocationsRecommendersRecommendationsGetCall struct { s *Service name string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // Get: Gets the requested recommendation. Requires the // recommender.*.get IAM permission for the specified recommender. func (r *ProjectsLocationsRecommendersRecommendationsService) Get(name string) *ProjectsLocationsRecommendersRecommendationsGetCall { c := &ProjectsLocationsRecommendersRecommendationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsRecommendersRecommendationsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsRecommendersRecommendationsGetCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLocationsRecommendersRecommendationsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsRecommendersRecommendationsGetCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsRecommendersRecommendationsGetCall) Context(ctx context.Context) *ProjectsLocationsRecommendersRecommendationsGetCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsRecommendersRecommendationsGetCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsRecommendersRecommendationsGetCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.recommenders.recommendations.get" call. // Exactly one of *GoogleCloudRecommenderV1beta1Recommendation or error // will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1Recommendation.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsRecommendersRecommendationsGetCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Recommendation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Recommendation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Gets the requested recommendation. Requires the recommender.*.get IAM permission for the specified recommender.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/recommenders/{recommendersId}/recommendations/{recommendationsId}", // "httpMethod": "GET", // "id": "recommender.projects.locations.recommenders.recommendations.get", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the recommendation.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}", // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Recommendation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "recommender.projects.locations.recommenders.recommendations.list": type ProjectsLocationsRecommendersRecommendationsListCall struct { s *Service parent string urlParams_ gensupport.URLParams ifNoneMatch_ string ctx_ context.Context header_ http.Header } // List: Lists recommendations for a Cloud project. Requires the // recommender.*.list IAM permission for the specified recommender. func (r *ProjectsLocationsRecommendersRecommendationsService) List(parent string) *ProjectsLocationsRecommendersRecommendationsListCall { c := &ProjectsLocationsRecommendersRecommendationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.parent = parent return c } // Filter sets the optional parameter "filter": Filter expression to // restrict the recommendations returned. Supported filter fields: // state_info.state Eg: `state_info.state:"DISMISSED" or // state_info.state:"FAILED" func (c *ProjectsLocationsRecommendersRecommendationsListCall) Filter(filter string) *ProjectsLocationsRecommendersRecommendationsListCall { c.urlParams_.Set("filter", filter) return c } // PageSize sets the optional parameter "pageSize": The maximum number // of results to return from this request. Non-positive values are // ignored. If not specified, the server will determine the number of // results to return. func (c *ProjectsLocationsRecommendersRecommendationsListCall) PageSize(pageSize int64) *ProjectsLocationsRecommendersRecommendationsListCall { c.urlParams_.Set("pageSize", fmt.Sprint(pageSize)) return c } // PageToken sets the optional parameter "pageToken": If present, // retrieves the next batch of results from the preceding call to this // method. `page_token` must be the value of `next_page_token` from the // previous response. The values of other method parameters must be // identical to those in the previous call. func (c *ProjectsLocationsRecommendersRecommendationsListCall) PageToken(pageToken string) *ProjectsLocationsRecommendersRecommendationsListCall { c.urlParams_.Set("pageToken", pageToken) return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsRecommendersRecommendationsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsRecommendersRecommendationsListCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // IfNoneMatch sets the optional parameter which makes the operation // fail if the object's ETag matches the given value. This is useful for // getting updates only after the object has changed since the last // request. Use googleapi.IsNotModified to check whether the response // error from Do is the result of In-None-Match. func (c *ProjectsLocationsRecommendersRecommendationsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsRecommendersRecommendationsListCall { c.ifNoneMatch_ = entityTag return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsRecommendersRecommendationsListCall) Context(ctx context.Context) *ProjectsLocationsRecommendersRecommendationsListCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsRecommendersRecommendationsListCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsRecommendersRecommendationsListCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) if c.ifNoneMatch_ != "" { reqHeaders.Set("If-None-Match", c.ifNoneMatch_) } var body io.Reader = nil c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+parent}/recommendations") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("GET", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "parent": c.parent, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.recommenders.recommendations.list" call. // Exactly one of // *GoogleCloudRecommenderV1beta1ListRecommendationsResponse or error // will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1ListRecommendationsResponse.ServerRespon // se.Header or (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsRecommendersRecommendationsListCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1ListRecommendationsResponse, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1ListRecommendationsResponse{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Lists recommendations for a Cloud project. Requires the recommender.*.list IAM permission for the specified recommender.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/recommenders/{recommendersId}/recommendations", // "httpMethod": "GET", // "id": "recommender.projects.locations.recommenders.recommendations.list", // "parameterOrder": [ // "parent" // ], // "parameters": { // "filter": { // "description": "Filter expression to restrict the recommendations returned. Supported filter fields: state_info.state Eg: `state_info.state:\"DISMISSED\" or state_info.state:\"FAILED\"", // "location": "query", // "type": "string" // }, // "pageSize": { // "description": "Optional. The maximum number of results to return from this request. Non-positive values are ignored. If not specified, the server will determine the number of results to return.", // "format": "int32", // "location": "query", // "type": "integer" // }, // "pageToken": { // "description": "Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters must be identical to those in the previous call.", // "location": "query", // "type": "string" // }, // "parent": { // "description": "Required. The container resource on which to execute the request. Acceptable formats: 1. \"projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]\", LOCATION here refers to GCP Locations: https://cloud.google.com/about/locations/ RECOMMENDER_ID refers to supported recommenders: https://cloud.google.com/recommender/docs/recommenders.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/recommenders/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+parent}/recommendations", // "response": { // "$ref": "GoogleCloudRecommenderV1beta1ListRecommendationsResponse" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // Pages invokes f for each page of results. // A non-nil error returned from f will halt the iteration. // The provided context supersedes any context provided to the Context method. func (c *ProjectsLocationsRecommendersRecommendationsListCall) Pages(ctx context.Context, f func(*GoogleCloudRecommenderV1beta1ListRecommendationsResponse) error) error { c.ctx_ = ctx defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point for { x, err := c.Do() if err != nil { return err } if err := f(x); err != nil { return err } if x.NextPageToken == "" { return nil } c.PageToken(x.NextPageToken) } } // method id "recommender.projects.locations.recommenders.recommendations.markClaimed": type ProjectsLocationsRecommendersRecommendationsMarkClaimedCall struct { s *Service name string googlecloudrecommenderv1beta1markrecommendationclaimedrequest *GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // MarkClaimed: Marks the Recommendation State as Claimed. Users can use // this method to indicate to the Recommender API that they are starting // to apply the recommendation themselves. This stops the recommendation // content from being updated. Associated insights are frozen and placed // in the ACCEPTED state. MarkRecommendationClaimed can be applied to // recommendations in CLAIMED or ACTIVE state. Requires the // recommender.*.update IAM permission for the specified recommender. func (r *ProjectsLocationsRecommendersRecommendationsService) MarkClaimed(name string, googlecloudrecommenderv1beta1markrecommendationclaimedrequest *GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest) *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall { c := &ProjectsLocationsRecommendersRecommendationsMarkClaimedCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.googlecloudrecommenderv1beta1markrecommendationclaimedrequest = googlecloudrecommenderv1beta1markrecommendationclaimedrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall) Fields(s ...googleapi.Field) *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall) Context(ctx context.Context) *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.googlecloudrecommenderv1beta1markrecommendationclaimedrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:markClaimed") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.recommenders.recommendations.markClaimed" call. // Exactly one of *GoogleCloudRecommenderV1beta1Recommendation or error // will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1Recommendation.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsRecommendersRecommendationsMarkClaimedCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Recommendation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Recommendation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Marks the Recommendation State as Claimed. Users can use this method to indicate to the Recommender API that they are starting to apply the recommendation themselves. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationClaimed can be applied to recommendations in CLAIMED or ACTIVE state. Requires the recommender.*.update IAM permission for the specified recommender.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/recommenders/{recommendersId}/recommendations/{recommendationsId}:markClaimed", // "httpMethod": "POST", // "id": "recommender.projects.locations.recommenders.recommendations.markClaimed", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the recommendation.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:markClaimed", // "request": { // "$ref": "GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest" // }, // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Recommendation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "recommender.projects.locations.recommenders.recommendations.markFailed": type ProjectsLocationsRecommendersRecommendationsMarkFailedCall struct { s *Service name string googlecloudrecommenderv1beta1markrecommendationfailedrequest *GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // MarkFailed: Marks the Recommendation State as Failed. Users can use // this method to indicate to the Recommender API that they have applied // the recommendation themselves, and the operation failed. This stops // the recommendation content from being updated. Associated insights // are frozen and placed in the ACCEPTED state. MarkRecommendationFailed // can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or // FAILED state. Requires the recommender.*.update IAM permission for // the specified recommender. func (r *ProjectsLocationsRecommendersRecommendationsService) MarkFailed(name string, googlecloudrecommenderv1beta1markrecommendationfailedrequest *GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest) *ProjectsLocationsRecommendersRecommendationsMarkFailedCall { c := &ProjectsLocationsRecommendersRecommendationsMarkFailedCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.googlecloudrecommenderv1beta1markrecommendationfailedrequest = googlecloudrecommenderv1beta1markrecommendationfailedrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsRecommendersRecommendationsMarkFailedCall) Fields(s ...googleapi.Field) *ProjectsLocationsRecommendersRecommendationsMarkFailedCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsRecommendersRecommendationsMarkFailedCall) Context(ctx context.Context) *ProjectsLocationsRecommendersRecommendationsMarkFailedCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsRecommendersRecommendationsMarkFailedCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsRecommendersRecommendationsMarkFailedCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.googlecloudrecommenderv1beta1markrecommendationfailedrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:markFailed") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.recommenders.recommendations.markFailed" call. // Exactly one of *GoogleCloudRecommenderV1beta1Recommendation or error // will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1Recommendation.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsRecommendersRecommendationsMarkFailedCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Recommendation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Recommendation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Marks the Recommendation State as Failed. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation failed. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationFailed can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/recommenders/{recommendersId}/recommendations/{recommendationsId}:markFailed", // "httpMethod": "POST", // "id": "recommender.projects.locations.recommenders.recommendations.markFailed", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the recommendation.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:markFailed", // "request": { // "$ref": "GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest" // }, // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Recommendation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } } // method id "recommender.projects.locations.recommenders.recommendations.markSucceeded": type ProjectsLocationsRecommendersRecommendationsMarkSucceededCall struct { s *Service name string googlecloudrecommenderv1beta1markrecommendationsucceededrequest *GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest urlParams_ gensupport.URLParams ctx_ context.Context header_ http.Header } // MarkSucceeded: Marks the Recommendation State as Succeeded. Users can // use this method to indicate to the Recommender API that they have // applied the recommendation themselves, and the operation was // successful. This stops the recommendation content from being updated. // Associated insights are frozen and placed in the ACCEPTED state. // MarkRecommendationSucceeded can be applied to recommendations in // ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the // recommender.*.update IAM permission for the specified recommender. func (r *ProjectsLocationsRecommendersRecommendationsService) MarkSucceeded(name string, googlecloudrecommenderv1beta1markrecommendationsucceededrequest *GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest) *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall { c := &ProjectsLocationsRecommendersRecommendationsMarkSucceededCall{s: r.s, urlParams_: make(gensupport.URLParams)} c.name = name c.googlecloudrecommenderv1beta1markrecommendationsucceededrequest = googlecloudrecommenderv1beta1markrecommendationsucceededrequest return c } // Fields allows partial responses to be retrieved. See // https://developers.google.com/gdata/docs/2.0/basics#PartialResponse // for more information. func (c *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall) Fields(s ...googleapi.Field) *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall { c.urlParams_.Set("fields", googleapi.CombineFields(s)) return c } // Context sets the context to be used in this call's Do method. Any // pending HTTP request will be aborted if the provided context is // canceled. func (c *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall) Context(ctx context.Context) *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall { c.ctx_ = ctx return c } // Header returns an http.Header that can be modified by the caller to // add HTTP headers to the request. func (c *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall) Header() http.Header { if c.header_ == nil { c.header_ = make(http.Header) } return c.header_ } func (c *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall) doRequest(alt string) (*http.Response, error) { reqHeaders := make(http.Header) reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20201020") for k, v := range c.header_ { reqHeaders[k] = v } reqHeaders.Set("User-Agent", c.s.userAgent()) var body io.Reader = nil body, err := googleapi.WithoutDataWrapper.JSONReader(c.googlecloudrecommenderv1beta1markrecommendationsucceededrequest) if err != nil { return nil, err } reqHeaders.Set("Content-Type", "application/json") c.urlParams_.Set("alt", alt) c.urlParams_.Set("prettyPrint", "false") urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta1/{+name}:markSucceeded") urls += "?" + c.urlParams_.Encode() req, err := http.NewRequest("POST", urls, body) if err != nil { return nil, err } req.Header = reqHeaders googleapi.Expand(req.URL, map[string]string{ "name": c.name, }) return gensupport.SendRequest(c.ctx_, c.s.client, req) } // Do executes the "recommender.projects.locations.recommenders.recommendations.markSucceeded" call. // Exactly one of *GoogleCloudRecommenderV1beta1Recommendation or error // will be non-nil. Any non-2xx status code is an error. Response // headers are in either // *GoogleCloudRecommenderV1beta1Recommendation.ServerResponse.Header or // (if a response was returned at all) in // error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check // whether the returned error was because http.StatusNotModified was // returned. func (c *ProjectsLocationsRecommendersRecommendationsMarkSucceededCall) Do(opts ...googleapi.CallOption) (*GoogleCloudRecommenderV1beta1Recommendation, error) { gensupport.SetOptions(c.urlParams_, opts...) res, err := c.doRequest("json") if res != nil && res.StatusCode == http.StatusNotModified { if res.Body != nil { res.Body.Close() } return nil, &googleapi.Error{ Code: res.StatusCode, Header: res.Header, } } if err != nil { return nil, err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { return nil, err } ret := &GoogleCloudRecommenderV1beta1Recommendation{ ServerResponse: googleapi.ServerResponse{ Header: res.Header, HTTPStatusCode: res.StatusCode, }, } target := &ret if err := gensupport.DecodeResponse(target, res); err != nil { return nil, err } return ret, nil // { // "description": "Marks the Recommendation State as Succeeded. Users can use this method to indicate to the Recommender API that they have applied the recommendation themselves, and the operation was successful. This stops the recommendation content from being updated. Associated insights are frozen and placed in the ACCEPTED state. MarkRecommendationSucceeded can be applied to recommendations in ACTIVE, CLAIMED, SUCCEEDED, or FAILED state. Requires the recommender.*.update IAM permission for the specified recommender.", // "flatPath": "v1beta1/projects/{projectsId}/locations/{locationsId}/recommenders/{recommendersId}/recommendations/{recommendationsId}:markSucceeded", // "httpMethod": "POST", // "id": "recommender.projects.locations.recommenders.recommendations.markSucceeded", // "parameterOrder": [ // "name" // ], // "parameters": { // "name": { // "description": "Required. Name of the recommendation.", // "location": "path", // "pattern": "^projects/[^/]+/locations/[^/]+/recommenders/[^/]+/recommendations/[^/]+$", // "required": true, // "type": "string" // } // }, // "path": "v1beta1/{+name}:markSucceeded", // "request": { // "$ref": "GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest" // }, // "response": { // "$ref": "GoogleCloudRecommenderV1beta1Recommendation" // }, // "scopes": [ // "https://www.googleapis.com/auth/cloud-platform" // ] // } }
{ rs := &ProjectsLocationsInsightTypesService{s: s} rs.Insights = NewProjectsLocationsInsightTypesInsightsService(s) return rs }
change_bds_instance_compartment_request_response.go
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. package bds import ( "github.com/oracle/oci-go-sdk/v46/common" "net/http" ) // ChangeBdsInstanceCompartmentRequest wrapper for the ChangeBdsInstanceCompartment operation // // See also // // Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/bds/ChangeBdsInstanceCompartment.go.html to see an example of how to use ChangeBdsInstanceCompartmentRequest. type ChangeBdsInstanceCompartmentRequest struct { // The OCID of the cluster. BdsInstanceId *string `mandatory:"true" contributesTo:"path" name:"bdsInstanceId"` // Details for the comparment change. ChangeBdsInstanceCompartmentDetails `contributesTo:"body"` // The client request ID for tracing. OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"` // For optimistic concurrency control. In the PUT or DELETE call // for a resource, set the `if-match` parameter to the value of the // etag from a previous GET or POST response for that resource. // The resource will be updated or deleted only if the etag you // provide matches the resource's current etag value. IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"` // A token that uniquely identifies a request so it can be retried in case of a timeout or // server error, without risk of executing that same action again. Retry tokens expire after 24 // hours but can be invalidated before then due to conflicting operations. For example, if a resource // has been deleted and purged from the system, then a retry of the original creation request // might be rejected. OpcRetryToken *string `mandatory:"false" contributesTo:"header" name:"opc-retry-token"` // Metadata about the request. This information will not be transmitted to the service, but // represents information that the SDK will consume to drive retry behavior. RequestMetadata common.RequestMetadata } func (request ChangeBdsInstanceCompartmentRequest) String() string { return common.PointerString(request) } // HTTPRequest implements the OCIRequest interface func (request ChangeBdsInstanceCompartmentRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error) { return common.MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path, request, extraHeaders) } // BinaryRequestBody implements the OCIRequest interface func (request ChangeBdsInstanceCompartmentRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) { return nil, false } // RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
} // ChangeBdsInstanceCompartmentResponse wrapper for the ChangeBdsInstanceCompartment operation type ChangeBdsInstanceCompartmentResponse struct { // The underlying http response RawResponse *http.Response // Unique Oracle-assigned identifier for the asynchronous request. You can use this to query status of the asynchronous operation. OpcWorkRequestId *string `presentIn:"header" name:"opc-work-request-id"` // Unique Oracle-assigned identifier for the request. If you need to contact // Oracle about a request, provide this request ID. OpcRequestId *string `presentIn:"header" name:"opc-request-id"` } func (response ChangeBdsInstanceCompartmentResponse) String() string { return common.PointerString(response) } // HTTPResponse implements the OCIResponse interface func (response ChangeBdsInstanceCompartmentResponse) HTTPResponse() *http.Response { return response.RawResponse }
func (request ChangeBdsInstanceCompartmentRequest) RetryPolicy() *common.RetryPolicy { return request.RequestMetadata.RetryPolicy
User.ts
import { Column, Entity, OneToMany, PrimaryColumn } from "../../../../src" import { Photo } from "./Photo" import { StringDecoder } from "string_decoder" @Entity() export class
{ @PrimaryColumn("binary", { length: 2, }) private _id: Buffer get id(): string { const decoder = new StringDecoder("hex") return decoder.end(this._id) } set id(value: string) { this._id = Buffer.from(value, "hex") } @Column() age: number @OneToMany((type) => Photo, (photo) => photo.user) photos: Photo[] }
User
tablet-v2_client_api.rs
// // This file was auto-generated, do not edit directly // /* Copyright 2014 © Stephen "Lyude" Chandler Paul Copyright 2015-2016 © Red Hat, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pub mod zwp_tablet_manager_v2 { //! controller object for graphic tablet devices //! //! An object that provides access to the graphics tablets available on this //! system. All tablets are associated with a seat, to get access to the //! actual tablets, use wp_tablet_manager.get_tablet_seat. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletManagerV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletManagerV2 {} unsafe impl Sync for ZwpTabletManagerV2 {} unsafe impl Proxy for ZwpTabletManagerV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletManagerV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletManagerV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletManagerV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletManagerV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletManagerV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_manager_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_manager_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletManagerV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletManagerV2 { ZwpTabletManagerV2 { ptr: self.ptr, data: self.data.clone() } } } const ZWP_TABLET_MANAGER_V2_GET_TABLET_SEAT: u32 = 0; const ZWP_TABLET_MANAGER_V2_DESTROY: u32 = 1; impl ZwpTabletManagerV2 { /// get the tablet seat /// /// Get the wp_tablet_seat object for the given seat. This object /// provides access to all graphics tablets in this seat. pub fn get_tablet_seat(&self, seat: &super::wl_seat::WlSeat) ->RequestResult<super::zwp_tablet_seat_v2::ZwpTabletSeatV2> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } let ptr = unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal_constructor, self.ptr(), ZWP_TABLET_MANAGER_V2_GET_TABLET_SEAT, &zwp_tablet_seat_v2_interface, ptr::null_mut::<wl_proxy>(), seat.ptr()) }; let proxy = unsafe { Proxy::from_ptr_new(ptr) }; RequestResult::Sent(proxy) } /// release the memory for the tablet manager object /// /// Destroy the wp_tablet_manager object. Objects created from this /// object are unaffected and should be destroyed separately. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_MANAGER_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_seat_v2 { //! controller object for graphic tablet devices of a seat //! //! An object that provides access to the graphics tablets available on this //! seat. After binding to this interface, the compositor sends a set of //! wp_tablet_seat.tablet_added and wp_tablet_seat.tool_added events. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletSeatV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletSeatV2 {} unsafe impl Sync for ZwpTabletSeatV2 {} unsafe impl Proxy for ZwpTabletSeatV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletSeatV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletSeatV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletSeatV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletSeatV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletSeatV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_seat_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_seat_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletSeatV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletSeatV2 { ZwpTabletSeatV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletSeatV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let id = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.tablet_added)(evq, idata, self, id); }, 1 => { let id = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.tool_added)(evq, idata, self, id); }, 2 => { let id = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.pad_added)(evq, idata, self, id); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } pub struct Implementation<ID> { /// new device notification /// /// This event is sent whenever a new tablet becomes available on this /// seat. This event only provides the object id of the tablet, any /// static information about the tablet (device name, vid/pid, etc.) is /// sent through the wp_tablet interface. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_seat_v2, id pub tablet_added: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_seat_v2: &ZwpTabletSeatV2, id: super::zwp_tablet_v2::ZwpTabletV2), /// a new tool has been used with a tablet /// /// This event is sent whenever a tool that has not previously been used /// with a tablet comes into use. This event only provides the object id /// of the tool; any static information about the tool (capabilities, /// type, etc.) is sent through the wp_tablet_tool interface. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_seat_v2, id pub tool_added: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_seat_v2: &ZwpTabletSeatV2, id: super::zwp_tablet_tool_v2::ZwpTabletToolV2), /// new pad notification /// /// This event is sent whenever a new pad is known to the system. Typically, /// pads are physically attached to tablets and a pad_added event is /// sent immediately after the wp_tablet_seat.tablet_added. /// However, some standalone pad devices logically attach to tablets at /// runtime, and the client must wait for wp_tablet_pad.enter to know /// the tablet a pad is attached to. /// /// This event only provides the object id of the pad. All further /// features (buttons, strips, rings) are sent through the wp_tablet_pad /// interface. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_seat_v2, id pub pad_added: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_seat_v2: &ZwpTabletSeatV2, id: super::zwp_tablet_pad_v2::ZwpTabletPadV2), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.tablet_added as usize == other.tablet_added as usize) && (self.tool_added as usize == other.tool_added as usize) && (self.pad_added as usize == other.pad_added as usize) } } const ZWP_TABLET_SEAT_V2_DESTROY: u32 = 0; impl ZwpTabletSeatV2 { /// release the memory for the tablet seat object /// /// Destroy the wp_tablet_seat object. Objects created from this /// object are unaffected and should be destroyed separately. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_SEAT_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_tool_v2 { //! a physical tablet tool //! //! An object that represents a physical tool that has been, or is //! currently in use with a tablet in this seat. Each wp_tablet_tool //! object stays valid until the client destroys it; the compositor //! reuses the wp_tablet_tool object to indicate that the object's //! respective physical tool has come into proximity of a tablet again. //! //! A wp_tablet_tool object's relation to a physical tool depends on the //! tablet's ability to report serial numbers. If the tablet supports //! this capability, then the object represents a specific physical tool //! and can be identified even when used on multiple tablets. //! //! A tablet tool has a number of static characteristics, e.g. tool type, //! hardware_serial and capabilities. These capabilities are sent in an //! event sequence after the wp_tablet_seat.tool_added event before any //! actual events from this tool. This initial event sequence is //! terminated by a wp_tablet_tool.done event. //! //! Tablet tool events are grouped by wp_tablet_tool.frame events. //! Any events received before a wp_tablet_tool.frame event should be //! considered part of the same hardware state change. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletToolV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletToolV2 {} unsafe impl Sync for ZwpTabletToolV2 {} unsafe impl Proxy for ZwpTabletToolV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletToolV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletToolV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletToolV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletToolV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletToolV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_tool_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_tool_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletToolV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletToolV2 { ZwpTabletToolV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletToolV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let tool_type = {match Type::from_raw(*(args.offset(0) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.type_)(evq, idata, self, tool_type); }, 1 => { let hardware_serial_hi = {*(args.offset(0) as *const u32)}; let hardware_serial_lo = {*(args.offset(1) as *const u32)}; (implementation.hardware_serial)(evq, idata, self, hardware_serial_hi, hardware_serial_lo); }, 2 => { let hardware_id_hi = {*(args.offset(0) as *const u32)}; let hardware_id_lo = {*(args.offset(1) as *const u32)}; (implementation.hardware_id_wacom)(evq, idata, self, hardware_id_hi, hardware_id_lo); }, 3 => { let capability = {match Capability::from_raw(*(args.offset(0) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.capability)(evq, idata, self, capability); }, 4 => { (implementation.done)(evq, idata, self); }, 5 => { (implementation.removed)(evq, idata, self); }, 6 => { let serial = {*(args.offset(0) as *const u32)}; let tablet = {Proxy::from_ptr_initialized(*(args.offset(1) as *const *mut wl_proxy))}; let surface = {Proxy::from_ptr_initialized(*(args.offset(2) as *const *mut wl_proxy))}; (implementation.proximity_in)(evq, idata, self, serial, &tablet, &surface); }, 7 => { (implementation.proximity_out)(evq, idata, self); }, 8 => { let serial = {*(args.offset(0) as *const u32)}; (implementation.down)(evq, idata, self, serial); }, 9 => { (implementation.up)(evq, idata, self); }, 10 => { let x = {wl_fixed_to_double(*(args.offset(0) as *const i32))}; let y = {wl_fixed_to_double(*(args.offset(1) as *const i32))}; (implementation.motion)(evq, idata, self, x, y); }, 11 => { let pressure = {*(args.offset(0) as *const u32)}; (implementation.pressure)(evq, idata, self, pressure); }, 12 => { let distance = {*(args.offset(0) as *const u32)}; (implementation.distance)(evq, idata, self, distance); }, 13 => { let tilt_x = {wl_fixed_to_double(*(args.offset(0) as *const i32))}; let tilt_y = {wl_fixed_to_double(*(args.offset(1) as *const i32))}; (implementation.tilt)(evq, idata, self, tilt_x, tilt_y); }, 14 => { let degrees = {wl_fixed_to_double(*(args.offset(0) as *const i32))}; (implementation.rotation)(evq, idata, self, degrees); }, 15 => { let position = {*(args.offset(0) as *const i32)}; (implementation.slider)(evq, idata, self, position); }, 16 => { let degrees = {wl_fixed_to_double(*(args.offset(0) as *const i32))}; let clicks = {*(args.offset(1) as *const i32)}; (implementation.wheel)(evq, idata, self, degrees, clicks); }, 17 => { let serial = {*(args.offset(0) as *const u32)}; let button = {*(args.offset(1) as *const u32)}; let state = {match ButtonState::from_raw(*(args.offset(2) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.button)(evq, idata, self, serial, button, state); }, 18 => { let time = {*(args.offset(0) as *const u32)}; (implementation.frame)(evq, idata, self, time); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } /// a physical tool type /// /// Describes the physical type of a tool. The physical type of a tool /// generally defines its base usage. /// /// The mouse tool represents a mouse-shaped tool that is not a relative /// device but bound to the tablet's surface, providing absolute /// coordinates. /// /// The lens tool is a mouse-shaped tool with an attached lens to /// provide precision focus. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum Type { /// Pen Pen = 0x140, /// Eraser Eraser = 0x141, /// Brush Brush = 0x142, /// Pencil Pencil = 0x143, /// Airbrush Airbrush = 0x144, /// Finger Finger = 0x145, /// Mouse Mouse = 0x146, /// Lens Lens = 0x147, } impl Type { pub fn from_raw(n: u32) -> Option<Type> { match n { 0x140 => Some(Type::Pen), 0x141 => Some(Type::Eraser), 0x142 => Some(Type::Brush), 0x143 => Some(Type::Pencil), 0x144 => Some(Type::Airbrush), 0x145 => Some(Type::Finger), 0x146 => Some(Type::Mouse), 0x147 => Some(Type::Lens), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } /// capability flags for a tool /// /// Describes extra capabilities on a tablet. /// /// Any tool must provide x and y values, extra axes are /// device-specific. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum Capability { /// Tilt axes Tilt = 1, /// Pressure axis Pressure = 2, /// Distance axis Distance = 3, /// Z-rotation axis Rotation = 4, /// Slider axis Slider = 5, /// Wheel axis Wheel = 6, } impl Capability { pub fn from_raw(n: u32) -> Option<Capability> { match n { 1 => Some(Capability::Tilt), 2 => Some(Capability::Pressure), 3 => Some(Capability::Distance), 4 => Some(Capability::Rotation), 5 => Some(Capability::Slider), 6 => Some(Capability::Wheel), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } /// physical button state /// /// Describes the physical state of a button that produced the button event. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum ButtonState { /// button is not pressed Released = 0, /// button is pressed Pressed = 1, } impl ButtonState { pub fn from_raw(n: u32) -> Option<ButtonState> { match n { 0 => Some(ButtonState::Released), 1 => Some(ButtonState::Pressed), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum Error { /// given wl_surface has another role Role = 0, } impl Error { pub fn from_raw(n: u32) -> Option<Error> { match n { 0 => Some(Error::Role), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } pub struct Implementation<ID> { /// tool type /// /// The tool type is the high-level type of the tool and usually decides /// the interaction expected from this tool. /// /// This event is sent in the initial burst of events before the /// wp_tablet_tool.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, tool_type pub type_: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, tool_type: Type), /// unique hardware serial number of the tool /// /// If the physical tool can be identified by a unique 64-bit serial /// number, this event notifies the client of this serial number. /// /// If multiple tablets are available in the same seat and the tool is /// uniquely identifiable by the serial number, that tool may move /// between tablets. /// /// Otherwise, if the tool has no serial number and this event is /// missing, the tool is tied to the tablet it first comes into /// proximity with. Even if the physical tool is used on multiple /// tablets, separate wp_tablet_tool objects will be created, one per /// tablet. /// /// This event is sent in the initial burst of events before the /// wp_tablet_tool.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, hardware_serial_hi, hardware_serial_lo pub hardware_serial: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, hardware_serial_hi: u32, hardware_serial_lo: u32), /// hardware id notification in Wacom's format /// /// This event notifies the client of a hardware id available on this tool. /// /// The hardware id is a device-specific 64-bit id that provides extra /// information about the tool in use, beyond the wl_tool.type /// enumeration. The format of the id is specific to tablets made by /// Wacom Inc. For example, the hardware id of a Wacom Grip /// Pen (a stylus) is 0x802. /// /// This event is sent in the initial burst of events before the /// wp_tablet_tool.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, hardware_id_hi, hardware_id_lo pub hardware_id_wacom: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, hardware_id_hi: u32, hardware_id_lo: u32), /// tool capability notification /// /// This event notifies the client of any capabilities of this tool, /// beyond the main set of x/y axes and tip up/down detection. /// /// One event is sent for each extra capability available on this tool. /// /// This event is sent in the initial burst of events before the /// wp_tablet_tool.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, capability pub capability: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, capability: Capability), /// tool description events sequence complete /// /// This event signals the end of the initial burst of descriptive /// events. A client may consider the static description of the tool to /// be complete and finalize initialization of the tool. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2 pub done: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2), /// tool removed /// /// This event is sent when the tool is removed from the system and will /// send no further events. Should the physical tool come back into /// proximity later, a new wp_tablet_tool object will be created. /// /// It is compositor-dependent when a tool is removed. A compositor may /// remove a tool on proximity out, tablet removal or any other reason. /// A compositor may also keep a tool alive until shutdown. /// /// If the tool is currently in proximity, a proximity_out event will be /// sent before the removed event. See wp_tablet_tool.proximity_out for /// the handling of any buttons logically down. /// /// When this event is received, the client must wp_tablet_tool.destroy /// the object. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2 pub removed: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2), /// proximity in event /// /// Notification that this tool is focused on a certain surface. /// /// This event can be received when the tool has moved from one surface to /// another, or when the tool has come back into proximity above the /// surface. /// /// If any button is logically down when the tool comes into proximity, /// the respective button event is sent after the proximity_in event but /// within the same frame as the proximity_in event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, serial, tablet, surface pub proximity_in: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, serial: u32, tablet: &super::zwp_tablet_v2::ZwpTabletV2, surface: &super::wl_surface::WlSurface), /// proximity out event /// /// Notification that this tool has either left proximity, or is no /// longer focused on a certain surface. /// /// When the tablet tool leaves proximity of the tablet, button release /// events are sent for each button that was held down at the time of /// leaving proximity. These events are sent before the proximity_out /// event but within the same wp_tablet.frame. /// /// If the tool stays within proximity of the tablet, but the focus /// changes from one surface to another, a button release event may not /// be sent until the button is actually released or the tool leaves the /// proximity of the tablet. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2 pub proximity_out: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2), /// tablet tool is making contact /// /// Sent whenever the tablet tool comes in contact with the surface of the /// tablet. /// /// If the tool is already in contact with the tablet when entering the /// input region, the client owning said region will receive a /// wp_tablet.proximity_in event, followed by a wp_tablet.down /// event and a wp_tablet.frame event. /// /// Note that this event describes logical contact, not physical /// contact. On some devices, a compositor may not consider a tool in /// logical contact until a minimum physical pressure threshold is /// exceeded. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, serial pub down: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, serial: u32), /// tablet tool is no longer making contact /// /// Sent whenever the tablet tool stops making contact with the surface of /// the tablet, or when the tablet tool moves out of the input region /// and the compositor grab (if any) is dismissed. /// /// If the tablet tool moves out of the input region while in contact /// with the surface of the tablet and the compositor does not have an /// ongoing grab on the surface, the client owning said region will /// receive a wp_tablet.up event, followed by a wp_tablet.proximity_out /// event and a wp_tablet.frame event. If the compositor has an ongoing /// grab on this device, this event sequence is sent whenever the grab /// is dismissed in the future. /// /// Note that this event describes logical contact, not physical /// contact. On some devices, a compositor may not consider a tool out /// of logical contact until physical pressure falls below a specific /// threshold. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2 pub up: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2), /// motion event /// /// Sent whenever a tablet tool moves. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, x, y pub motion: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, x: f64, y: f64), /// pressure change event /// /// Sent whenever the pressure axis on a tool changes. The value of this /// event is normalized to a value between 0 and 65535. /// /// Note that pressure may be nonzero even when a tool is not in logical /// contact. See the down and up events for more details. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, pressure pub pressure: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, pressure: u32), /// distance change event /// /// Sent whenever the distance axis on a tool changes. The value of this /// event is normalized to a value between 0 and 65535. /// /// Note that distance may be nonzero even when a tool is not in logical /// contact. See the down and up events for more details. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, distance pub distance: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, distance: u32), /// tilt change event /// /// Sent whenever one or both of the tilt axes on a tool change. Each tilt /// value is in degrees, relative to the z-axis of the tablet. /// The angle is positive when the top of a tool tilts along the /// positive x or y axis. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, tilt_x, tilt_y pub tilt: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, tilt_x: f64, tilt_y: f64), /// z-rotation change event /// /// Sent whenever the z-rotation axis on the tool changes. The /// rotation value is in degrees clockwise from the tool's /// logical neutral position. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, degrees pub rotation: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, degrees: f64), /// Slider position change event /// /// Sent whenever the slider position on the tool changes. The /// value is normalized between -65535 and 65535, with 0 as the logical /// neutral position of the slider. /// /// The slider is available on e.g. the Wacom Airbrush tool. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, position pub slider: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, position: i32), /// Wheel delta event /// /// Sent whenever the wheel on the tool emits an event. This event /// contains two values for the same axis change. The degrees value is /// in the same orientation as the wl_pointer.vertical_scroll axis. The /// clicks value is in discrete logical clicks of the mouse wheel. This /// value may be zero if the movement of the wheel was less /// than one logical click. /// /// Clients should choose either value and avoid mixing degrees and /// clicks. The compositor may accumulate values smaller than a logical /// click and emulate click events when a certain threshold is met. /// Thus, wl_tablet_tool.wheel events with non-zero clicks values may /// have different degrees values. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, degrees, clicks pub wheel: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, degrees: f64, clicks: i32), /// button event /// /// Sent whenever a button on the tool is pressed or released. /// /// If a button is held down when the tool moves in or out of proximity, /// button events are generated by the compositor. See /// wp_tablet_tool.proximity_in and wp_tablet_tool.proximity_out for /// details. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, serial, button, state pub button: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, serial: u32, button: u32, state: ButtonState), /// frame event /// /// Marks the end of a series of axis and/or button updates from the /// tablet. The Wayland protocol requires axis updates to be sent /// sequentially, however all events within a frame should be considered /// one hardware event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_tool_v2, time pub frame: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_tool_v2: &ZwpTabletToolV2, time: u32), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.type_ as usize == other.type_ as usize) && (self.hardware_serial as usize == other.hardware_serial as usize) && (self.hardware_id_wacom as usize == other.hardware_id_wacom as usize) && (self.capability as usize == other.capability as usize) && (self.done as usize == other.done as usize) && (self.removed as usize == other.removed as usize) && (self.proximity_in as usize == other.proximity_in as usize) && (self.proximity_out as usize == other.proximity_out as usize) && (self.down as usize == other.down as usize) && (self.up as usize == other.up as usize) && (self.motion as usize == other.motion as usize) && (self.pressure as usize == other.pressure as usize) && (self.distance as usize == other.distance as usize) && (self.tilt as usize == other.tilt as usize) && (self.rotation as usize == other.rotation as usize) && (self.slider as usize == other.slider as usize) && (self.wheel as usize == other.wheel as usize) && (self.button as usize == other.button as usize) && (self.frame as usize == other.frame as usize) } } const ZWP_TABLET_TOOL_V2_SET_CURSOR: u32 = 0; const ZWP_TABLET_TOOL_V2_DESTROY: u32 = 1; impl ZwpTabletToolV2 { /// set the tablet tool's surface /// /// Sets the surface of the cursor used for this tool on the given /// tablet. This request only takes effect if the tool is in proximity /// of one of the requesting client's surfaces or the surface parameter /// is the current pointer surface. If there was a previous surface set /// with this request it is replaced. If surface is NULL, the cursor /// image is hidden. /// /// The parameters hotspot_x and hotspot_y define the position of the /// pointer surface relative to the pointer location. Its top-left corner /// is always at (x, y) - (hotspot_x, hotspot_y), where (x, y) are the /// coordinates of the pointer location, in surface-local coordinates. /// /// On surface.attach requests to the pointer surface, hotspot_x and /// hotspot_y are decremented by the x and y parameters passed to the /// request. Attach must be confirmed by wl_surface.commit as usual. /// /// The hotspot can also be updated by passing the currently set pointer /// surface to this request with new values for hotspot_x and hotspot_y. /// /// The current and pending input regions of the wl_surface are cleared, /// and wl_surface.set_input_region is ignored until the wl_surface is no /// longer used as the cursor. When the use as a cursor ends, the current /// and pending input regions become undefined, and the wl_surface is /// unmapped. /// /// This request gives the surface the role of a wp_tablet_tool cursor. A /// surface may only ever be used as the cursor surface for one /// wp_tablet_tool. If the surface already has another role or has /// previously been used as cursor surface for a different tool, a /// protocol error is raised. pub fn set_cursor(&self, serial: u32, surface: Option<&super::wl_surface::WlSurface>, hotspot_x: i32, hotspot_y: i32) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_TOOL_V2_SET_CURSOR, serial, surface.map(Proxy::ptr).unwrap_or(ptr::null_mut()), hotspot_x, hotspot_y) }; RequestResult::Sent(()) } /// destroy the tool object /// /// This destroys the client's resource for this tool object. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_TOOL_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_v2 { //! graphics tablet device //! //! The wp_tablet interface represents one graphics tablet device. The //! tablet interface itself does not generate events; all events are //! generated by wp_tablet_tool objects when in proximity above a tablet. //! //! A tablet has a number of static characteristics, e.g. device name and //! pid/vid. These capabilities are sent in an event sequence after the //! wp_tablet_seat.tablet_added event. This initial event sequence is //! terminated by a wp_tablet.done event. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletV2 {} unsafe impl Sync for ZwpTabletV2 {} unsafe impl Proxy for ZwpTabletV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletV2 { ZwpTabletV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let name = {String::from_utf8_lossy(CStr::from_ptr(*(args.offset(0) as *const *const _)).to_bytes()).into_owned()}; (implementation.name)(evq, idata, self, name); }, 1 => { let vid = {*(args.offset(0) as *const u32)}; let pid = {*(args.offset(1) as *const u32)}; (implementation.id)(evq, idata, self, vid, pid); }, 2 => { let path = {String::from_utf8_lossy(CStr::from_ptr(*(args.offset(0) as *const *const _)).to_bytes()).into_owned()}; (implementation.path)(evq, idata, self, path); }, 3 => { (implementation.done)(evq, idata, self); }, 4 => { (implementation.removed)(evq, idata, self); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } pub struct Implementation<ID> { /// tablet device name /// /// This event is sent in the initial burst of events before the /// wp_tablet.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_v2, name pub name: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_v2: &ZwpTabletV2, name: String), /// tablet device USB vendor/product id /// /// This event is sent in the initial burst of events before the /// wp_tablet.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_v2, vid, pid pub id: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_v2: &ZwpTabletV2, vid: u32, pid: u32), /// path to the device /// /// A system-specific device path that indicates which device is behind /// this wp_tablet. This information may be used to gather additional /// information about the device, e.g. through libwacom. /// /// A device may have more than one device path. If so, multiple /// wp_tablet.path events are sent. A device may be emulated and not /// have a device path, and in that case this event will not be sent. /// /// The format of the path is unspecified, it may be a device node, a /// sysfs path, or some other identifier. It is up to the client to /// identify the string provided. /// /// This event is sent in the initial burst of events before the /// wp_tablet.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_v2, path pub path: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_v2: &ZwpTabletV2, path: String), /// tablet description events sequence complete /// /// This event is sent immediately to signal the end of the initial /// burst of descriptive events. A client may consider the static /// description of the tablet to be complete and finalize initialization /// of the tablet. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_v2 pub done: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_v2: &ZwpTabletV2), /// tablet removed event /// /// Sent when the tablet has been removed from the system. When a tablet /// is removed, some tools may be removed. /// /// When this event is received, the client must wp_tablet.destroy /// the object. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_v2 pub removed: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_v2: &ZwpTabletV2), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.name as usize == other.name as usize) && (self.id as usize == other.id as usize) && (self.path as usize == other.path as usize) && (self.done as usize == other.done as usize) && (self.removed as usize == other.removed as usize) } } const ZWP_TABLET_V2_DESTROY: u32 = 0; impl ZwpTabletV2 { /// destroy the tablet object /// /// This destroys the client's resource for this tablet object. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_pad_ring_v2 { //! pad ring //! //! A circular interaction area, such as the touch ring on the Wacom Intuos //! Pro series tablets. //! //! Events on a ring are logically grouped by the wl_tablet_pad_ring.frame //! event. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletPadRingV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletPadRingV2 {} unsafe impl Sync for ZwpTabletPadRingV2 {} unsafe impl Proxy for ZwpTabletPadRingV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletPadRingV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletPadRingV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletPadRingV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletPadRingV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletPadRingV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_pad_ring_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_pad_ring_v2" } fn su
-> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletPadRingV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletPadRingV2 { ZwpTabletPadRingV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletPadRingV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let source = {match Source::from_raw(*(args.offset(0) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.source)(evq, idata, self, source); }, 1 => { let degrees = {wl_fixed_to_double(*(args.offset(0) as *const i32))}; (implementation.angle)(evq, idata, self, degrees); }, 2 => { (implementation.stop)(evq, idata, self); }, 3 => { let time = {*(args.offset(0) as *const u32)}; (implementation.frame)(evq, idata, self, time); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } /// ring axis source /// /// Describes the source types for ring events. This indicates to the /// client how a ring event was physically generated; a client may /// adjust the user interface accordingly. For example, events /// from a "finger" source may trigger kinetic scrolling. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum Source { /// finger Finger = 1, } impl Source { pub fn from_raw(n: u32) -> Option<Source> { match n { 1 => Some(Source::Finger), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } pub struct Implementation<ID> { /// ring event source /// /// Source information for ring events. /// /// This event does not occur on its own. It is sent before a /// wp_tablet_pad_ring.frame event and carries the source information /// for all events within that frame. /// /// The source specifies how this event was generated. If the source is /// wp_tablet_pad_ring.source.finger, a wp_tablet_pad_ring.stop event /// will be sent when the user lifts the finger off the device. /// /// This event is optional. If the source is unknown for an interaction, /// no event is sent. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_ring_v2, source pub source: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_ring_v2: &ZwpTabletPadRingV2, source: Source), /// angle changed /// /// Sent whenever the angle on a ring changes. /// /// The angle is provided in degrees clockwise from the logical /// north of the ring in the pad's current rotation. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_ring_v2, degrees pub angle: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_ring_v2: &ZwpTabletPadRingV2, degrees: f64), /// interaction stopped /// /// Stop notification for ring events. /// /// For some wp_tablet_pad_ring.source types, a wp_tablet_pad_ring.stop /// event is sent to notify a client that the interaction with the ring /// has terminated. This enables the client to implement kinetic scrolling. /// See the wp_tablet_pad_ring.source documentation for information on /// when this event may be generated. /// /// Any wp_tablet_pad_ring.angle events with the same source after this /// event should be considered as the start of a new interaction. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_ring_v2 pub stop: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_ring_v2: &ZwpTabletPadRingV2), /// end of a ring event sequence /// /// Indicates the end of a set of ring events that logically belong /// together. A client is expected to accumulate the data in all events /// within the frame before proceeding. /// /// All wp_tablet_pad_ring events before a wp_tablet_pad_ring.frame event belong /// logically together. For example, on termination of a finger interaction /// on a ring the compositor will send a wp_tablet_pad_ring.source event, /// a wp_tablet_pad_ring.stop event and a wp_tablet_pad_ring.frame event. /// /// A wp_tablet_pad_ring.frame event is sent for every logical event /// group, even if the group only contains a single wp_tablet_pad_ring /// event. Specifically, a client may get a sequence: angle, frame, /// angle, frame, etc. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_ring_v2, time pub frame: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_ring_v2: &ZwpTabletPadRingV2, time: u32), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.source as usize == other.source as usize) && (self.angle as usize == other.angle as usize) && (self.stop as usize == other.stop as usize) && (self.frame as usize == other.frame as usize) } } const ZWP_TABLET_PAD_RING_V2_SET_FEEDBACK: u32 = 0; const ZWP_TABLET_PAD_RING_V2_DESTROY: u32 = 1; impl ZwpTabletPadRingV2 { /// set compositor feedback /// /// Request that the compositor use the provided feedback string /// associated with this ring. This request should be issued immediately /// after a wp_tablet_pad_group.mode_switch event from the corresponding /// group is received, or whenever the ring is mapped to a different /// action. See wp_tablet_pad_group.mode_switch for more details. /// /// Clients are encouraged to provide context-aware descriptions for /// the actions associated with the ring; compositors may use this /// information to offer visual feedback about the button layout /// (eg. on-screen displays). /// /// The provided string 'description' is a UTF-8 encoded string to be /// associated with this ring, and is considered user-visible; general /// internationalization rules apply. /// /// The serial argument will be that of the last /// wp_tablet_pad_group.mode_switch event received for the group of this /// ring. Requests providing other serials than the most recent one will be /// ignored. pub fn set_feedback(&self, description: String, serial: u32) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } let description = CString::new(description).unwrap_or_else(|_| panic!("Got a String with interior null in zwp_tablet_pad_ring_v2.set_feedback:description")); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_RING_V2_SET_FEEDBACK, description.as_ptr(), serial) }; RequestResult::Sent(()) } /// destroy the ring object /// /// This destroys the client's resource for this ring object. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_RING_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_pad_strip_v2 { //! pad strip //! //! A linear interaction area, such as the strips found in Wacom Cintiq //! models. //! //! Events on a strip are logically grouped by the wl_tablet_pad_strip.frame //! event. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletPadStripV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletPadStripV2 {} unsafe impl Sync for ZwpTabletPadStripV2 {} unsafe impl Proxy for ZwpTabletPadStripV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletPadStripV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletPadStripV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletPadStripV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletPadStripV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletPadStripV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_pad_strip_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_pad_strip_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletPadStripV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletPadStripV2 { ZwpTabletPadStripV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletPadStripV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let source = {match Source::from_raw(*(args.offset(0) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.source)(evq, idata, self, source); }, 1 => { let position = {*(args.offset(0) as *const u32)}; (implementation.position)(evq, idata, self, position); }, 2 => { (implementation.stop)(evq, idata, self); }, 3 => { let time = {*(args.offset(0) as *const u32)}; (implementation.frame)(evq, idata, self, time); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } /// strip axis source /// /// Describes the source types for strip events. This indicates to the /// client how a strip event was physically generated; a client may /// adjust the user interface accordingly. For example, events /// from a "finger" source may trigger kinetic scrolling. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum Source { /// finger Finger = 1, } impl Source { pub fn from_raw(n: u32) -> Option<Source> { match n { 1 => Some(Source::Finger), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } pub struct Implementation<ID> { /// strip event source /// /// Source information for strip events. /// /// This event does not occur on its own. It is sent before a /// wp_tablet_pad_strip.frame event and carries the source information /// for all events within that frame. /// /// The source specifies how this event was generated. If the source is /// wp_tablet_pad_strip.source.finger, a wp_tablet_pad_strip.stop event /// will be sent when the user lifts their finger off the device. /// /// This event is optional. If the source is unknown for an interaction, /// no event is sent. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_strip_v2, source pub source: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_strip_v2: &ZwpTabletPadStripV2, source: Source), /// position changed /// /// Sent whenever the position on a strip changes. /// /// The position is normalized to a range of [0, 65535], the 0-value /// represents the top-most and/or left-most position of the strip in /// the pad's current rotation. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_strip_v2, position pub position: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_strip_v2: &ZwpTabletPadStripV2, position: u32), /// interaction stopped /// /// Stop notification for strip events. /// /// For some wp_tablet_pad_strip.source types, a wp_tablet_pad_strip.stop /// event is sent to notify a client that the interaction with the strip /// has terminated. This enables the client to implement kinetic /// scrolling. See the wp_tablet_pad_strip.source documentation for /// information on when this event may be generated. /// /// Any wp_tablet_pad_strip.position events with the same source after this /// event should be considered as the start of a new interaction. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_strip_v2 pub stop: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_strip_v2: &ZwpTabletPadStripV2), /// end of a strip event sequence /// /// Indicates the end of a set of events that represent one logical /// hardware strip event. A client is expected to accumulate the data /// in all events within the frame before proceeding. /// /// All wp_tablet_pad_strip events before a wp_tablet_pad_strip.frame event belong /// logically together. For example, on termination of a finger interaction /// on a strip the compositor will send a wp_tablet_pad_strip.source event, /// a wp_tablet_pad_strip.stop event and a wp_tablet_pad_strip.frame /// event. /// /// A wp_tablet_pad_strip.frame event is sent for every logical event /// group, even if the group only contains a single wp_tablet_pad_strip /// event. Specifically, a client may get a sequence: position, frame, /// position, frame, etc. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_strip_v2, time pub frame: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_strip_v2: &ZwpTabletPadStripV2, time: u32), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.source as usize == other.source as usize) && (self.position as usize == other.position as usize) && (self.stop as usize == other.stop as usize) && (self.frame as usize == other.frame as usize) } } const ZWP_TABLET_PAD_STRIP_V2_SET_FEEDBACK: u32 = 0; const ZWP_TABLET_PAD_STRIP_V2_DESTROY: u32 = 1; impl ZwpTabletPadStripV2 { /// set compositor feedback /// /// Requests the compositor to use the provided feedback string /// associated with this strip. This request should be issued immediately /// after a wp_tablet_pad_group.mode_switch event from the corresponding /// group is received, or whenever the strip is mapped to a different /// action. See wp_tablet_pad_group.mode_switch for more details. /// /// Clients are encouraged to provide context-aware descriptions for /// the actions associated with the strip, and compositors may use this /// information to offer visual feedback about the button layout /// (eg. on-screen displays). /// /// The provided string 'description' is a UTF-8 encoded string to be /// associated with this ring, and is considered user-visible; general /// internationalization rules apply. /// /// The serial argument will be that of the last /// wp_tablet_pad_group.mode_switch event received for the group of this /// strip. Requests providing other serials than the most recent one will be /// ignored. pub fn set_feedback(&self, description: String, serial: u32) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } let description = CString::new(description).unwrap_or_else(|_| panic!("Got a String with interior null in zwp_tablet_pad_strip_v2.set_feedback:description")); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_STRIP_V2_SET_FEEDBACK, description.as_ptr(), serial) }; RequestResult::Sent(()) } /// destroy the strip object /// /// This destroys the client's resource for this strip object. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_STRIP_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_pad_group_v2 { //! a set of buttons, rings and strips //! //! A pad group describes a distinct (sub)set of buttons, rings and strips //! present in the tablet. The criteria of this grouping is usually positional, //! eg. if a tablet has buttons on the left and right side, 2 groups will be //! presented. The physical arrangement of groups is undisclosed and may //! change on the fly. //! //! Pad groups will announce their features during pad initialization. Between //! the corresponding wp_tablet_pad.group event and wp_tablet_pad_group.done, the //! pad group will announce the buttons, rings and strips contained in it, //! plus the number of supported modes. //! //! Modes are a mechanism to allow multiple groups of actions for every element //! in the pad group. The number of groups and available modes in each is //! persistent across device plugs. The current mode is user-switchable, it //! will be announced through the wp_tablet_pad_group.mode_switch event both //! whenever it is switched, and after wp_tablet_pad.enter. //! //! The current mode logically applies to all elements in the pad group, //! although it is at clients' discretion whether to actually perform different //! actions, and/or issue the respective .set_feedback requests to notify the //! compositor. See the wp_tablet_pad_group.mode_switch event for more details. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletPadGroupV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletPadGroupV2 {} unsafe impl Sync for ZwpTabletPadGroupV2 {} unsafe impl Proxy for ZwpTabletPadGroupV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletPadGroupV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletPadGroupV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletPadGroupV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletPadGroupV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletPadGroupV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_pad_group_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_pad_group_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletPadGroupV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletPadGroupV2 { ZwpTabletPadGroupV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletPadGroupV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let buttons = {let array = *(args.offset(0) as *const *mut wl_array); ::std::slice::from_raw_parts((*array).data as *const u8, (*array).size as usize).to_owned()}; (implementation.buttons)(evq, idata, self, buttons); }, 1 => { let ring = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.ring)(evq, idata, self, ring); }, 2 => { let strip = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.strip)(evq, idata, self, strip); }, 3 => { let modes = {*(args.offset(0) as *const u32)}; (implementation.modes)(evq, idata, self, modes); }, 4 => { (implementation.done)(evq, idata, self); }, 5 => { let time = {*(args.offset(0) as *const u32)}; let serial = {*(args.offset(1) as *const u32)}; let mode = {*(args.offset(2) as *const u32)}; (implementation.mode_switch)(evq, idata, self, time, serial, mode); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } pub struct Implementation<ID> { /// buttons announced /// /// Sent on wp_tablet_pad_group initialization to announce the available /// buttons in the group. Button indices start at 0, a button may only be /// in one group at a time. /// /// This event is first sent in the initial burst of events before the /// wp_tablet_pad_group.done event. /// /// Some buttons are reserved by the compositor. These buttons may not be /// assigned to any wp_tablet_pad_group. Compositors may broadcast this /// event in the case of changes to the mapping of these reserved buttons. /// If the compositor happens to reserve all buttons in a group, this event /// will be sent with an empty array. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2, buttons pub buttons: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2, buttons: Vec<u8>), /// ring announced /// /// Sent on wp_tablet_pad_group initialization to announce available rings. /// One event is sent for each ring available on this pad group. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad_group.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2, ring pub ring: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2, ring: super::zwp_tablet_pad_ring_v2::ZwpTabletPadRingV2), /// strip announced /// /// Sent on wp_tablet_pad initialization to announce available strips. /// One event is sent for each strip available on this pad group. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad_group.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2, strip pub strip: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2, strip: super::zwp_tablet_pad_strip_v2::ZwpTabletPadStripV2), /// mode-switch ability announced /// /// Sent on wp_tablet_pad_group initialization to announce that the pad /// group may switch between modes. A client may use a mode to store a /// specific configuration for buttons, rings and strips and use the /// wl_tablet_pad_group.mode_switch event to toggle between these /// configurations. Mode indices start at 0. /// /// Switching modes is compositor-dependent. See the /// wp_tablet_pad_group.mode_switch event for more details. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad_group.done event. This event is only sent when more than /// more than one mode is available. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2, modes pub modes: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2, modes: u32), /// tablet group description events sequence complete /// /// This event is sent immediately to signal the end of the initial /// burst of descriptive events. A client may consider the static /// description of the tablet to be complete and finalize initialization /// of the tablet group. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2 pub done: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2), /// mode switch event /// /// Notification that the mode was switched. /// /// A mode applies to all buttons, rings and strips in a group /// simultaneously, but a client is not required to assign different actions /// for each mode. For example, a client may have mode-specific button /// mappings but map the ring to vertical scrolling in all modes. Mode /// indices start at 0. /// /// Switching modes is compositor-dependent. The compositor may provide /// visual cues to the client about the mode, e.g. by toggling LEDs on /// the tablet device. Mode-switching may be software-controlled or /// controlled by one or more physical buttons. For example, on a Wacom /// Intuos Pro, the button inside the ring may be assigned to switch /// between modes. /// /// The compositor will also send this event after wp_tablet_pad.enter on /// each group in order to notify of the current mode. Groups that only /// feature one mode will use mode=0 when emitting this event. /// /// If a button action in the new mode differs from the action in the /// previous mode, the client should immediately issue a /// wp_tablet_pad.set_feedback request for each changed button. /// /// If a ring or strip action in the new mode differs from the action /// in the previous mode, the client should immediately issue a /// wp_tablet_ring.set_feedback or wp_tablet_strip.set_feedback request /// for each changed ring or strip. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_group_v2, time, serial, mode pub mode_switch: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_group_v2: &ZwpTabletPadGroupV2, time: u32, serial: u32, mode: u32), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.buttons as usize == other.buttons as usize) && (self.ring as usize == other.ring as usize) && (self.strip as usize == other.strip as usize) && (self.modes as usize == other.modes as usize) && (self.done as usize == other.done as usize) && (self.mode_switch as usize == other.mode_switch as usize) } } const ZWP_TABLET_PAD_GROUP_V2_DESTROY: u32 = 0; impl ZwpTabletPadGroupV2 { /// destroy the pad object /// /// Destroy the wp_tablet_pad_group object. Objects created from this object /// are unaffected and should be destroyed separately. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_GROUP_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } } pub mod zwp_tablet_pad_v2 { //! a set of buttons, rings and strips //! //! A pad device is a set of buttons, rings and strips //! usually physically present on the tablet device itself. Some //! exceptions exist where the pad device is physically detached, e.g. the //! Wacom ExpressKey Remote. //! //! Pad devices have no axes that control the cursor and are generally //! auxiliary devices to the tool devices used on the tablet surface. //! //! A pad device has a number of static characteristics, e.g. the number //! of rings. These capabilities are sent in an event sequence after the //! wp_tablet_seat.pad_added event before any actual events from this pad. //! This initial event sequence is terminated by a wp_tablet_pad.done //! event. //! //! All pad features (buttons, rings and strips) are logically divided into //! groups and all pads have at least one group. The available groups are //! notified through the wp_tablet_pad.group event; the compositor will //! emit one event per group before emitting wp_tablet_pad.done. //! //! Groups may have multiple modes. Modes allow clients to map multiple //! actions to a single pad feature. Only one mode can be active per group, //! although different groups may have different active modes. use super::EventQueueHandle; use super::Proxy; use super::RequestResult; use super::{Liveness, Implementable}; use super::interfaces::*; use wayland_sys::common::*; use std::any::Any; use std::ffi::{CString,CStr}; use std::os::raw::c_void; use std::ptr; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicPtr, Ordering}; use wayland_sys::RUST_MANAGED; use wayland_sys::client::*; type UserData = (*mut EventQueueHandle, Option<Box<Any>>, Arc<(AtomicBool, AtomicPtr<()>)>); pub struct ZwpTabletPadV2 { ptr: *mut wl_proxy, data: Option<Arc<(AtomicBool, AtomicPtr<()>)>> } unsafe impl Send for ZwpTabletPadV2 {} unsafe impl Sync for ZwpTabletPadV2 {} unsafe impl Proxy for ZwpTabletPadV2 { fn ptr(&self) -> *mut wl_proxy { self.ptr } unsafe fn from_ptr_new(ptr: *mut wl_proxy) -> ZwpTabletPadV2 { let data: *mut UserData = Box::into_raw(Box::new(( ptr::null_mut(), Option::None, Arc::new((AtomicBool::new(true), AtomicPtr::new(ptr::null_mut()))), ))); ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_set_user_data, ptr, data as *mut c_void); ZwpTabletPadV2 { ptr: ptr, data: Some((&*data).2.clone()) } } unsafe fn from_ptr_initialized(ptr: *mut wl_proxy) -> ZwpTabletPadV2 { let implem = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_listener, ptr); let rust_managed = implem == &RUST_MANAGED as *const _ as *const _; if rust_managed { let data = ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, ptr) as *mut UserData; ZwpTabletPadV2 { ptr: ptr, data: Some((&*data).2.clone()) } } else { ZwpTabletPadV2 { ptr: ptr, data: Option::None } } } fn interface_ptr() -> *const wl_interface { unsafe { &zwp_tablet_pad_v2_interface } } fn interface_name() -> &'static str { "zwp_tablet_pad_v2" } fn supported_version() -> u32 { 1 } fn version(&self) -> u32 { unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_version, self.ptr()) } } fn status(&self) -> Liveness { if let Some(ref data) = self.data { if data.0.load(Ordering::SeqCst) { Liveness::Alive } else { Liveness::Dead } } else { Liveness::Unmanaged } } fn equals(&self, other: &ZwpTabletPadV2) -> bool { self.status() != Liveness::Dead && other.status() != Liveness::Dead && self.ptr == other.ptr } fn set_user_data(&self, ptr: *mut ()) { if let Some(ref data) = self.data { data.1.store(ptr, Ordering::SeqCst); } } fn get_user_data(&self) -> *mut () { if let Some(ref data) = self.data { data.1.load(Ordering::SeqCst) } else { ::std::ptr::null_mut() } } unsafe fn clone_unchecked(&self) -> ZwpTabletPadV2 { ZwpTabletPadV2 { ptr: self.ptr, data: self.data.clone() } } } unsafe impl<ID: 'static> Implementable<ID> for ZwpTabletPadV2 { type Implementation = Implementation<ID>; #[allow(unused_mut,unused_assignments)] unsafe fn __dispatch_msg(&self, opcode: u32, args: *const wl_argument) -> Result<(),()> { let data = &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData); let evq = &mut *(data.0); let mut kill = false; { let &mut (ref implementation, ref mut idata) = data.1.as_mut().unwrap().downcast_mut::<(Implementation<ID>, ID)>().unwrap(); match opcode { 0 => { let pad_group = {Proxy::from_ptr_new(*(args.offset(0) as *const *mut wl_proxy))}; (implementation.group)(evq, idata, self, pad_group); }, 1 => { let path = {String::from_utf8_lossy(CStr::from_ptr(*(args.offset(0) as *const *const _)).to_bytes()).into_owned()}; (implementation.path)(evq, idata, self, path); }, 2 => { let buttons = {*(args.offset(0) as *const u32)}; (implementation.buttons)(evq, idata, self, buttons); }, 3 => { (implementation.done)(evq, idata, self); }, 4 => { let time = {*(args.offset(0) as *const u32)}; let button = {*(args.offset(1) as *const u32)}; let state = {match ButtonState::from_raw(*(args.offset(2) as *const u32)) { Some(v) => v, Option::None => return Err(()) }}; (implementation.button)(evq, idata, self, time, button, state); }, 5 => { let serial = {*(args.offset(0) as *const u32)}; let tablet = {Proxy::from_ptr_initialized(*(args.offset(1) as *const *mut wl_proxy))}; let surface = {Proxy::from_ptr_initialized(*(args.offset(2) as *const *mut wl_proxy))}; (implementation.enter)(evq, idata, self, serial, &tablet, &surface); }, 6 => { let serial = {*(args.offset(0) as *const u32)}; let surface = {Proxy::from_ptr_initialized(*(args.offset(1) as *const *mut wl_proxy))}; (implementation.leave)(evq, idata, self, serial, &surface); }, 7 => { (implementation.removed)(evq, idata, self); }, _ => return Err(()) } } if kill { let _impl = data.1.take(); ::std::mem::drop(_impl); } Ok(()) } } /// physical button state /// /// Describes the physical state of a button that caused the button /// event. #[repr(u32)] #[derive(Copy,Clone,Debug,PartialEq)] pub enum ButtonState { /// the button is not pressed Released = 0, /// the button is pressed Pressed = 1, } impl ButtonState { pub fn from_raw(n: u32) -> Option<ButtonState> { match n { 0 => Some(ButtonState::Released), 1 => Some(ButtonState::Pressed), _ => Option::None } } pub fn to_raw(&self) -> u32 { *self as u32 } } pub struct Implementation<ID> { /// group announced /// /// Sent on wp_tablet_pad initialization to announce available groups. /// One event is sent for each pad group available. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad.done event. At least one group will be announced. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, pad_group pub group: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, pad_group: super::zwp_tablet_pad_group_v2::ZwpTabletPadGroupV2), /// path to the device /// /// A system-specific device path that indicates which device is behind /// this wp_tablet_pad. This information may be used to gather additional /// information about the device, e.g. through libwacom. /// /// The format of the path is unspecified, it may be a device node, a /// sysfs path, or some other identifier. It is up to the client to /// identify the string provided. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad.done event. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, path pub path: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, path: String), /// buttons announced /// /// Sent on wp_tablet_pad initialization to announce the available /// buttons. /// /// This event is sent in the initial burst of events before the /// wp_tablet_pad.done event. This event is only sent when at least one /// button is available. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, buttons pub buttons: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, buttons: u32), /// pad description event sequence complete /// /// This event signals the end of the initial burst of descriptive /// events. A client may consider the static description of the pad to /// be complete and finalize initialization of the pad. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2 pub done: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2), /// physical button state /// /// Sent whenever the physical state of a button changes. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, time, button, state pub button: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, time: u32, button: u32, state: ButtonState), /// enter event /// /// Notification that this pad is focused on the specified surface. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, serial, tablet, surface pub enter: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, serial: u32, tablet: &super::zwp_tablet_v2::ZwpTabletV2, surface: &super::wl_surface::WlSurface), /// enter event /// /// Notification that this pad is no longer focused on the specified /// surface. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2, serial, surface pub leave: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2, serial: u32, surface: &super::wl_surface::WlSurface), /// pad removed event /// /// Sent when the pad has been removed from the system. When a tablet /// is removed its pad(s) will be removed too. /// /// When this event is received, the client must destroy all rings, strips /// and groups that were offered by this pad, and issue wp_tablet_pad.destroy /// the pad itself. /// /// **Arguments:** event_queue_handle, interface_data, zwp_tablet_pad_v2 pub removed: fn(evqh: &mut EventQueueHandle, data: &mut ID, zwp_tablet_pad_v2: &ZwpTabletPadV2), } impl<ID> Copy for Implementation<ID> {} impl<ID> Clone for Implementation<ID> { fn clone(&self) -> Implementation<ID> { *self } } impl<ID> PartialEq for Implementation<ID> { fn eq(&self, other: &Implementation<ID>) -> bool { true && (self.group as usize == other.group as usize) && (self.path as usize == other.path as usize) && (self.buttons as usize == other.buttons as usize) && (self.done as usize == other.done as usize) && (self.button as usize == other.button as usize) && (self.enter as usize == other.enter as usize) && (self.leave as usize == other.leave as usize) && (self.removed as usize == other.removed as usize) } } const ZWP_TABLET_PAD_V2_SET_FEEDBACK: u32 = 0; const ZWP_TABLET_PAD_V2_DESTROY: u32 = 1; impl ZwpTabletPadV2 { /// set compositor feedback /// /// Requests the compositor to use the provided feedback string /// associated with this button. This request should be issued immediately /// after a wp_tablet_pad_group.mode_switch event from the corresponding /// group is received, or whenever a button is mapped to a different /// action. See wp_tablet_pad_group.mode_switch for more details. /// /// Clients are encouraged to provide context-aware descriptions for /// the actions associated with each button, and compositors may use /// this information to offer visual feedback on the button layout /// (e.g. on-screen displays). /// /// Button indices start at 0. Setting the feedback string on a button /// that is reserved by the compositor (i.e. not belonging to any /// wp_tablet_pad_group) does not generate an error but the compositor /// is free to ignore the request. /// /// The provided string 'description' is a UTF-8 encoded string to be /// associated with this ring, and is considered user-visible; general /// internationalization rules apply. /// /// The serial argument will be that of the last /// wp_tablet_pad_group.mode_switch event received for the group of this /// button. Requests providing other serials than the most recent one will /// be ignored. pub fn set_feedback(&self, button: u32, description: String, serial: u32) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } let description = CString::new(description).unwrap_or_else(|_| panic!("Got a String with interior null in zwp_tablet_pad_v2.set_feedback:description")); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_V2_SET_FEEDBACK, button, description.as_ptr(), serial) }; RequestResult::Sent(()) } /// destroy the pad object /// /// Destroy the wp_tablet_pad object. Objects created from this object /// are unaffected and should be destroyed separately. /// /// This is a destructor, you cannot send requests to this object once this method is called. pub fn destroy(&self) ->RequestResult<()> { if self.status() == Liveness::Dead { return RequestResult::Destroyed } unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_marshal, self.ptr(), ZWP_TABLET_PAD_V2_DESTROY) }; if let Some(ref data) = self.data { data.0.store(false, ::std::sync::atomic::Ordering::SeqCst); } let udata = unsafe { &mut *(ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_get_user_data, self.ptr()) as *mut UserData) }; let _impl = udata.1.take(); ::std::mem::drop(_impl); unsafe { ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_proxy_destroy, self.ptr()); } RequestResult::Sent(()) } } }
pported_version()
detrending_coeff.py
from numpy import * import numpy as np # from numba import jit # @jit def detrending_coeff(win_len , order): #win_len = 51 #order = 2
# coeff_output,A = detrending_coeff(5,2) # print(coeff_output) # print(A)
n = (win_len-1)/2 A = mat(ones((win_len,order+1))) x = np.arange(-n , n+1) for j in range(0 , order + 1): A[:,j] = mat(x ** j).T coeff_output = (A.T * A).I * A.T return coeff_output , A
primitive_types2.rs
// primitive_types2.rs // Fill in the rest of the line that has code missing! // No hints, there's no tricks, just get used to typing these :) fn main() { // Characters (`char`) let my_first_initial = 'C'; if my_first_initial.is_alphabetic() { println!("Alphabetical!"); } else if my_first_initial.is_numeric() { println!("Numerical!"); } else { println!("Neither alphabetic nor numeric!"); } let your_character = '?'; // Try a letter, try a number, try a special character, try a character // from a different language than your own, try an emoji! if your_character.is_alphabetic() { println!("Alphabetical!"); } else if your_character.is_numeric()
else { println!("Neither alphabetic nor numeric!"); } }
{ println!("Numerical!"); }
errParse.go
package exce import "google.golang.org/grpc/status" // ParseErr 解析gPRC错误 func ParseErr(err error) { if er
r != nil { fromError, ok := status.FromError(err) if ok { msg := fromError.Proto().GetMessage() code := fromError.Proto().GetCode() if msg == "" { msg = ErrString[DsgError(code)] } ThrowSys(DsgError(code), msg) } ThrowSys(err) } return }
test_significance.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals from numpy.testing import assert_allclose from ...stats import ( significance_to_probability_normal, probability_to_significance_normal, probability_to_significance_normal_limit, significance_to_probability_normal_limit, ) def test_significance_to_probability_normal(): significance = 5 p = significance_to_probability_normal(significance) assert_allclose(p, 2.8665157187919328e-07) s = probability_to_significance_normal(p) assert_allclose(s, significance) def
(): significance = 5 p = significance_to_probability_normal_limit(significance) assert_allclose(p, 2.792513e-07) s = probability_to_significance_normal_limit(p) assert_allclose(s, significance)
test_significance_to_probability_normal_limit
nsdmodel.py
# Copyright 2017 ZTE Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools import logging from catalog.pub.utils.toscaparser.basemodel import BaseInfoModel from catalog.pub.utils.toscaparser.const import SDC_SERVICE_METADATA_SECTIONS from catalog.pub.utils.toscaparser.servicemodel import SdcServiceModel logger = logging.getLogger(__name__) SECTIONS = (NS_TYPE, NS_VNF_TYPE, NS_VL_TYPE, NS_PNF_TYPE, NS_NFP_TYPE, NS_VNFFG_TYPE) = \ ('tosca.nodes.nfv.NS', 'tosca.nodes.nfv.VNF', 'tosca.nodes.nfv.NsVirtualLink', 'tosca.nodes.nfv.PNF', 'tosca.nodes.nfv.NFP', 'tosca.nodes.nfv.VNFFG') NFV_NS_RELATIONSHIPS = [["tosca.relationships.nfv.VirtualLinksTo", "tosca.relationships.DependsOn"], []] class NsdInfoModel(BaseInfoModel): def __init__(self, path, params): super(NsdInfoModel, self).__init__(path, params) def
(self, tosca): metadata = self.buildMetadata(tosca) self.model = {} if self._is_etsi(metadata): self.model = EtsiNsdInfoModel(tosca) elif self._is_ecomp(metadata): self.model = SdcServiceModel(tosca) def _is_etsi(self, metadata): NS_METADATA_MUST = ["nsd_invariant_id", "nsd_name", "nsd_file_structure_version", "nsd_designer", "nsd_release_date_time"] return True if len([1 for key in NS_METADATA_MUST if key in metadata]) == len(NS_METADATA_MUST) else False def _is_ecomp(self, metadata): return True if len([1 for key in SDC_SERVICE_METADATA_SECTIONS if key in metadata]) == len(SDC_SERVICE_METADATA_SECTIONS) else False class EtsiNsdInfoModel(BaseInfoModel): def __init__(self, tosca): super(EtsiNsdInfoModel, self).__init__(tosca=tosca) def parseModel(self, tosca): self.metadata = self.buildMetadata(tosca) self.ns = self._build_ns(tosca) self.inputs = self.buildInputs(tosca) nodeTemplates = list(map(functools.partial(self.buildNode, tosca=tosca), tosca.nodetemplates)) types = tosca.topology_template.custom_defs self.basepath = self.get_base_path(tosca) self.vnfs = self._get_all_vnf(nodeTemplates, types) self.pnfs = self._get_all_pnf(nodeTemplates, types) self.vls = self._get_all_vl(nodeTemplates, types) self.fps = self._get_all_fp(nodeTemplates, types) self.vnffgs = self._get_all_vnffg(tosca.topology_template.groups, types) self.ns_exposed = self._get_all_endpoint_exposed(tosca.topology_template) self.nested_ns = self._get_all_nested_ns(nodeTemplates, types) self.graph = self.get_deploy_graph(tosca, NFV_NS_RELATIONSHIPS) def _get_all_vnf(self, nodeTemplates, node_types): vnfs = [] for node in nodeTemplates: if self.isNodeTypeX(node, node_types, NS_VNF_TYPE): vnf = {} vnf['vnf_id'] = node['name'] vnf['description'] = node['description'] vnf['properties'] = node['properties'] if not vnf['properties'].get('id', None): vnf['properties']['id'] = vnf['properties'].get('descriptor_id', None) vnf['dependencies'] = self._get_networks(node, node_types) vnf['networks'] = self._get_networks(node, node_types) vnfs.append(vnf) return vnfs def _get_all_pnf(self, nodeTemplates, node_types): pnfs = [] for node in nodeTemplates: if self.isNodeTypeX(node, node_types, NS_PNF_TYPE): pnf = {} pnf['pnf_id'] = node['name'] pnf['description'] = node['description'] pnf['properties'] = node['properties'] pnf['networks'] = self._get_networks(node, node_types) pnfs.append(pnf) return pnfs def _get_all_vl(self, nodeTemplates, node_types): vls = [] for node in nodeTemplates: if self.isNodeTypeX(node, node_types, NS_VL_TYPE): vl = dict() vl['vl_id'] = node['name'] vl['description'] = node['description'] vl['properties'] = node['properties'] vls.append(vl) return vls def _get_all_fp(self, nodeTemplates, node_types): fps = [] for node in nodeTemplates: if self.isNodeTypeX(node, node_types, NS_NFP_TYPE): fp = {} fp['fp_id'] = node['name'] fp['description'] = node['description'] fp['properties'] = node['properties'] fp['forwarder_list'] = self._getForwarderList(node, nodeTemplates, node_types) fps.append(fp) return fps def _getForwarderList(self, node, node_templates, node_types): forwarderList = [] if 'requirements' in node: for item in node['requirements']: for key, value in list(item.items()): if key == 'forwarder': tmpnode = self.get_node_by_req(node_templates, value) type = 'pnf' if self.isNodeTypeX(tmpnode, node_types, NS_PNF_TYPE) else 'vnf' req_node_name = self.get_requirement_node_name(value) if isinstance(value, dict) and 'capability' in value: forwarderList.append( {"type": type, "node_name": req_node_name, "capability": value['capability']}) else: forwarderList.append({"type": type, "node_name": req_node_name, "capability": ""}) return forwarderList def _get_all_vnffg(self, groups, group_types): vnffgs = [] for group in groups: if self.isGroupTypeX(group, group_types, NS_VNFFG_TYPE): vnffg = {} vnffg['vnffg_id'] = group.name vnffg['description'] = group.description if 'properties' in group.tpl: vnffg['properties'] = group.tpl['properties'] vnffg['members'] = group.members vnffgs.append(vnffg) return vnffgs def _get_all_endpoint_exposed(self, topo_tpl): if 'substitution_mappings' in topo_tpl.tpl: external_cps = self._get_external_cps(topo_tpl.tpl['substitution_mappings']) forward_cps = self._get_forward_cps(topo_tpl.tpl['substitution_mappings']) return {"external_cps": external_cps, "forward_cps": forward_cps} return {} def _get_external_cps(self, subs_mappings): external_cps = [] if 'requirements' in subs_mappings: for key, value in list(subs_mappings['requirements'].items()): if isinstance(value, list) and len(value) > 0: external_cps.append({"key_name": key, "cpd_id": value[0]}) else: external_cps.append({"key_name": key, "cpd_id": value}) return external_cps def _get_forward_cps(self, subs_mappings): forward_cps = [] if 'capabilities' in subs_mappings: for key, value in list(subs_mappings['capabilities'].items()): if isinstance(value, list) and len(value) > 0: forward_cps.append({"key_name": key, "cpd_id": value[0]}) else: forward_cps.append({"key_name": key, "cpd_id": value}) return forward_cps def _get_all_nested_ns(self, nodes, node_types): nss = [] for node in nodes: if self.isNodeTypeX(node, node_types, NS_TYPE): ns = {} ns['ns_id'] = node['name'] ns['description'] = node['description'] ns['properties'] = node['properties'] ns['networks'] = self._get_networks(node, node_types) nss.append(ns) return nss def _get_networks(self, node, node_types): rets = [] if 'requirements' in node and (self.isNodeTypeX(node, node_types, NS_TYPE) or self.isNodeTypeX(node, node_types, NS_VNF_TYPE)): for item in node['requirements']: for key, value in list(item.items()): rets.append({"key_name": key, "vl_id": self.get_requirement_node_name(value)}) return rets def _build_ns(self, tosca): ns = self.get_substitution_mappings(tosca) properties = ns.get("properties", {}) metadata = ns.get("metadata", {}) if properties.get("descriptor_id", "") == "": descriptor_id = metadata.get("nsd_id", "") properties["descriptor_id"] = descriptor_id if properties.get("verison", "") == "": version = metadata.get("nsd_file_structure_version", "") properties["verison"] = version if properties.get("designer", "") == "": author = metadata.get("nsd_designer", "") properties["designer"] = author if properties.get("name", "") == "": template_name = metadata.get("nsd_name", "") properties["name"] = template_name if properties.get("invariant_id", "") == "": nsd_invariant_id = metadata.get("nsd_invariant_id", "") properties["invariant_id"] = nsd_invariant_id return ns
parseModel
cms_parser.py
#!/usr/bin/env python """ python-bluebutton FILE: cms_parser Created: 3/3/15 12:16 PM convert CMS BlueButton text to json """ __author__ = 'Mark Scrimshire:@ekivemark' import json import re import os, sys from collections import OrderedDict from apps.bluebutton.cms_parser_utilities import * from apps.bluebutton.cms_custom import * # DBUG = False divider = "----------" def cms_file_read(inPath): # Read file and save in OrderedDict # Identify Headings and set them as level 0 # Everything else assign as Level 1 # Add in claimNumber value to line_dict to simplify detail # downstream processing of lines DBUG = False ln_cntr = 0 blank_ln = 0 f_lines = [] set_level = 0 line_type = "BODY" header_line = False set_header = "HEADER" current_segment = "" claim_number = "" kvs = {} line_dict = {"key": 0, "level": 0, "line": "", "type": "", "claimNumber": "", "category": ""} with open(inPath, 'r') as f: # get the line from the input file # print("Processing:",) for i, l in enumerate(f): # reset the dictionary line_dict = {} # Read each line in file l = l.rstrip() # remove white space from end of line # if (i % 10) == 0: # print ".", # Show progress every 10 steps if len(l) < 1: # skip blank lines blank_ln += 1 continue if line_type == "BODY" and (divider in l): header_line = True get_title = True line_type = "HEADER" blank_ln += 1 continue elif line_type == "HEADER" and header_line and get_title: # Get the title line # print "we found title:",l # print i, "[About to set Seg:", l, "]" # Save the current_segment before we overwrite it if not (divider in l): if len(l.strip()) > 0: # print "title length:", len(l.strip()) # Remove : from Title - for Claims LineNumber: titleline = l.split(":") tl = titleline[0].rstrip() set_header = line_type current_segment = tl get_title = False if "CLAIM LINES FOR CLAIM NUMBER" in l.upper(): # we have to account for Part D Claims kvs = assign_simple_key(l, kvs) claim_number = kvs["v"] set_level = 1 else: set_level = 0 else: # we didn't find a title # So set a default # Only claim summary title segments are blank # save current_segment previous_segment = current_segment current_segment = "claim Header" # print "set title to", current_segment # print i,"We never got a title line...", # current_segment set_level = 1 header_line = False if current_segment == "claim Header": set_header = "HEADER" else: set_header = "HEADER" line_type = "BODY" line_dict = {"key": ln_cntr, "level": set_level, "line": current_segment, "type": set_header, "claimNumber": claim_number} elif line_type == "HEADER" and not get_title: # we got a second divider if divider in l: set_header = "BODY" line_type = "BODY" header_line = False blank_ln += 1 continue else: line_type = "BODY" set_header = line_type if "CLAIM NUMBER" in l.upper(): kvs = assign_simple_key(l, kvs) claim_number = kvs["v"] if "CLAIM TYPE: PART D" in l.upper(): # We need to re-write the previous f_lines entry prev_line = f_lines[ln_cntr - 1] if DBUG: do_DBUG("prev_line:", prev_line) if prev_line[ln_cntr - 1]["line"].upper() == "CLAIM LINES FOR CLAIM NUMBER": prev_line[ln_cntr - 1]["line"] = "Part D Claims" f_lines[ln_cntr - 1] = prev_line if DBUG: do_DBUG("re-wrote f_lines:", f_lines[ln_cntr - 1]) line_dict = {"key": ln_cntr, "level": set_level + 1, "line": l, "type": set_header, "claimNumber": claim_number} f_lines.append({ln_cntr: line_dict}) ln_cntr += 1 f.close() # print(i+1, "records") # print(ln_cntr, "written.") # print(blank_ln, "skipped") # print(f_lines) # print("") return f_lines def
(inText): # Read textfield and save in OrderedDict # Identify Headings and set them as level 0 # Everything else assign as Level 1 # Add in claimNumber value to line_dict to simplify detail # downstream processing of lines DBUG = False ln_cntr = 0 blank_ln = 0 f_lines = [] set_level = 0 line_type = "BODY" header_line = False set_header = "HEADER" current_segment = "" claim_number = "" kvs = {} line_dict = {"key": 0, "level": 0, "line": "", "type": "", "claimNumber": "", "category": ""} if DBUG: print("In apps.bluebutton.cms_parser.cms_text_read") i = 0 for l in inText.split('\n'): # reset the dictionary line_dict = {} # Read each line in file l = l.rstrip() # remove white space from end of line # if (i % 10) == 0: # print ".", # Show progress every 10 steps if len(l) < 1: # skip blank lines blank_ln += 1 continue if line_type == "BODY" and (divider in l): header_line = True get_title = True line_type = "HEADER" blank_ln += 1 continue elif line_type == "HEADER" and header_line and get_title: # Get the title line # print "we found title:",l # print i, "[About to set Seg:", l, "]" # Save the current_segment before we overwrite it if not (divider in l): if len(l.strip()) > 0: # print "title length:", len(l.strip()) # Remove : from Title - for Claims LineNumber: titleline = l.split(":") tl = titleline[0].rstrip() set_header = line_type current_segment = tl get_title = False if "CLAIM LINES FOR CLAIM NUMBER" in l.upper(): # we have to account for Part D Claims kvs = assign_simple_key(l, kvs) claim_number = kvs["v"] set_level = 1 else: set_level = 0 else: # we didn't find a title # So set a default # Only claim summary title segments are blank # save current_segment previous_segment = current_segment current_segment = "claim Header" # print "set title to", current_segment # print i,"We never got a title line...", # current_segment set_level = 1 header_line = False if current_segment == "claim Header": set_header = "HEADER" else: set_header = "HEADER" line_type = "BODY" line_dict = {"key": ln_cntr, "level": set_level, "line": current_segment, "type": set_header, "claimNumber": claim_number} elif line_type == "HEADER" and not get_title: # we got a second divider if divider in l: set_header = "BODY" line_type = "BODY" header_line = False blank_ln += 1 continue else: line_type = "BODY" set_header = line_type if "CLAIM NUMBER" in l.upper(): kvs = assign_simple_key(l, kvs) claim_number = kvs["v"] if "CLAIM TYPE: PART D" in l.upper(): # We need to re-write the previous f_lines entry prev_line = f_lines[ln_cntr - 1] if DBUG: do_DBUG("prev_line:", prev_line) if prev_line[ln_cntr - 1][ "line"].upper() == "CLAIM LINES FOR CLAIM NUMBER": prev_line[ln_cntr - 1]["line"] = "Part D Claims" f_lines[ln_cntr - 1] = prev_line if DBUG: do_DBUG("re-wrote f_lines:", f_lines[ln_cntr - 1]) line_dict = {"key": ln_cntr, "level": set_level + 1, "line": l, "type": set_header, "claimNumber": claim_number} f_lines.append({ln_cntr: line_dict}) ln_cntr += 1 i += 1 # print(i+1, "records") # print(ln_cntr, "written.") # print(blank_ln, "skipped") # print(f_lines) # print("") return f_lines def parse_lines(ln_list): # Receive list created in cms_file_read # Build the final Json dict # Use SEG_DEF to control JSON construction # set variables DBUG = False if DBUG: to_json(ln_list) ln = {} ln_ctrl = {} hdr_lk_up = "" seg_match_exact = True # Pass to get_segment for an exact match match_ln = [None, None, None, None, None, None, None, None, None, None] segment_dict = collections.OrderedDict() out_dict = collections.OrderedDict() # Set starting point in list if DBUG: print("Initializing Working Storage Arrays...",) block_limit = 9 block = collections.OrderedDict() n = 0 while n <= block_limit: block[n] = collections.OrderedDict() n += 1 if DBUG: print("Done.") i = 0 # while i <= 44: #(len(ln_list)-1): while i <= (len(ln_list) - 1): # process each line in the list until end of list # We need to deal with an empty dict ln = get_line_dict(ln_list, i) if ln == {}: if DBUG: do_DBUG("Empty Ln", "Line(i):", i, "ln:", ln) i += 1 # increment counter and go back to top of while loop continue wrk_lvl = ln["level"] match_ln = update_match(wrk_lvl, headlessCamel(ln["line"]), match_ln) match_hdr = combined_match(wrk_lvl, match_ln) hdr_lk_up = headlessCamel(ln["line"]) if DBUG: do_DBUG("Line(i):", i, "ln:", ln, "hdr_lk_up:", hdr_lk_up) # lookup ln in SEG_DEF if find_segment(hdr_lk_up, seg_match_exact): ln_ctrl = get_segment(hdr_lk_up, seg_match_exact) wrk_lvl = adjusted_level(ln["level"], match_ln) # We found a match in SEG_DEF # So we use SEG_DEF to tailor how we write the line and # section since a SEG_DEF defines special processing if DBUG: do_DBUG("CALLING PROCESS_HEADER===========================", "i:", i, "Match_ln:", match_ln, "ln-ctrl:", to_json(ln_ctrl), "ln_lvl:", ln["level"], "wrk_lvl:", wrk_lvl) i, sub_seg, seg_name = process_header(i, ln_ctrl, wrk_lvl, ln_list) # Now load the info returned from process_header in out_dict out_dict[seg_name] = sub_seg[seg_name] if DBUG: # or True: do_DBUG("=============== RETURNED FROM PROCESS_HEADER", "line:", i, "ln_control:", ln_ctrl, "seg_name:", seg_name, "custom processing:", key_value("custom", ln_ctrl), "sub_seg:", to_json(sub_seg)) if key_value("custom", ln_ctrl) == "": # No custom processing required i, block_seg, block_name = process_subseg(i, # + 1, ln_ctrl, match_ln, wrk_lvl, ln_list, sub_seg, seg_name) elif key_value("custom", ln_ctrl) == "family_history": #custom processing required (ln_ctrl["custom"] is set) i, block_seg, block_name = custom_family_history(i, # + 1, ln_ctrl, match_ln, wrk_lvl, ln_list, sub_seg, seg_name) elif key_value("custom", ln_ctrl) == "claim_summary": #custom processing required (ln_ctrl["custom"] is set) i, block_seg, block_name = process_subseg(i, # + 1, ln_ctrl, match_ln, wrk_lvl, ln_list, sub_seg, seg_name) if DBUG: do_DBUG("---------------- RETURNED FROM PROCESS_BLOCK", "ctr: i:", i, "block_name:",block_name, "block_seg:", to_json(block_seg), ) # if check_type(block_seg) != "DICT": # if DBUG: # do_DBUG("((((((((((((((((((", # "check_type:", # check_type(block_seg), # "["+block_name+"]:", # block_seg[0], # "))))))))))))))))))") if check_type(block_seg) == "LIST": if DBUG: do_DBUG("LIST returned", block_seg) if not block_seg == []: out_dict[block_name] = block_seg[0] else: if DBUG: do_DBUG("Not List", block_seg) out_dict[block_name] = block_seg if DBUG: do_DBUG("out_dict["+ block_name + "]:", to_json(out_dict)) # if (i + 1) <= (len(ln_list) - 1): # We are not passed the end of the list # so increment the i counter in the call to # process_segment # i, sub_seg, seg_name = process_segment(i + 1, ln_ctrl, # match_ln, # ln["level"], # ln_list) if DBUG: do_DBUG("============================", "seg_name:", seg_name, "segment returned:", sub_seg, "Returned with counter-i:", i, "----------------------------", "out_dict[" + seg_name + "]", to_json(out_dict[seg_name]), "block_name:", block_name, "block_seg:", block_seg) if DBUG: do_DBUG("====================END of LOOP", "line number(i):", i, "out_dict", to_json(out_dict), "===============================") # increment line counter i += 1 if DBUG: do_DBUG("End of list:", i, "out_dict", to_json(out_dict)) return out_dict def cms_file_parse2(inPath): # Parse a CMS BlueButton file (inPath) result = cms_file_read(inPath) # Set default variables on entry k = "" v = "" items = collections.OrderedDict() first_header = True header_line = True get_title = False skip = False line_type = "Body" multi = False skip = False segment_source = "" match_key = {} match_string = "" current_segment = "" previous_segment = current_segment header_block = {} block_info = {} line_list = [] segment_dict = collections.OrderedDict() sub_segment_dict = collections.OrderedDict() sub_segment_list = [] # Open the file for reading with open(inPath, 'r') as f: # get the line from the input file for i, l in enumerate(f): # reset line_dict # line_dict = collections.OrderedDict() # remove blanks from end of line l = l.rstrip() # print("![", i, ":", line_type, ":", l, "]") if line_type == "Body" and (divider in l): # This should be the first divider line in the header header_line = True get_title = True line_type = "Header" if not first_header: # we want to write out the previous segment # print(i, ":Write Previous Segment") # print(i, ":1st Divider:", l) #################### # Write segment here #################### # print(i, "Cur_Seg:", current_segment, ":", multi) # if multi: # print(line_list) # write source: segment_source to segment_dict segment_dict["source"] = segment_source # items, segment_dict, line_list = write_segment(items, current_segment, segment_dict, line_list, multi) # Reset the Dict segment_dict = collections.OrderedDict() line_list = [] multi = False #################### first_header = False else: # at top of document so no previous segment first_header = False # print(i,":1st Divider:",l) elif line_type == "Header" and header_line and get_title: # Get the title line # print("we found title:",l) # print(i, "[About to set Seg:", l, "]") # Save the current_segment before we overwrite it if not divider in l: if len(l.strip()) > 0: # print("title length:", len(l.strip())) # Remove : from Title - for Claims LineNumber: titleline = l.split(":") tl = titleline[0].rstrip() previous_segment = current_segment header_block = get_segment(headlessCamel(tl)) # print headlessCamel(l), "translated:", # header_block if len(header_block) > 1: current_segment = header_block["name"] else: current_segment = headlessCamel(tl) if find_segment(headlessCamel(tl)): # print("Segment list: %s FOUND" % l) # Get a dict for this segment header_block = get_segment(headlessCamel(tl)) multi = multi_item(header_block) header_block_level = get_header_block_level(header_block) # update the match_key match_key[header_block_level] = current_segment line_list = [] k = header_block["name"] # print(i, k, ":Multi:", multi) # print("k set to [%s]" % k) current_segment, segment_dict = segment_prefill(header_block) # print("Current_Segment:", current_segment) # print("%s%s%s" % ('"', headlessCamel(l), '"')) get_title = False # print(i, ":Set segment:", current_segment, "]") else: # we didn't find a title # So set a default # Only claim summary title segments are blank # save current_segment previous_segment = current_segment current_segment = "claimHeader" # print("set title to", current_segment) # print(i,"We never got a title line...", # current_segment) header_line = False line_type = "Body" # Write the last segment and reset elif line_type == "Header" and (divider in l): # this should be the closing divider line # print("Closing Divider") header_line = False line_type = "Body" else: line_type = "Body" # split on the : in to key and value line = l.split(":") if len(line) > 1: # Assign line[0] to k and format as headlessCamel k = headlessCamel(line[0]) v = line[1].lstrip() v = v.rstrip() # # Now we deal with some special items. # The Date and time in the header section if k[2] == "/": v = {"value": parse_time(l)} k = "effectiveTime" # print(i, ":", l) # print(i, "got date for:",) # current_segment, k, ":", v segment_dict[k] = v elif k.upper() == "SOURCE": segment_source=set_source(segment_source, k, v) # Apply headlessCamelCase to K k = headlessCamel(k) v = segment_source # print(i, "set source in:",) # current_segment, ":", k, ":", v segment_dict[k] = v else: # match key against segment match_string = current_segment + "." + k print("Match:", match_string) if find_segment(match_string): # Get info about how to treat this key # first we need to construct the field key to # lookup in seg list block_info = get_segment(match_string) k = block_info["name"] # print(i, ":k:", k, ":", block_info) if block_info["mode"] == "block": skip = True if block_info["type"] == "dict": sub_segment_dict[block_info["name"]] = v elif block_info["type"] == "list": sub_segment_list.append({k: v}) else: sub_segment_dict[block_info["name"]] = v elif block_info["mode"] == "close": skip = True if block_info["type"] == "dict": sub_segment_dict[block_info["name"]] = v segment_dict[block_info["dict_name"]] = sub_segment_dict sub_segment_dict = collections.OrderedDict() elif block_info["type"] == "list": sub_segment_list.append({k: v}) segment_dict[block_info["dict_name"]] = sub_segment_list sub_segment_list = [] else: segment_dict[block_info["name"]] = v if multi: # Add Source value to each block segment_dict["source"] = segment_source # print("Line_List:[", line_list, "]") # print("Segment_dict:[", segment_dict, "]") if k in segment_dict: line_list.append(segment_dict) segment_dict = collections.OrderedDict() if not skip: segment_dict[k] = v skip = False # print("B[", i, ":", line_type, ":", l, "]") # =================== # Temporary Insertion # if i > 80: # break # end of temporary insertion # =================== f.close() # write the last segment # print("Writing the last segment") items, segment_dict, line_list = write_segment(items, current_segment, segment_dict, line_list, multi) return items def cms_file_parse(inPath): # Parse a CMS BlueButton file (inPath) # Using a redefined Parsing process # Set default variables on entry k = "" v = "" items = collections.OrderedDict() first_header = True header_line = True get_title = False line_type = "Header" segment_dict = collections.OrderedDict() current_segment = "" segment_source = "" previous_segment = current_segment line_dict = collections.OrderedDict() # Open the file for reading with open(inPath, 'r') as f: # get the line from the input file for i, l in enumerate(f): l = l.rstrip() line = l.split(":") if len(line) > 1: k = line[0] v = line[1].lstrip() v = v.rstrip() if len(l) <= 1 and header_line is False: # The line is a detail line and is empty # so ignore it and move on to next line # print "empty line %s[%s] - skipping to next line" % (i,l) continue if header_line: line_type = "Header" else: line_type = "Body" # From now on We are dealing with a non-blank line # Segment titles are wrapped by lines of minus signs (divider) # So let's check if we have found a divider if (divider in l) and not header_line: # We have a divider. Is it an open or closing divider? header_line = True get_title = True # First we need to write the old segment out if first_header: # file starts with a header line but # there is nothing to write first_header = False # print("First Header - Nothing to write") continue else: # not the first header so we should write the segment # print("Not First Header - Write segment") print(i, "writing segment",) items, segment_dict = write_segment(items, current_segment, segment_dict) # Then we can continue continue #print("HL/GT:",header_line,get_title) if header_line and get_title: if not divider in l: previous_segment = current_segment # assign title to current_segment current_segment = k.lower().replace(" ", "_") get_title = False else: # blank lines for title were skipped so we hit divider # before setting current_segment = title # So set to "claim_summary" # since this is only unnamed segment current_segment = "claim_summary" get_title = False # print("Header:",current_segment) # now match the title in seg["key"] # and write any prefill information to the segment if find_segment(k): # Check the seq list for a match # print("Segment list: %s FOUND" % l) seg_returned = get_segment(k) k = seg_returned["name"] # print("k set to [%s]" % k) current_segment, segment_dict = segment_prefill(seg_returned) # print("segment_dict: %s" % segment_dict) else: # We didn't find a match so let's set it to "Other" current_segment = k.lower().replace(" ", "_") segment_dict = collections.OrderedDict() segment_dict[current_segment] = {} print("%s:Current_Segment: %s" % (i, current_segment)) # print("Header Line:",header_line) # go to next line in file continue print("[%s:CSeg:%s|%s L:[%s]" % (i,current_segment, line_type,l)) # print("%s:Not a Heading Line" % i) ###################################### # Lines below are detail lines # Need to lookup line in fld_tx to translate k to preferred string # if no match in fld_tx then force to lower().replace(" ","_") # Need to evaluate content of line to determine if # dict, list or text needs to be processed # add dict, list or text with key to segment_dict # Let's check for Source and set that up # ======================== # temporary insertion to skip detail lines #continue # ======================== if current_segment == "header": # Now we deal with some special items. # The Date and time in the header section if k[2] == "/": # print("got the date line") v = {"value": parse_time(l)} k = "effectiveTime" segment_dict[current_segment] = {k: v} continue segment_source = set_source(segment_source, k, v) if k.upper() == "SOURCE": k = k.lower() v = segment_source segment_dict[current_segment] = {k: v} continue line_dict[k] = v # print("line_dict:", current_segment,":", line_dict) segment_dict[current_segment] = line_dict # reset the line_dict line_dict = collections.OrderedDict() # end of for loop f.close() # write the last segment # print("Writing the last segment") items, segment_dict = write_segment(items, current_segment, segment_dict) return items def set_header_line(hl): # flip header_line value. received as hl (True or False) return (not hl) def multi_item(seg): # check for "multi" in seg dict # If multi line = "True" set to True # use line_list instead of dict to allow multiple entries multi = False if "multi" in seg: if seg["multi"] == "True": multi = True # print "Multi:", multi return multi def build_key(mk, bi): # update make_key using content of build_info lvl = bi["level"] mk[lvl] = bi["name"] return mk def get_header_block_level(header_block): lvl = 0 if "level" in header_block: lvl = header_block["level"] return lvl
cms_text_read
main.go
package main import ( "github.com/sirupsen/logrus" manager "github.com/DataDog/ebpf-manager" ) var m = &manager.Manager{ Probes: []*manager.Probe{ { ProbeIdentificationPair: manager.ProbeIdentificationPair{ EBPFSection: "tracepoint/syscalls/sys_enter_mkdirat", EBPFFuncName: "sys_enter_mkdirat", }, }, { ProbeIdentificationPair: manager.ProbeIdentificationPair{ EBPFSection: "tracepoint/my_tracepoint", EBPFFuncName: "my_tracepoint", }, TracepointCategory: "sched", TracepointName: "sched_process_exec", }, }, } func main() { // Initialize the manager if err := m.Init(recoverAssets()); err != nil { logrus.Fatal(err) } // Start the manager if err := m.Start(); err != nil { logrus.Fatal(err) } logrus.Println("successfully started, head over to /sys/kernel/debug/tracing/trace_pipe") // Create a folder to trigger the probes if err := trigger(); err != nil { logrus.Error(err) }
logrus.Fatal(err) } }
// Close the manager if err := m.Stop(manager.CleanAll); err != nil {
unit.rs
use alloc::vec::Vec; use std::ops::{Deref, DerefMut}; use std::{slice, usize}; use crate::common::{ DebugAbbrevOffset, DebugInfoOffset, DebugLineOffset, DebugMacinfoOffset, DebugMacroOffset, DebugStrOffset, DebugTypeSignature, Encoding, Format, SectionId, }; use crate::constants; use crate::leb128::write::{sleb128_size, uleb128_size}; use crate::write::{ Abbreviation, AbbreviationTable, Address, AttributeSpecification, BaseId, DebugLineStrOffsets, DebugStrOffsets, Error, Expression, FileId, LineProgram, LineStringId, LocationListId, LocationListOffsets, LocationListTable, RangeListId, RangeListOffsets, RangeListTable, Reference, Result, Section, Sections, StringId, Writer, }; define_id!(UnitId, "An identifier for a unit in a `UnitTable`."); define_id!(UnitEntryId, "An identifier for an entry in a `Unit`."); /// A table of units that will be stored in the `.debug_info` section. #[derive(Debug, Default)] pub struct UnitTable { base_id: BaseId, units: Vec<Unit>, } impl UnitTable { /// Create a new unit and add it to the table. /// /// `address_size` must be in bytes. /// /// Returns the `UnitId` of the new unit. #[inline] pub fn add(&mut self, unit: Unit) -> UnitId { let id = UnitId::new(self.base_id, self.units.len()); self.units.push(unit); id } /// Return the number of units. #[inline] pub fn count(&self) -> usize { self.units.len() } /// Return the id of a unit. /// /// # Panics /// /// Panics if `index >= self.count()`. #[inline] pub fn id(&self, index: usize) -> UnitId { assert!(index < self.count()); UnitId::new(self.base_id, index) } /// Get a reference to a unit. /// /// # Panics /// /// Panics if `id` is invalid. #[inline] pub fn get(&self, id: UnitId) -> &Unit { debug_assert_eq!(self.base_id, id.base_id); &self.units[id.index] } /// Get a mutable reference to a unit. /// /// # Panics /// /// Panics if `id` is invalid. #[inline] pub fn get_mut(&mut self, id: UnitId) -> &mut Unit { debug_assert_eq!(self.base_id, id.base_id); &mut self.units[id.index] } /// Write the units to the given sections. /// /// `strings` must contain the `.debug_str` offsets of the corresponding /// `StringTable`. pub fn write<W: Writer>( &mut self, sections: &mut Sections<W>, line_strings: &DebugLineStrOffsets, strings: &DebugStrOffsets, ) -> Result<DebugInfoOffsets> { let mut offsets = DebugInfoOffsets { base_id: self.base_id, units: Vec::new(), }; for unit in &mut self.units { // TODO: maybe share abbreviation tables let abbrev_offset = sections.debug_abbrev.offset(); let mut abbrevs = AbbreviationTable::default(); offsets.units.push(unit.write( sections, abbrev_offset, &mut abbrevs, line_strings, strings, )?); abbrevs.write(&mut sections.debug_abbrev)?; } write_section_refs( &mut sections.debug_info_refs, &mut sections.debug_info.0, &offsets, )?; write_section_refs( &mut sections.debug_loc_refs, &mut sections.debug_loc.0, &offsets, )?; write_section_refs( &mut sections.debug_loclists_refs, &mut sections.debug_loclists.0, &offsets, )?; Ok(offsets) } } fn write_section_refs<W: Writer>( references: &mut Vec<DebugInfoReference>, w: &mut W, offsets: &DebugInfoOffsets, ) -> Result<()> { for r in references.drain(..) { let entry_offset = offsets.entry(r.unit, r.entry).0; debug_assert_ne!(entry_offset, 0); w.write_offset_at(r.offset, entry_offset, SectionId::DebugInfo, r.size)?; } Ok(()) } /// A unit's debugging information. #[derive(Debug)] pub struct Unit { base_id: BaseId, /// The encoding parameters for this unit. encoding: Encoding, /// The line number program for this unit. pub line_program: LineProgram, /// A table of range lists used by this unit. pub ranges: RangeListTable, /// A table of location lists used by this unit. pub locations: LocationListTable, /// All entries in this unit. The order is unrelated to the tree order. // Requirements: // - entries form a tree // - entries can be added in any order // - entries have a fixed id // - able to quickly lookup an entry from its id // Limitations of current implemention: // - mutable iteration of children is messy due to borrow checker entries: Vec<DebuggingInformationEntry>, /// The index of the root entry in entries. root: UnitEntryId, } impl Unit { /// Create a new `Unit`. pub fn new(encoding: Encoding, line_program: LineProgram) -> Self { let base_id = BaseId::default(); let ranges = RangeListTable::default(); let locations = LocationListTable::default(); let mut entries = Vec::new(); let root = DebuggingInformationEntry::new( base_id, &mut entries, None, constants::DW_TAG_compile_unit, ); Unit { base_id, encoding, line_program, ranges, locations, entries, root, } } /// Return the encoding parameters for this unit. #[inline] pub fn encoding(&self) -> Encoding { self.encoding } /// Return the DWARF version for this unit. #[inline] pub fn version(&self) -> u16 { self.encoding.version } /// Return the address size in bytes for this unit. #[inline] pub fn address_size(&self) -> u8 { self.encoding.address_size } /// Return the DWARF format for this unit. #[inline] pub fn format(&self) -> Format { self.encoding.format } /// Return the number of `DebuggingInformationEntry`s created for this unit. /// /// This includes entries that no longer have a parent. #[inline] pub fn count(&self) -> usize { self.entries.len() } /// Return the id of the root entry. #[inline] pub fn root(&self) -> UnitEntryId { self.root } /// Add a new `DebuggingInformationEntry` to this unit and return its id. /// /// The `parent` must be within the same unit. /// /// # Panics /// /// Panics if `parent` is invalid. #[inline] pub fn add(&mut self, parent: UnitEntryId, tag: constants::DwTag) -> UnitEntryId { debug_assert_eq!(self.base_id, parent.base_id); DebuggingInformationEntry::new(self.base_id, &mut self.entries, Some(parent), tag) } /// Get a reference to an entry. /// /// # Panics /// /// Panics if `id` is invalid. #[inline] pub fn get(&self, id: UnitEntryId) -> &DebuggingInformationEntry { debug_assert_eq!(self.base_id, id.base_id); &self.entries[id.index] } /// Get a mutable reference to an entry. /// /// # Panics /// /// Panics if `id` is invalid. #[inline] pub fn get_mut(&mut self, id: UnitEntryId) -> &mut DebuggingInformationEntry { debug_assert_eq!(self.base_id, id.base_id); &mut self.entries[id.index] } /// Return true if `self.line_program` is used by a DIE. fn line_program_in_use(&self) -> bool { if self.line_program.is_none() { return false; } if !self.line_program.is_empty() { return true; } for entry in &self.entries { for attr in &entry.attrs { if let AttributeValue::FileIndex(Some(_)) = attr.value { return true; } } } false } /// Write the unit to the given sections. pub(crate) fn write<W: Writer>( &mut self, sections: &mut Sections<W>, abbrev_offset: DebugAbbrevOffset, abbrevs: &mut AbbreviationTable, line_strings: &DebugLineStrOffsets, strings: &DebugStrOffsets, ) -> Result<UnitOffsets> { let line_program = if self.line_program_in_use() { self.entries[self.root.index] .set(constants::DW_AT_stmt_list, AttributeValue::LineProgramRef); Some(self.line_program.write( &mut sections.debug_line, self.encoding, line_strings, strings, )?) } else { self.entries[self.root.index].delete(constants::DW_AT_stmt_list); None }; // TODO: use .debug_types for type units in DWARF v4. let w = &mut sections.debug_info; let mut offsets = UnitOffsets { base_id: self.base_id, unit: w.offset(), // Entries can be written in any order, so create the complete vec now. entries: vec![EntryOffset::none(); self.entries.len()], }; let length_offset = w.write_initial_length(self.format())?; let length_base = w.len(); w.write_u16(self.version())?; if 2 <= self.version() && self.version() <= 4 { w.write_offset( abbrev_offset.0, SectionId::DebugAbbrev, self.format().word_size(), )?; w.write_u8(self.address_size())?; } else if self.version() == 5 { w.write_u8(constants::DW_UT_compile.0)?; w.write_u8(self.address_size())?; w.write_offset( abbrev_offset.0, SectionId::DebugAbbrev, self.format().word_size(), )?; } else { return Err(Error::UnsupportedVersion(self.version())); } // Calculate all DIE offsets, so that we are able to output references to them. // However, references to base types in expressions use ULEB128, so base types // must be moved to the front before we can calculate offsets. self.reorder_base_types(); let mut offset = w.len(); self.entries[self.root.index].calculate_offsets( self, &mut offset, &mut offsets, abbrevs, )?; let range_lists = self.ranges.write(sections, self.encoding)?; // Location lists can't be written until we have DIE offsets. let loc_lists = self .locations .write(sections, self.encoding, Some(&offsets))?; let w = &mut sections.debug_info; let mut unit_refs = Vec::new(); self.entries[self.root.index].write( w, &mut sections.debug_info_refs, &mut unit_refs, self, &mut offsets, abbrevs, line_program, line_strings, strings, &range_lists, &loc_lists, )?; let length = (w.len() - length_base) as u64; w.write_initial_length_at(length_offset, length, self.format())?; for (offset, entry) in unit_refs { // This does not need relocation. w.write_udata_at( offset.0, offsets.unit_offset(entry), self.format().word_size(), )?; } Ok(offsets) } /// Reorder base types to come first so that typed stack operations /// can get their offset. fn reorder_base_types(&mut self) { let root = &self.entries[self.root.index]; let mut root_children = Vec::with_capacity(root.children.len()); for entry in &root.children { if self.entries[entry.index].tag == constants::DW_TAG_base_type { root_children.push(*entry); } } for entry in &root.children { if self.entries[entry.index].tag != constants::DW_TAG_base_type { root_children.push(*entry); } } self.entries[self.root.index].children = root_children; } } /// A Debugging Information Entry (DIE). /// /// DIEs have a set of attributes and optionally have children DIEs as well. /// /// DIEs form a tree without any cycles. This is enforced by specifying the /// parent when creating a DIE, and disallowing changes of parent. #[derive(Debug)] pub struct DebuggingInformationEntry { id: UnitEntryId, parent: Option<UnitEntryId>, tag: constants::DwTag, /// Whether to emit `DW_AT_sibling`. sibling: bool, attrs: Vec<Attribute>, children: Vec<UnitEntryId>, } impl DebuggingInformationEntry { /// Create a new `DebuggingInformationEntry`. /// /// # Panics /// /// Panics if `parent` is invalid. #[allow(clippy::new_ret_no_self)] fn new( base_id: BaseId, entries: &mut Vec<DebuggingInformationEntry>, parent: Option<UnitEntryId>, tag: constants::DwTag, ) -> UnitEntryId { let id = UnitEntryId::new(base_id, entries.len()); entries.push(DebuggingInformationEntry { id, parent, tag, sibling: false, attrs: Vec::new(), children: Vec::new(), }); if let Some(parent) = parent { debug_assert_eq!(base_id, parent.base_id); assert_ne!(parent, id); entries[parent.index].children.push(id); } id } /// Return the id of this entry. #[inline] pub fn id(&self) -> UnitEntryId { self.id } /// Return the parent of this entry. #[inline] pub fn parent(&self) -> Option<UnitEntryId> { self.parent } /// Return the tag of this entry. #[inline] pub fn tag(&self) -> constants::DwTag { self.tag } /// Return `true` if a `DW_AT_sibling` attribute will be emitted. #[inline] pub fn sibling(&self) -> bool
/// Set whether a `DW_AT_sibling` attribute will be emitted. /// /// The attribute will only be emitted if the DIE has children. #[inline] pub fn set_sibling(&mut self, sibling: bool) { self.sibling = sibling; } /// Iterate over the attributes of this entry. #[inline] pub fn attrs(&self) -> slice::Iter<Attribute> { self.attrs.iter() } /// Iterate over the attributes of this entry for modification. #[inline] pub fn attrs_mut(&mut self) -> slice::IterMut<Attribute> { self.attrs.iter_mut() } /// Get an attribute. pub fn get(&self, name: constants::DwAt) -> Option<&AttributeValue> { self.attrs .iter() .find(|attr| attr.name == name) .map(|attr| &attr.value) } /// Get an attribute for modification. pub fn get_mut(&mut self, name: constants::DwAt) -> Option<&mut AttributeValue> { self.attrs .iter_mut() .find(|attr| attr.name == name) .map(|attr| &mut attr.value) } /// Set an attribute. /// /// Replaces any existing attribute with the same name. /// /// # Panics /// /// Panics if `name` is `DW_AT_sibling`. Use `set_sibling` instead. pub fn set(&mut self, name: constants::DwAt, value: AttributeValue) { assert_ne!(name, constants::DW_AT_sibling); if let Some(attr) = self.attrs.iter_mut().find(|attr| attr.name == name) { attr.value = value; return; } self.attrs.push(Attribute { name, value }); } /// Delete an attribute. /// /// Replaces any existing attribute with the same name. pub fn delete(&mut self, name: constants::DwAt) { self.attrs.retain(|x| x.name != name); } /// Iterate over the children of this entry. /// /// Note: use `Unit::add` to add a new child to this entry. #[inline] pub fn children(&self) -> slice::Iter<UnitEntryId> { self.children.iter() } /// Return the type abbreviation for this DIE. fn abbreviation(&self, encoding: Encoding) -> Result<Abbreviation> { let mut attrs = Vec::new(); if self.sibling && !self.children.is_empty() { let form = match encoding.format { Format::Dwarf32 => constants::DW_FORM_ref4, Format::Dwarf64 => constants::DW_FORM_ref8, }; attrs.push(AttributeSpecification::new(constants::DW_AT_sibling, form)); } for attr in &self.attrs { attrs.push(attr.specification(encoding)?); } Ok(Abbreviation::new( self.tag, !self.children.is_empty(), attrs, )) } fn calculate_offsets( &self, unit: &Unit, offset: &mut usize, offsets: &mut UnitOffsets, abbrevs: &mut AbbreviationTable, ) -> Result<()> { offsets.entries[self.id.index].offset = DebugInfoOffset(*offset); offsets.entries[self.id.index].abbrev = abbrevs.add(self.abbreviation(unit.encoding())?); *offset += self.size(unit, offsets); if !self.children.is_empty() { for child in &self.children { unit.entries[child.index].calculate_offsets(unit, offset, offsets, abbrevs)?; } // Null child *offset += 1; } Ok(()) } fn size(&self, unit: &Unit, offsets: &UnitOffsets) -> usize { let mut size = uleb128_size(offsets.abbrev(self.id)); if self.sibling && !self.children.is_empty() { size += unit.format().word_size() as usize; } for attr in &self.attrs { size += attr.value.size(unit, offsets); } size } /// Write the entry to the given sections. #[allow(clippy::too_many_arguments)] fn write<W: Writer>( &self, w: &mut DebugInfo<W>, debug_info_refs: &mut Vec<DebugInfoReference>, unit_refs: &mut Vec<(DebugInfoOffset, UnitEntryId)>, unit: &Unit, offsets: &mut UnitOffsets, abbrevs: &mut AbbreviationTable, line_program: Option<DebugLineOffset>, line_strings: &DebugLineStrOffsets, strings: &DebugStrOffsets, range_lists: &RangeListOffsets, loc_lists: &LocationListOffsets, ) -> Result<()> { debug_assert_eq!(offsets.debug_info_offset(self.id), w.offset()); w.write_uleb128(offsets.abbrev(self.id))?; let sibling_offset = if self.sibling && !self.children.is_empty() { let offset = w.offset(); w.write_udata(0, unit.format().word_size())?; Some(offset) } else { None }; for attr in &self.attrs { attr.value.write( w, debug_info_refs, unit_refs, unit, offsets, line_program, line_strings, strings, range_lists, loc_lists, )?; } if !self.children.is_empty() { for child in &self.children { unit.entries[child.index].write( w, debug_info_refs, unit_refs, unit, offsets, abbrevs, line_program, line_strings, strings, range_lists, loc_lists, )?; } // Null child w.write_u8(0)?; } if let Some(offset) = sibling_offset { let next_offset = (w.offset().0 - offsets.unit.0) as u64; // This does not need relocation. w.write_udata_at(offset.0, next_offset, unit.format().word_size())?; } Ok(()) } } /// An attribute in a `DebuggingInformationEntry`, consisting of a name and /// associated value. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Attribute { name: constants::DwAt, value: AttributeValue, } impl Attribute { /// Get the name of this attribute. #[inline] pub fn name(&self) -> constants::DwAt { self.name } /// Get the value of this attribute. #[inline] pub fn get(&self) -> &AttributeValue { &self.value } /// Set the value of this attribute. #[inline] pub fn set(&mut self, value: AttributeValue) { self.value = value; } /// Return the type specification for this attribute. fn specification(&self, encoding: Encoding) -> Result<AttributeSpecification> { Ok(AttributeSpecification::new( self.name, self.value.form(encoding)?, )) } } /// The value of an attribute in a `DebuggingInformationEntry`. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AttributeValue { /// "Refers to some location in the address space of the described program." Address(Address), /// A slice of an arbitrary number of bytes. Block(Vec<u8>), /// A one byte constant data value. How to interpret the byte depends on context. /// /// From section 7 of the standard: "Depending on context, it may be a /// signed integer, an unsigned integer, a floating-point constant, or /// anything else." Data1(u8), /// A two byte constant data value. How to interpret the bytes depends on context. /// /// This value will be converted to the target endian before writing. /// /// From section 7 of the standard: "Depending on context, it may be a /// signed integer, an unsigned integer, a floating-point constant, or /// anything else." Data2(u16), /// A four byte constant data value. How to interpret the bytes depends on context. /// /// This value will be converted to the target endian before writing. /// /// From section 7 of the standard: "Depending on context, it may be a /// signed integer, an unsigned integer, a floating-point constant, or /// anything else." Data4(u32), /// An eight byte constant data value. How to interpret the bytes depends on context. /// /// This value will be converted to the target endian before writing. /// /// From section 7 of the standard: "Depending on context, it may be a /// signed integer, an unsigned integer, a floating-point constant, or /// anything else." Data8(u64), /// A signed integer constant. Sdata(i64), /// An unsigned integer constant. Udata(u64), /// "The information bytes contain a DWARF expression (see Section 2.5) or /// location description (see Section 2.6)." Exprloc(Expression), /// A boolean that indicates presence or absence of the attribute. Flag(bool), /// An attribute that is always present. FlagPresent, /// A reference to a `DebuggingInformationEntry` in this unit. UnitRef(UnitEntryId), /// A reference to a `DebuggingInformationEntry` in a potentially different unit. DebugInfoRef(Reference), /// An offset into the `.debug_info` section of the supplementary object file. /// /// The API does not currently assist with generating this offset. /// This variant will be removed from the API once support for writing /// supplementary object files is implemented. DebugInfoRefSup(DebugInfoOffset), /// A reference to a line number program. LineProgramRef, /// A reference to a location list. LocationListRef(LocationListId), /// An offset into the `.debug_macinfo` section. /// /// The API does not currently assist with generating this offset. /// This variant will be removed from the API once support for writing /// `.debug_macinfo` sections is implemented. DebugMacinfoRef(DebugMacinfoOffset), /// An offset into the `.debug_macro` section. /// /// The API does not currently assist with generating this offset. /// This variant will be removed from the API once support for writing /// `.debug_macro` sections is implemented. DebugMacroRef(DebugMacroOffset), /// A reference to a range list. RangeListRef(RangeListId), /// A type signature. /// /// The API does not currently assist with generating this signature. /// This variant will be removed from the API once support for writing /// `.debug_types` sections is implemented. DebugTypesRef(DebugTypeSignature), /// A reference to a string in the `.debug_str` section. StringRef(StringId), /// An offset into the `.debug_str` section of the supplementary object file. /// /// The API does not currently assist with generating this offset. /// This variant will be removed from the API once support for writing /// supplementary object files is implemented. DebugStrRefSup(DebugStrOffset), /// A reference to a string in the `.debug_line_str` section. LineStringRef(LineStringId), /// A slice of bytes representing a string. Must not include null bytes. /// Not guaranteed to be UTF-8 or anything like that. String(Vec<u8>), /// The value of a `DW_AT_encoding` attribute. Encoding(constants::DwAte), /// The value of a `DW_AT_decimal_sign` attribute. DecimalSign(constants::DwDs), /// The value of a `DW_AT_endianity` attribute. Endianity(constants::DwEnd), /// The value of a `DW_AT_accessibility` attribute. Accessibility(constants::DwAccess), /// The value of a `DW_AT_visibility` attribute. Visibility(constants::DwVis), /// The value of a `DW_AT_virtuality` attribute. Virtuality(constants::DwVirtuality), /// The value of a `DW_AT_language` attribute. Language(constants::DwLang), /// The value of a `DW_AT_address_class` attribute. AddressClass(constants::DwAddr), /// The value of a `DW_AT_identifier_case` attribute. IdentifierCase(constants::DwId), /// The value of a `DW_AT_calling_convention` attribute. CallingConvention(constants::DwCc), /// The value of a `DW_AT_inline` attribute. Inline(constants::DwInl), /// The value of a `DW_AT_ordering` attribute. Ordering(constants::DwOrd), /// An index into the filename entries from the line number information /// table for the unit containing this value. FileIndex(Option<FileId>), } impl AttributeValue { /// Return the form that will be used to encode this value. pub fn form(&self, encoding: Encoding) -> Result<constants::DwForm> { // TODO: missing forms: // - DW_FORM_indirect // - DW_FORM_implicit_const // - FW_FORM_block1/block2/block4 // - DW_FORM_str/strx1/strx2/strx3/strx4 // - DW_FORM_addrx/addrx1/addrx2/addrx3/addrx4 // - DW_FORM_data16 // - DW_FORM_line_strp // - DW_FORM_loclistx // - DW_FORM_rnglistx let form = match *self { AttributeValue::Address(_) => constants::DW_FORM_addr, AttributeValue::Block(_) => constants::DW_FORM_block, AttributeValue::Data1(_) => constants::DW_FORM_data1, AttributeValue::Data2(_) => constants::DW_FORM_data2, AttributeValue::Data4(_) => constants::DW_FORM_data4, AttributeValue::Data8(_) => constants::DW_FORM_data8, AttributeValue::Exprloc(_) => constants::DW_FORM_exprloc, AttributeValue::Flag(_) => constants::DW_FORM_flag, AttributeValue::FlagPresent => constants::DW_FORM_flag_present, AttributeValue::UnitRef(_) => { // Using a fixed size format lets us write a placeholder before we know // the value. match encoding.format { Format::Dwarf32 => constants::DW_FORM_ref4, Format::Dwarf64 => constants::DW_FORM_ref8, } } AttributeValue::DebugInfoRef(_) => constants::DW_FORM_ref_addr, AttributeValue::DebugInfoRefSup(_) => { // TODO: should this depend on the size of supplementary section? match encoding.format { Format::Dwarf32 => constants::DW_FORM_ref_sup4, Format::Dwarf64 => constants::DW_FORM_ref_sup8, } } AttributeValue::LineProgramRef | AttributeValue::LocationListRef(_) | AttributeValue::DebugMacinfoRef(_) | AttributeValue::DebugMacroRef(_) | AttributeValue::RangeListRef(_) => { if encoding.version == 2 || encoding.version == 3 { match encoding.format { Format::Dwarf32 => constants::DW_FORM_data4, Format::Dwarf64 => constants::DW_FORM_data8, } } else { constants::DW_FORM_sec_offset } } AttributeValue::DebugTypesRef(_) => constants::DW_FORM_ref_sig8, AttributeValue::StringRef(_) => constants::DW_FORM_strp, AttributeValue::DebugStrRefSup(_) => constants::DW_FORM_strp_sup, AttributeValue::LineStringRef(_) => constants::DW_FORM_line_strp, AttributeValue::String(_) => constants::DW_FORM_string, AttributeValue::Encoding(_) | AttributeValue::DecimalSign(_) | AttributeValue::Endianity(_) | AttributeValue::Accessibility(_) | AttributeValue::Visibility(_) | AttributeValue::Virtuality(_) | AttributeValue::Language(_) | AttributeValue::AddressClass(_) | AttributeValue::IdentifierCase(_) | AttributeValue::CallingConvention(_) | AttributeValue::Inline(_) | AttributeValue::Ordering(_) | AttributeValue::FileIndex(_) | AttributeValue::Udata(_) => constants::DW_FORM_udata, AttributeValue::Sdata(_) => constants::DW_FORM_sdata, }; Ok(form) } fn size(&self, unit: &Unit, offsets: &UnitOffsets) -> usize { macro_rules! debug_assert_form { ($form:expr) => { debug_assert_eq!(self.form(unit.encoding()).unwrap(), $form) }; } match *self { AttributeValue::Address(_) => { debug_assert_form!(constants::DW_FORM_addr); unit.address_size() as usize } AttributeValue::Block(ref val) => { debug_assert_form!(constants::DW_FORM_block); uleb128_size(val.len() as u64) + val.len() } AttributeValue::Data1(_) => { debug_assert_form!(constants::DW_FORM_data1); 1 } AttributeValue::Data2(_) => { debug_assert_form!(constants::DW_FORM_data2); 2 } AttributeValue::Data4(_) => { debug_assert_form!(constants::DW_FORM_data4); 4 } AttributeValue::Data8(_) => { debug_assert_form!(constants::DW_FORM_data8); 8 } AttributeValue::Sdata(val) => { debug_assert_form!(constants::DW_FORM_sdata); sleb128_size(val) } AttributeValue::Udata(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val) } AttributeValue::Exprloc(ref val) => { debug_assert_form!(constants::DW_FORM_exprloc); let size = val.size(unit.encoding(), Some(offsets)); uleb128_size(size as u64) + size } AttributeValue::Flag(_) => { debug_assert_form!(constants::DW_FORM_flag); 1 } AttributeValue::FlagPresent => { debug_assert_form!(constants::DW_FORM_flag_present); 0 } AttributeValue::UnitRef(_) => { match unit.format() { Format::Dwarf32 => debug_assert_form!(constants::DW_FORM_ref4), Format::Dwarf64 => debug_assert_form!(constants::DW_FORM_ref8), } unit.format().word_size() as usize } AttributeValue::DebugInfoRef(_) => { debug_assert_form!(constants::DW_FORM_ref_addr); if unit.version() == 2 { unit.address_size() as usize } else { unit.format().word_size() as usize } } AttributeValue::DebugInfoRefSup(_) => { match unit.format() { Format::Dwarf32 => debug_assert_form!(constants::DW_FORM_ref_sup4), Format::Dwarf64 => debug_assert_form!(constants::DW_FORM_ref_sup8), } unit.format().word_size() as usize } AttributeValue::LineProgramRef => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } unit.format().word_size() as usize } AttributeValue::LocationListRef(_) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } unit.format().word_size() as usize } AttributeValue::DebugMacinfoRef(_) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } unit.format().word_size() as usize } AttributeValue::DebugMacroRef(_) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } unit.format().word_size() as usize } AttributeValue::RangeListRef(_) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } unit.format().word_size() as usize } AttributeValue::DebugTypesRef(_) => { debug_assert_form!(constants::DW_FORM_ref_sig8); 8 } AttributeValue::StringRef(_) => { debug_assert_form!(constants::DW_FORM_strp); unit.format().word_size() as usize } AttributeValue::DebugStrRefSup(_) => { debug_assert_form!(constants::DW_FORM_strp_sup); unit.format().word_size() as usize } AttributeValue::LineStringRef(_) => { debug_assert_form!(constants::DW_FORM_line_strp); unit.format().word_size() as usize } AttributeValue::String(ref val) => { debug_assert_form!(constants::DW_FORM_string); val.len() + 1 } AttributeValue::Encoding(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::DecimalSign(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Endianity(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Accessibility(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Visibility(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Virtuality(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Language(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::AddressClass(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::IdentifierCase(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::CallingConvention(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Inline(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::Ordering(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.0 as u64) } AttributeValue::FileIndex(val) => { debug_assert_form!(constants::DW_FORM_udata); uleb128_size(val.map(FileId::raw).unwrap_or(0)) } } } /// Write the attribute value to the given sections. #[allow(clippy::cyclomatic_complexity, clippy::too_many_arguments)] fn write<W: Writer>( &self, w: &mut DebugInfo<W>, debug_info_refs: &mut Vec<DebugInfoReference>, unit_refs: &mut Vec<(DebugInfoOffset, UnitEntryId)>, unit: &Unit, offsets: &UnitOffsets, line_program: Option<DebugLineOffset>, line_strings: &DebugLineStrOffsets, strings: &DebugStrOffsets, range_lists: &RangeListOffsets, loc_lists: &LocationListOffsets, ) -> Result<()> { macro_rules! debug_assert_form { ($form:expr) => { debug_assert_eq!(self.form(unit.encoding()).unwrap(), $form) }; } match *self { AttributeValue::Address(val) => { debug_assert_form!(constants::DW_FORM_addr); w.write_address(val, unit.address_size())?; } AttributeValue::Block(ref val) => { debug_assert_form!(constants::DW_FORM_block); w.write_uleb128(val.len() as u64)?; w.write(&val)?; } AttributeValue::Data1(val) => { debug_assert_form!(constants::DW_FORM_data1); w.write_u8(val)?; } AttributeValue::Data2(val) => { debug_assert_form!(constants::DW_FORM_data2); w.write_u16(val)?; } AttributeValue::Data4(val) => { debug_assert_form!(constants::DW_FORM_data4); w.write_u32(val)?; } AttributeValue::Data8(val) => { debug_assert_form!(constants::DW_FORM_data8); w.write_u64(val)?; } AttributeValue::Sdata(val) => { debug_assert_form!(constants::DW_FORM_sdata); w.write_sleb128(val)?; } AttributeValue::Udata(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(val)?; } AttributeValue::Exprloc(ref val) => { debug_assert_form!(constants::DW_FORM_exprloc); w.write_uleb128(val.size(unit.encoding(), Some(offsets)) as u64)?; val.write( &mut w.0, Some(debug_info_refs), unit.encoding(), Some(offsets), )?; } AttributeValue::Flag(val) => { debug_assert_form!(constants::DW_FORM_flag); w.write_u8(val as u8)?; } AttributeValue::FlagPresent => { debug_assert_form!(constants::DW_FORM_flag_present); } AttributeValue::UnitRef(id) => { match unit.format() { Format::Dwarf32 => debug_assert_form!(constants::DW_FORM_ref4), Format::Dwarf64 => debug_assert_form!(constants::DW_FORM_ref8), } unit_refs.push((w.offset(), id)); w.write_udata(0, unit.format().word_size())?; } AttributeValue::DebugInfoRef(reference) => { debug_assert_form!(constants::DW_FORM_ref_addr); let size = if unit.version() == 2 { unit.address_size() } else { unit.format().word_size() }; match reference { Reference::Symbol(symbol) => w.write_reference(symbol, size)?, Reference::Entry(unit, entry) => { debug_info_refs.push(DebugInfoReference { offset: w.len(), unit, entry, size, }); w.write_udata(0, size)?; } } } AttributeValue::DebugInfoRefSup(val) => { match unit.format() { Format::Dwarf32 => debug_assert_form!(constants::DW_FORM_ref_sup4), Format::Dwarf64 => debug_assert_form!(constants::DW_FORM_ref_sup8), } w.write_udata(val.0 as u64, unit.format().word_size())?; } AttributeValue::LineProgramRef => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } match line_program { Some(line_program) => { w.write_offset( line_program.0, SectionId::DebugLine, unit.format().word_size(), )?; } None => return Err(Error::InvalidAttributeValue), } } AttributeValue::LocationListRef(val) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } let section = if unit.version() <= 4 { SectionId::DebugLoc } else { SectionId::DebugLocLists }; w.write_offset(loc_lists.get(val).0, section, unit.format().word_size())?; } AttributeValue::DebugMacinfoRef(val) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } w.write_offset(val.0, SectionId::DebugMacinfo, unit.format().word_size())?; } AttributeValue::DebugMacroRef(val) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } w.write_offset(val.0, SectionId::DebugMacro, unit.format().word_size())?; } AttributeValue::RangeListRef(val) => { if unit.version() >= 4 { debug_assert_form!(constants::DW_FORM_sec_offset); } let section = if unit.version() <= 4 { SectionId::DebugRanges } else { SectionId::DebugRngLists }; w.write_offset(range_lists.get(val).0, section, unit.format().word_size())?; } AttributeValue::DebugTypesRef(val) => { debug_assert_form!(constants::DW_FORM_ref_sig8); w.write_u64(val.0)?; } AttributeValue::StringRef(val) => { debug_assert_form!(constants::DW_FORM_strp); w.write_offset( strings.get(val).0, SectionId::DebugStr, unit.format().word_size(), )?; } AttributeValue::DebugStrRefSup(val) => { debug_assert_form!(constants::DW_FORM_strp_sup); w.write_udata(val.0 as u64, unit.format().word_size())?; } AttributeValue::LineStringRef(val) => { debug_assert_form!(constants::DW_FORM_line_strp); w.write_offset( line_strings.get(val).0, SectionId::DebugLineStr, unit.format().word_size(), )?; } AttributeValue::String(ref val) => { debug_assert_form!(constants::DW_FORM_string); w.write(&val)?; w.write_u8(0)?; } AttributeValue::Encoding(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::DecimalSign(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Endianity(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Accessibility(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Visibility(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Virtuality(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Language(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::AddressClass(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(val.0)?; } AttributeValue::IdentifierCase(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::CallingConvention(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Inline(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::Ordering(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(u64::from(val.0))?; } AttributeValue::FileIndex(val) => { debug_assert_form!(constants::DW_FORM_udata); w.write_uleb128(val.map(FileId::raw).unwrap_or(0))?; } } Ok(()) } } define_section!( DebugInfo, DebugInfoOffset, "A writable `.debug_info` section." ); /// The section offsets of all elements within a `.debug_info` section. #[derive(Debug, Default)] pub struct DebugInfoOffsets { base_id: BaseId, units: Vec<UnitOffsets>, } impl DebugInfoOffsets { #[cfg(test)] pub(crate) fn unit_offsets(&self, unit: UnitId) -> &UnitOffsets { debug_assert_eq!(self.base_id, unit.base_id); &self.units[unit.index] } /// Get the `.debug_info` section offset for the given unit. #[inline] pub fn unit(&self, unit: UnitId) -> DebugInfoOffset { debug_assert_eq!(self.base_id, unit.base_id); self.units[unit.index].unit } /// Get the `.debug_info` section offset for the given entry. #[inline] pub fn entry(&self, unit: UnitId, entry: UnitEntryId) -> DebugInfoOffset { debug_assert_eq!(self.base_id, unit.base_id); self.units[unit.index].debug_info_offset(entry) } } /// The section offsets of all elements of a unit within a `.debug_info` section. #[derive(Debug)] pub(crate) struct UnitOffsets { base_id: BaseId, unit: DebugInfoOffset, entries: Vec<EntryOffset>, } impl UnitOffsets { #[cfg(test)] fn none() -> Self { UnitOffsets { base_id: BaseId::default(), unit: DebugInfoOffset(0), entries: Vec::new(), } } /// Get the .debug_info offset for the given entry. #[inline] pub(crate) fn debug_info_offset(&self, entry: UnitEntryId) -> DebugInfoOffset { debug_assert_eq!(self.base_id, entry.base_id); let offset = self.entries[entry.index].offset; debug_assert_ne!(offset.0, 0); offset } /// Get the unit offset for the given entry. #[inline] pub(crate) fn unit_offset(&self, entry: UnitEntryId) -> u64 { let offset = self.debug_info_offset(entry); (offset.0 - self.unit.0) as u64 } /// Get the abbreviation code for the given entry. #[inline] pub(crate) fn abbrev(&self, entry: UnitEntryId) -> u64 { debug_assert_eq!(self.base_id, entry.base_id); self.entries[entry.index].abbrev } } #[derive(Debug, Clone, Copy)] pub(crate) struct EntryOffset { offset: DebugInfoOffset, abbrev: u64, } impl EntryOffset { fn none() -> Self { EntryOffset { offset: DebugInfoOffset(0), abbrev: 0, } } } /// A reference to a `.debug_info` entry that has yet to be resolved. #[derive(Debug, Clone, Copy)] pub(crate) struct DebugInfoReference { /// The offset within the section of the reference. pub offset: usize, /// The size of the reference. pub size: u8, /// The unit containing the entry. pub unit: UnitId, /// The entry being referenced. pub entry: UnitEntryId, } #[cfg(feature = "read")] pub(crate) mod convert { use super::*; use crate::common::UnitSectionOffset; use crate::read::{self, Reader}; use crate::write::{self, ConvertError, ConvertResult, LocationList, RangeList}; use std::collections::HashMap; pub(crate) struct ConvertUnit<R: Reader<Offset = usize>> { from_unit: read::Unit<R>, base_id: BaseId, encoding: Encoding, entries: Vec<DebuggingInformationEntry>, entry_offsets: Vec<read::UnitOffset>, root: UnitEntryId, } pub(crate) struct ConvertUnitContext<'a, R: Reader<Offset = usize>> { pub dwarf: &'a read::Dwarf<R>, pub unit: &'a read::Unit<R>, pub line_strings: &'a mut write::LineStringTable, pub strings: &'a mut write::StringTable, pub ranges: &'a mut write::RangeListTable, pub locations: &'a mut write::LocationListTable, pub convert_address: &'a dyn Fn(u64) -> Option<Address>, pub base_address: Address, pub line_program_offset: Option<DebugLineOffset>, pub line_program_files: Vec<FileId>, pub entry_ids: &'a HashMap<UnitSectionOffset, (UnitId, UnitEntryId)>, } impl UnitTable { /// Create a unit table by reading the data in the given sections. /// /// This also updates the given tables with the values that are referenced from /// attributes in this section. /// /// `convert_address` is a function to convert read addresses into the `Address` /// type. For non-relocatable addresses, this function may simply return /// `Address::Constant(address)`. For relocatable addresses, it is the caller's /// responsibility to determine the symbol and addend corresponding to the address /// and return `Address::Symbol { symbol, addend }`. pub fn from<R: Reader<Offset = usize>>( dwarf: &read::Dwarf<R>, line_strings: &mut write::LineStringTable, strings: &mut write::StringTable, convert_address: &dyn Fn(u64) -> Option<Address>, ) -> ConvertResult<UnitTable> { let base_id = BaseId::default(); let mut unit_entries = Vec::new(); let mut entry_ids = HashMap::new(); let mut from_units = dwarf.units(); while let Some(from_unit) = from_units.next()? { let unit_id = UnitId::new(base_id, unit_entries.len()); unit_entries.push(Unit::convert_entries( from_unit, unit_id, &mut entry_ids, dwarf, )?); } // Attributes must be converted in a separate pass so that we can handle // references to other compilation units. let mut units = Vec::new(); for unit_entries in unit_entries.drain(..) { units.push(Unit::convert_attributes( unit_entries, &entry_ids, dwarf, line_strings, strings, convert_address, )?); } Ok(UnitTable { base_id, units }) } } impl Unit { /// Create a unit by reading the data in the input sections. /// /// Does not add entry attributes. #[allow(clippy::too_many_arguments)] pub(crate) fn convert_entries<R: Reader<Offset = usize>>( from_header: read::CompilationUnitHeader<R>, unit_id: UnitId, entry_ids: &mut HashMap<UnitSectionOffset, (UnitId, UnitEntryId)>, dwarf: &read::Dwarf<R>, ) -> ConvertResult<ConvertUnit<R>> { let base_id = BaseId::default(); let from_unit = dwarf.unit(from_header)?; let encoding = from_unit.encoding(); let mut entries = Vec::new(); let mut entry_offsets = Vec::new(); let mut from_tree = from_unit.entries_tree(None)?; let from_root = from_tree.root()?; let root = DebuggingInformationEntry::convert_entry( from_root, &from_unit, base_id, &mut entries, &mut entry_offsets, entry_ids, None, unit_id, )?; Ok(ConvertUnit { from_unit, base_id, encoding, entries, entry_offsets, root, }) } /// Create entry attributes by reading the data in the input sections. fn convert_attributes<R: Reader<Offset = usize>>( unit: ConvertUnit<R>, entry_ids: &HashMap<UnitSectionOffset, (UnitId, UnitEntryId)>, dwarf: &read::Dwarf<R>, line_strings: &mut write::LineStringTable, strings: &mut write::StringTable, convert_address: &dyn Fn(u64) -> Option<Address>, ) -> ConvertResult<Unit> { let from_unit = unit.from_unit; let base_address = convert_address(from_unit.low_pc).ok_or(ConvertError::InvalidAddress)?; let (line_program_offset, line_program, line_program_files) = match from_unit.line_program { Some(ref from_program) => { let from_program = from_program.clone(); let line_program_offset = from_program.header().offset(); let (line_program, line_program_files) = LineProgram::from( from_program, dwarf, line_strings, strings, convert_address, )?; (Some(line_program_offset), line_program, line_program_files) } None => (None, LineProgram::none(), Vec::new()), }; let mut ranges = RangeListTable::default(); let mut locations = LocationListTable::default(); let mut context = ConvertUnitContext { entry_ids, dwarf, unit: &from_unit, line_strings, strings, ranges: &mut ranges, locations: &mut locations, convert_address, base_address, line_program_offset, line_program_files, }; let mut entries = unit.entries; for entry in &mut entries { entry.convert_attributes(&mut context, &unit.entry_offsets)?; } Ok(Unit { base_id: unit.base_id, encoding: unit.encoding, line_program, ranges, locations, entries, root: unit.root, }) } } impl DebuggingInformationEntry { /// Create an entry by reading the data in the input sections. /// /// Does not add the entry attributes. fn convert_entry<R: Reader<Offset = usize>>( from: read::EntriesTreeNode<R>, from_unit: &read::Unit<R>, base_id: BaseId, entries: &mut Vec<DebuggingInformationEntry>, entry_offsets: &mut Vec<read::UnitOffset>, entry_ids: &mut HashMap<UnitSectionOffset, (UnitId, UnitEntryId)>, parent: Option<UnitEntryId>, unit_id: UnitId, ) -> ConvertResult<UnitEntryId> { let from_entry = from.entry(); let id = DebuggingInformationEntry::new(base_id, entries, parent, from_entry.tag()); let offset = from_entry.offset(); entry_offsets.push(offset); entry_ids.insert(offset.to_unit_section_offset(from_unit), (unit_id, id)); let mut from_children = from.children(); while let Some(from_child) = from_children.next()? { DebuggingInformationEntry::convert_entry( from_child, from_unit, base_id, entries, entry_offsets, entry_ids, Some(id), unit_id, )?; } Ok(id) } /// Create an entry's attributes by reading the data in the input sections. fn convert_attributes<R: Reader<Offset = usize>>( &mut self, context: &mut ConvertUnitContext<R>, entry_offsets: &[read::UnitOffset], ) -> ConvertResult<()> { let offset = entry_offsets[self.id.index]; let from = context.unit.entry(offset)?; let mut from_attrs = from.attrs(); while let Some(from_attr) = from_attrs.next()? { if from_attr.name() == constants::DW_AT_sibling { // This may point to a null entry, so we have to treat it differently. self.set_sibling(true); } else if let Some(attr) = Attribute::from(context, &from_attr)? { self.set(attr.name, attr.value); } } Ok(()) } } impl Attribute { /// Create an attribute by reading the data in the given sections. pub(crate) fn from<R: Reader<Offset = usize>>( context: &mut ConvertUnitContext<R>, from: &read::Attribute<R>, ) -> ConvertResult<Option<Attribute>> { let value = AttributeValue::from(context, from.value())?; Ok(value.map(|value| Attribute { name: from.name(), value, })) } } impl AttributeValue { /// Create an attribute value by reading the data in the given sections. pub(crate) fn from<R: Reader<Offset = usize>>( context: &mut ConvertUnitContext<R>, from: read::AttributeValue<R>, ) -> ConvertResult<Option<AttributeValue>> { let to = match from { read::AttributeValue::Addr(val) => match (context.convert_address)(val) { Some(val) => AttributeValue::Address(val), None => return Err(ConvertError::InvalidAddress), }, read::AttributeValue::Block(r) => AttributeValue::Block(r.to_slice()?.into()), read::AttributeValue::Data1(val) => AttributeValue::Data1(val), read::AttributeValue::Data2(val) => AttributeValue::Data2(val), read::AttributeValue::Data4(val) => AttributeValue::Data4(val), read::AttributeValue::Data8(val) => AttributeValue::Data8(val), read::AttributeValue::Sdata(val) => AttributeValue::Sdata(val), read::AttributeValue::Udata(val) => AttributeValue::Udata(val), read::AttributeValue::Exprloc(expression) => { let expression = Expression::from( expression, context.unit.encoding(), Some(context.dwarf), Some(context.unit), Some(context.entry_ids), context.convert_address, )?; AttributeValue::Exprloc(expression) } // TODO: it would be nice to preserve the flag form. read::AttributeValue::Flag(val) => AttributeValue::Flag(val), read::AttributeValue::DebugAddrBase(_base) => { // We convert all address indices to addresses, // so this is unneeded. return Ok(None); } read::AttributeValue::DebugAddrIndex(index) => { let val = context.dwarf.address(context.unit, index)?; match (context.convert_address)(val) { Some(val) => AttributeValue::Address(val), None => return Err(ConvertError::InvalidAddress), } } read::AttributeValue::UnitRef(val) => { if !context.unit.header.is_valid_offset(val) { return Err(ConvertError::InvalidUnitRef); } let id = context .entry_ids .get(&val.to_unit_section_offset(context.unit)) .ok_or(ConvertError::InvalidUnitRef)?; AttributeValue::UnitRef(id.1) } read::AttributeValue::DebugInfoRef(val) => { // TODO: support relocation of this value let id = context .entry_ids .get(&UnitSectionOffset::DebugInfoOffset(val)) .ok_or(ConvertError::InvalidDebugInfoRef)?; AttributeValue::DebugInfoRef(Reference::Entry(id.0, id.1)) } read::AttributeValue::DebugInfoRefSup(val) => AttributeValue::DebugInfoRefSup(val), read::AttributeValue::DebugLineRef(val) => { // There should only be the line program in the CU DIE which we've already // converted, so check if it matches that. if Some(val) == context.line_program_offset { AttributeValue::LineProgramRef } else { return Err(ConvertError::InvalidLineRef); } } read::AttributeValue::DebugMacinfoRef(val) => AttributeValue::DebugMacinfoRef(val), read::AttributeValue::DebugMacroRef(val) => AttributeValue::DebugMacroRef(val), read::AttributeValue::LocationListsRef(val) => { let iter = context .dwarf .locations .raw_locations(val, context.unit.encoding())?; let loc_list = LocationList::from(iter, context)?; let loc_id = context.locations.add(loc_list); AttributeValue::LocationListRef(loc_id) } read::AttributeValue::DebugLocListsBase(_base) => { // We convert all location list indices to offsets, // so this is unneeded. return Ok(None); } read::AttributeValue::DebugLocListsIndex(index) => { let offset = context.dwarf.locations_offset(context.unit, index)?; let iter = context .dwarf .locations .raw_locations(offset, context.unit.encoding())?; let loc_list = LocationList::from(iter, context)?; let loc_id = context.locations.add(loc_list); AttributeValue::LocationListRef(loc_id) } read::AttributeValue::RangeListsRef(val) => { let iter = context .dwarf .ranges .raw_ranges(val, context.unit.encoding())?; let range_list = RangeList::from(iter, context)?; let range_id = context.ranges.add(range_list); AttributeValue::RangeListRef(range_id) } read::AttributeValue::DebugRngListsBase(_base) => { // We convert all range list indices to offsets, // so this is unneeded. return Ok(None); } read::AttributeValue::DebugRngListsIndex(index) => { let offset = context.dwarf.ranges_offset(context.unit, index)?; let iter = context .dwarf .ranges .raw_ranges(offset, context.unit.encoding())?; let range_list = RangeList::from(iter, context)?; let range_id = context.ranges.add(range_list); AttributeValue::RangeListRef(range_id) } read::AttributeValue::DebugTypesRef(val) => AttributeValue::DebugTypesRef(val), read::AttributeValue::DebugStrRef(offset) => { let r = context.dwarf.string(offset)?; let id = context.strings.add(r.to_slice()?); AttributeValue::StringRef(id) } read::AttributeValue::DebugStrRefSup(val) => AttributeValue::DebugStrRefSup(val), read::AttributeValue::DebugStrOffsetsBase(_base) => { // We convert all string offsets to `.debug_str` references, // so this is unneeded. return Ok(None); } read::AttributeValue::DebugStrOffsetsIndex(index) => { let offset = context.dwarf.string_offset(context.unit, index)?; let r = context.dwarf.string(offset)?; let id = context.strings.add(r.to_slice()?); AttributeValue::StringRef(id) } read::AttributeValue::DebugLineStrRef(offset) => { let r = context.dwarf.line_string(offset)?; let id = context.line_strings.add(r.to_slice()?); AttributeValue::LineStringRef(id) } read::AttributeValue::String(r) => AttributeValue::String(r.to_slice()?.into()), read::AttributeValue::Encoding(val) => AttributeValue::Encoding(val), read::AttributeValue::DecimalSign(val) => AttributeValue::DecimalSign(val), read::AttributeValue::Endianity(val) => AttributeValue::Endianity(val), read::AttributeValue::Accessibility(val) => AttributeValue::Accessibility(val), read::AttributeValue::Visibility(val) => AttributeValue::Visibility(val), read::AttributeValue::Virtuality(val) => AttributeValue::Virtuality(val), read::AttributeValue::Language(val) => AttributeValue::Language(val), read::AttributeValue::AddressClass(val) => AttributeValue::AddressClass(val), read::AttributeValue::IdentifierCase(val) => AttributeValue::IdentifierCase(val), read::AttributeValue::CallingConvention(val) => { AttributeValue::CallingConvention(val) } read::AttributeValue::Inline(val) => AttributeValue::Inline(val), read::AttributeValue::Ordering(val) => AttributeValue::Ordering(val), read::AttributeValue::FileIndex(val) => { if val == 0 { // 0 means not specified, even for version 5. AttributeValue::FileIndex(None) } else { match context.line_program_files.get(val as usize) { Some(id) => AttributeValue::FileIndex(Some(*id)), None => return Err(ConvertError::InvalidFileIndex), } } } // Should always be a more specific section reference. read::AttributeValue::SecOffset(_) => { return Err(ConvertError::InvalidAttributeValue); } }; Ok(Some(to)) } } } #[cfg(test)] #[cfg(feature = "read")] mod tests { use super::*; use crate::common::{ DebugAddrBase, DebugLocListsBase, DebugRngListsBase, DebugStrOffsetsBase, LineEncoding, UnitSectionOffset, }; use crate::constants; use crate::read; use crate::write::{ DebugLine, DebugLineStr, DebugStr, EndianVec, LineString, LineStringTable, Location, LocationList, LocationListTable, Range, RangeList, RangeListOffsets, RangeListTable, StringTable, }; use crate::LittleEndian; use std::collections::HashMap; use std::mem; #[test] #[allow(clippy::cyclomatic_complexity)] fn test_unit_table() { let mut strings = StringTable::default(); let mut units = UnitTable::default(); let unit_id1 = units.add(Unit::new( Encoding { version: 4, address_size: 8, format: Format::Dwarf32, }, LineProgram::none(), )); let unit2 = units.add(Unit::new( Encoding { version: 2, address_size: 4, format: Format::Dwarf64, }, LineProgram::none(), )); let unit3 = units.add(Unit::new( Encoding { version: 5, address_size: 4, format: Format::Dwarf32, }, LineProgram::none(), )); assert_eq!(units.count(), 3); { let unit1 = units.get_mut(unit_id1); assert_eq!(unit1.version(), 4); assert_eq!(unit1.address_size(), 8); assert_eq!(unit1.format(), Format::Dwarf32); assert_eq!(unit1.count(), 1); let root_id = unit1.root(); assert_eq!(root_id, UnitEntryId::new(unit1.base_id, 0)); { let root = unit1.get_mut(root_id); assert_eq!(root.id(), root_id); assert!(root.parent().is_none()); assert_eq!(root.tag(), constants::DW_TAG_compile_unit); // Test get/get_mut assert!(root.get(constants::DW_AT_producer).is_none()); assert!(root.get_mut(constants::DW_AT_producer).is_none()); let mut producer = AttributeValue::String(b"root"[..].into()); root.set(constants::DW_AT_producer, producer.clone()); assert_eq!(root.get(constants::DW_AT_producer), Some(&producer)); assert_eq!(root.get_mut(constants::DW_AT_producer), Some(&mut producer)); // Test attrs let mut attrs = root.attrs(); let attr = attrs.next().unwrap(); assert_eq!(attr.name(), constants::DW_AT_producer); assert_eq!(attr.get(), &producer); assert!(attrs.next().is_none()); } let child1 = unit1.add(root_id, constants::DW_TAG_subprogram); assert_eq!(child1, UnitEntryId::new(unit1.base_id, 1)); { let child1 = unit1.get_mut(child1); assert_eq!(child1.parent(), Some(root_id)); let tmp = AttributeValue::String(b"tmp"[..].into()); child1.set(constants::DW_AT_name, tmp.clone()); assert_eq!(child1.get(constants::DW_AT_name), Some(&tmp)); // Test attrs_mut let name = AttributeValue::StringRef(strings.add(&b"child1"[..])); { let attr = child1.attrs_mut().next().unwrap(); assert_eq!(attr.name(), constants::DW_AT_name); attr.set(name.clone()); } assert_eq!(child1.get(constants::DW_AT_name), Some(&name)); } let child2 = unit1.add(root_id, constants::DW_TAG_subprogram); assert_eq!(child2, UnitEntryId::new(unit1.base_id, 2)); { let child2 = unit1.get_mut(child2); assert_eq!(child2.parent(), Some(root_id)); let tmp = AttributeValue::String(b"tmp"[..].into()); child2.set(constants::DW_AT_name, tmp.clone()); assert_eq!(child2.get(constants::DW_AT_name), Some(&tmp)); // Test replace let name = AttributeValue::StringRef(strings.add(&b"child2"[..])); child2.set(constants::DW_AT_name, name.clone()); assert_eq!(child2.get(constants::DW_AT_name), Some(&name)); } { let root = unit1.get(root_id); assert_eq!( root.children().cloned().collect::<Vec<_>>(), vec![child1, child2] ); } } { let unit2 = units.get(unit2); assert_eq!(unit2.version(), 2); assert_eq!(unit2.address_size(), 4); assert_eq!(unit2.format(), Format::Dwarf64); assert_eq!(unit2.count(), 1); let root = unit2.root(); assert_eq!(root, UnitEntryId::new(unit2.base_id, 0)); let root = unit2.get(root); assert_eq!(root.id(), UnitEntryId::new(unit2.base_id, 0)); assert!(root.parent().is_none()); assert_eq!(root.tag(), constants::DW_TAG_compile_unit); } let mut sections = Sections::new(EndianVec::new(LittleEndian)); let debug_line_str_offsets = DebugLineStrOffsets::none(); let debug_str_offsets = strings.write(&mut sections.debug_str).unwrap(); units .write(&mut sections, &debug_line_str_offsets, &debug_str_offsets) .unwrap(); println!("{:?}", sections.debug_str); println!("{:?}", sections.debug_info); println!("{:?}", sections.debug_abbrev); let dwarf = read::Dwarf { debug_abbrev: read::DebugAbbrev::new(sections.debug_abbrev.slice(), LittleEndian), debug_info: read::DebugInfo::new(sections.debug_info.slice(), LittleEndian), debug_str: read::DebugStr::new(sections.debug_str.slice(), LittleEndian), ..Default::default() }; let mut read_units = dwarf.units(); { let read_unit1 = read_units.next().unwrap().unwrap(); let unit1 = units.get(unit_id1); assert_eq!(unit1.version(), read_unit1.version()); assert_eq!(unit1.address_size(), read_unit1.address_size()); assert_eq!(unit1.format(), read_unit1.format()); let read_unit1 = dwarf.unit(read_unit1).unwrap(); let mut read_entries = read_unit1.entries(); let root = unit1.get(unit1.root()); { let (depth, read_root) = read_entries.next_dfs().unwrap().unwrap(); assert_eq!(depth, 0); assert_eq!(root.tag(), read_root.tag()); assert!(read_root.has_children()); let producer = match root.get(constants::DW_AT_producer).unwrap() { AttributeValue::String(ref producer) => &**producer, otherwise => panic!("unexpected {:?}", otherwise), }; assert_eq!(producer, b"root"); let read_producer = read_root .attr_value(constants::DW_AT_producer) .unwrap() .unwrap(); assert_eq!( dwarf .attr_string(&read_unit1, read_producer) .unwrap() .slice(), producer ); } let mut children = root.children().cloned(); { let child = children.next().unwrap(); assert_eq!(child, UnitEntryId::new(unit1.base_id, 1)); let child = unit1.get(child); let (depth, read_child) = read_entries.next_dfs().unwrap().unwrap(); assert_eq!(depth, 1); assert_eq!(child.tag(), read_child.tag()); assert!(!read_child.has_children()); let name = match child.get(constants::DW_AT_name).unwrap() { AttributeValue::StringRef(name) => *name, otherwise => panic!("unexpected {:?}", otherwise), }; let name = strings.get(name); assert_eq!(name, b"child1"); let read_name = read_child .attr_value(constants::DW_AT_name) .unwrap() .unwrap(); assert_eq!( dwarf.attr_string(&read_unit1, read_name).unwrap().slice(), name ); } { let child = children.next().unwrap(); assert_eq!(child, UnitEntryId::new(unit1.base_id, 2)); let child = unit1.get(child); let (depth, read_child) = read_entries.next_dfs().unwrap().unwrap(); assert_eq!(depth, 0); assert_eq!(child.tag(), read_child.tag()); assert!(!read_child.has_children()); let name = match child.get(constants::DW_AT_name).unwrap() { AttributeValue::StringRef(name) => *name, otherwise => panic!("unexpected {:?}", otherwise), }; let name = strings.get(name); assert_eq!(name, b"child2"); let read_name = read_child .attr_value(constants::DW_AT_name) .unwrap() .unwrap(); assert_eq!( dwarf.attr_string(&read_unit1, read_name).unwrap().slice(), name ); } assert!(read_entries.next_dfs().unwrap().is_none()); } { let read_unit2 = read_units.next().unwrap().unwrap(); let unit2 = units.get(unit2); assert_eq!(unit2.version(), read_unit2.version()); assert_eq!(unit2.address_size(), read_unit2.address_size()); assert_eq!(unit2.format(), read_unit2.format()); let abbrevs = dwarf.abbreviations(&read_unit2).unwrap(); let mut read_entries = read_unit2.entries(&abbrevs); { let root = unit2.get(unit2.root()); let (depth, read_root) = read_entries.next_dfs().unwrap().unwrap(); assert_eq!(depth, 0); assert_eq!(root.tag(), read_root.tag()); assert!(!read_root.has_children()); } assert!(read_entries.next_dfs().unwrap().is_none()); } { let read_unit3 = read_units.next().unwrap().unwrap(); let unit3 = units.get(unit3); assert_eq!(unit3.version(), read_unit3.version()); assert_eq!(unit3.address_size(), read_unit3.address_size()); assert_eq!(unit3.format(), read_unit3.format()); let abbrevs = dwarf.abbreviations(&read_unit3).unwrap(); let mut read_entries = read_unit3.entries(&abbrevs); { let root = unit3.get(unit3.root()); let (depth, read_root) = read_entries.next_dfs().unwrap().unwrap(); assert_eq!(depth, 0); assert_eq!(root.tag(), read_root.tag()); assert!(!read_root.has_children()); } assert!(read_entries.next_dfs().unwrap().is_none()); } assert!(read_units.next().unwrap().is_none()); let mut convert_line_strings = LineStringTable::default(); let mut convert_strings = StringTable::default(); let convert_units = UnitTable::from( &dwarf, &mut convert_line_strings, &mut convert_strings, &|address| Some(Address::Constant(address)), ) .unwrap(); assert_eq!(convert_units.count(), units.count()); for i in 0..convert_units.count() { let unit_id = units.id(i); let unit = units.get(unit_id); let convert_unit_id = convert_units.id(i); let convert_unit = convert_units.get(convert_unit_id); assert_eq!(convert_unit.version(), unit.version()); assert_eq!(convert_unit.address_size(), unit.address_size()); assert_eq!(convert_unit.format(), unit.format()); assert_eq!(convert_unit.count(), unit.count()); let root = unit.get(unit.root()); let convert_root = convert_unit.get(convert_unit.root()); assert_eq!(convert_root.tag(), root.tag()); for (convert_attr, attr) in convert_root.attrs().zip(root.attrs()) { assert_eq!(convert_attr, attr); } } } #[test] fn test_attribute_value() { // Create a string table and a string with a non-zero id/offset. let mut strings = StringTable::default(); strings.add("string one"); let string_id = strings.add("string two"); let mut debug_str = DebugStr::from(EndianVec::new(LittleEndian)); let debug_str_offsets = strings.write(&mut debug_str).unwrap(); let read_debug_str = read::DebugStr::new(debug_str.slice(), LittleEndian); let mut line_strings = LineStringTable::default(); line_strings.add("line string one"); let line_string_id = line_strings.add("line string two"); let mut debug_line_str = DebugLineStr::from(EndianVec::new(LittleEndian)); let debug_line_str_offsets = line_strings.write(&mut debug_line_str).unwrap(); let read_debug_line_str = read::DebugLineStr::from(read::EndianSlice::new(debug_line_str.slice(), LittleEndian)); let data = vec![1, 2, 3, 4]; let read_data = read::EndianSlice::new(&[1, 2, 3, 4], LittleEndian); let mut expression = Expression::new(); expression.op_constu(57); let read_expression = read::Expression(read::EndianSlice::new( &[constants::DW_OP_constu.0, 57], LittleEndian, )); let mut ranges = RangeListTable::default(); let range_id = ranges.add(RangeList(vec![Range::StartEnd { begin: Address::Constant(0x1234), end: Address::Constant(0x2345), }])); let mut locations = LocationListTable::default(); let loc_id = locations.add(LocationList(vec![Location::StartEnd { begin: Address::Constant(0x1234), end: Address::Constant(0x2345), data: expression.clone(), }])); for &version in &[2, 3, 4, 5] { for &address_size in &[4, 8] { for &format in &[Format::Dwarf32, Format::Dwarf64] { let encoding = Encoding { format, version, address_size, }; let mut sections = Sections::new(EndianVec::new(LittleEndian)); let range_list_offsets = ranges.write(&mut sections, encoding).unwrap(); let loc_list_offsets = locations.write(&mut sections, encoding, None).unwrap(); let read_debug_ranges = read::DebugRanges::new(sections.debug_ranges.slice(), LittleEndian); let read_debug_rnglists = read::DebugRngLists::new(sections.debug_rnglists.slice(), LittleEndian); let read_debug_loc = read::DebugLoc::new(sections.debug_loc.slice(), LittleEndian); let read_debug_loclists = read::DebugLocLists::new(sections.debug_loclists.slice(), LittleEndian); let mut units = UnitTable::default(); let unit = units.add(Unit::new(encoding, LineProgram::none())); let unit = units.get(unit); let encoding = Encoding { format, version, address_size, }; let from_unit = read::UnitHeader::new( encoding, 0, DebugAbbrevOffset(0), read::EndianSlice::new(&[], LittleEndian), ); for &(ref name, ref value, ref expect_value) in &[ ( constants::DW_AT_name, AttributeValue::Address(Address::Constant(0x1234)), read::AttributeValue::Addr(0x1234), ), ( constants::DW_AT_name, AttributeValue::Block(data.clone()), read::AttributeValue::Block(read_data), ), ( constants::DW_AT_name, AttributeValue::Data1(0x12), read::AttributeValue::Data1(0x12), ), ( constants::DW_AT_name, AttributeValue::Data2(0x1234), read::AttributeValue::Data2(0x1234), ), ( constants::DW_AT_name, AttributeValue::Data4(0x1234), read::AttributeValue::Data4(0x1234), ), ( constants::DW_AT_name, AttributeValue::Data8(0x1234), read::AttributeValue::Data8(0x1234), ), ( constants::DW_AT_name, AttributeValue::Sdata(0x1234), read::AttributeValue::Sdata(0x1234), ), ( constants::DW_AT_name, AttributeValue::Udata(0x1234), read::AttributeValue::Udata(0x1234), ), ( constants::DW_AT_name, AttributeValue::Exprloc(expression.clone()), read::AttributeValue::Exprloc(read_expression), ), ( constants::DW_AT_name, AttributeValue::Flag(false), read::AttributeValue::Flag(false), ), /* ( constants::DW_AT_name, AttributeValue::FlagPresent, read::AttributeValue::Flag(true), ), */ ( constants::DW_AT_name, AttributeValue::DebugInfoRefSup(DebugInfoOffset(0x1234)), read::AttributeValue::DebugInfoRefSup(DebugInfoOffset(0x1234)), ), ( constants::DW_AT_location, AttributeValue::LocationListRef(loc_id), read::AttributeValue::SecOffset(loc_list_offsets.get(loc_id).0), ), ( constants::DW_AT_macro_info, AttributeValue::DebugMacinfoRef(DebugMacinfoOffset(0x1234)), read::AttributeValue::SecOffset(0x1234), ), ( constants::DW_AT_macros, AttributeValue::DebugMacroRef(DebugMacroOffset(0x1234)), read::AttributeValue::SecOffset(0x1234), ), ( constants::DW_AT_ranges, AttributeValue::RangeListRef(range_id), read::AttributeValue::SecOffset(range_list_offsets.get(range_id).0), ), ( constants::DW_AT_name, AttributeValue::DebugTypesRef(DebugTypeSignature(0x1234)), read::AttributeValue::DebugTypesRef(DebugTypeSignature(0x1234)), ), ( constants::DW_AT_name, AttributeValue::StringRef(string_id), read::AttributeValue::DebugStrRef(debug_str_offsets.get(string_id)), ), ( constants::DW_AT_name, AttributeValue::DebugStrRefSup(DebugStrOffset(0x1234)), read::AttributeValue::DebugStrRefSup(DebugStrOffset(0x1234)), ), ( constants::DW_AT_name, AttributeValue::LineStringRef(line_string_id), read::AttributeValue::DebugLineStrRef( debug_line_str_offsets.get(line_string_id), ), ), ( constants::DW_AT_name, AttributeValue::String(data.clone()), read::AttributeValue::String(read_data), ), ( constants::DW_AT_encoding, AttributeValue::Encoding(constants::DwAte(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_decimal_sign, AttributeValue::DecimalSign(constants::DwDs(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_endianity, AttributeValue::Endianity(constants::DwEnd(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_accessibility, AttributeValue::Accessibility(constants::DwAccess(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_visibility, AttributeValue::Visibility(constants::DwVis(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_virtuality, AttributeValue::Virtuality(constants::DwVirtuality(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_language, AttributeValue::Language(constants::DwLang(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_address_class, AttributeValue::AddressClass(constants::DwAddr(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_identifier_case, AttributeValue::IdentifierCase(constants::DwId(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_calling_convention, AttributeValue::CallingConvention(constants::DwCc(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_ordering, AttributeValue::Ordering(constants::DwOrd(0x12)), read::AttributeValue::Udata(0x12), ), ( constants::DW_AT_inline, AttributeValue::Inline(constants::DwInl(0x12)), read::AttributeValue::Udata(0x12), ), ][..] { let form = value.form(encoding).unwrap(); let attr = Attribute { name: *name, value: value.clone(), }; let offsets = UnitOffsets::none(); let line_program_offset = None; let mut debug_info_refs = Vec::new(); let mut unit_refs = Vec::new(); let mut debug_info = DebugInfo::from(EndianVec::new(LittleEndian)); attr.value .write( &mut debug_info, &mut debug_info_refs, &mut unit_refs, &unit, &offsets, line_program_offset, &debug_line_str_offsets, &debug_str_offsets, &range_list_offsets, &loc_list_offsets, ) .unwrap(); let spec = read::AttributeSpecification::new(*name, form, None); let mut r = read::EndianSlice::new(debug_info.slice(), LittleEndian); let read_attr = read::parse_attribute(&mut r, encoding, spec).unwrap(); let read_value = &read_attr.raw_value(); // read::AttributeValue is invariant in the lifetime of R. // The lifetimes here are all okay, so transmute it. let read_value = unsafe { mem::transmute::< &read::AttributeValue<read::EndianSlice<LittleEndian>>, &read::AttributeValue<read::EndianSlice<LittleEndian>>, >(read_value) }; assert_eq!(read_value, expect_value); let dwarf = read::Dwarf { debug_str: read_debug_str.clone(), debug_line_str: read_debug_line_str.clone(), ranges: read::RangeLists::new(read_debug_ranges, read_debug_rnglists), locations: read::LocationLists::new( read_debug_loc, read_debug_loclists, ), ..Default::default() }; let unit = read::Unit { offset: UnitSectionOffset::DebugInfoOffset(DebugInfoOffset(0)), header: from_unit, abbreviations: read::Abbreviations::default(), name: None, comp_dir: None, low_pc: 0, str_offsets_base: DebugStrOffsetsBase(0), addr_base: DebugAddrBase(0), loclists_base: DebugLocListsBase(0), rnglists_base: DebugRngListsBase(0), line_program: None, }; let mut context = convert::ConvertUnitContext { dwarf: &dwarf, unit: &unit, line_strings: &mut line_strings, strings: &mut strings, ranges: &mut ranges, locations: &mut locations, convert_address: &|address| Some(Address::Constant(address)), base_address: Address::Constant(0), line_program_offset: None, line_program_files: Vec::new(), entry_ids: &HashMap::new(), }; let convert_attr = Attribute::from(&mut context, &read_attr).unwrap().unwrap(); assert_eq!(convert_attr, attr); } } } } } #[test] #[allow(clippy::cyclomatic_complexity)] fn test_unit_ref() { let mut units = UnitTable::default(); let unit_id1 = units.add(Unit::new( Encoding { version: 4, address_size: 8, format: Format::Dwarf32, }, LineProgram::none(), )); assert_eq!(unit_id1, units.id(0)); let unit_id2 = units.add(Unit::new( Encoding { version: 2, address_size: 4, format: Format::Dwarf64, }, LineProgram::none(), )); assert_eq!(unit_id2, units.id(1)); let unit1_child1 = UnitEntryId::new(units.get(unit_id1).base_id, 1); let unit1_child2 = UnitEntryId::new(units.get(unit_id1).base_id, 2); let unit2_child1 = UnitEntryId::new(units.get(unit_id2).base_id, 1); let unit2_child2 = UnitEntryId::new(units.get(unit_id2).base_id, 2); { let unit1 = units.get_mut(unit_id1); let root = unit1.root(); let child_id1 = unit1.add(root, constants::DW_TAG_subprogram); assert_eq!(child_id1, unit1_child1); let child_id2 = unit1.add(root, constants::DW_TAG_subprogram); assert_eq!(child_id2, unit1_child2); { let child1 = unit1.get_mut(child_id1); child1.set(constants::DW_AT_type, AttributeValue::UnitRef(child_id2)); } { let child2 = unit1.get_mut(child_id2); child2.set( constants::DW_AT_type, AttributeValue::DebugInfoRef(Reference::Entry(unit_id2, unit2_child1)), ); } } { let unit2 = units.get_mut(unit_id2); let root = unit2.root(); let child_id1 = unit2.add(root, constants::DW_TAG_subprogram); assert_eq!(child_id1, unit2_child1); let child_id2 = unit2.add(root, constants::DW_TAG_subprogram); assert_eq!(child_id2, unit2_child2); { let child1 = unit2.get_mut(child_id1); child1.set(constants::DW_AT_type, AttributeValue::UnitRef(child_id2)); } { let child2 = unit2.get_mut(child_id2); child2.set( constants::DW_AT_type, AttributeValue::DebugInfoRef(Reference::Entry(unit_id1, unit1_child1)), ); } } let debug_line_str_offsets = DebugLineStrOffsets::none(); let debug_str_offsets = DebugStrOffsets::none(); let mut sections = Sections::new(EndianVec::new(LittleEndian)); let debug_info_offsets = units .write(&mut sections, &debug_line_str_offsets, &debug_str_offsets) .unwrap(); println!("{:?}", sections.debug_info); println!("{:?}", sections.debug_abbrev); let dwarf = read::Dwarf { debug_abbrev: read::DebugAbbrev::new(sections.debug_abbrev.slice(), LittleEndian), debug_info: read::DebugInfo::new(sections.debug_info.slice(), LittleEndian), ..Default::default() }; let mut read_units = dwarf.units(); { let read_unit1 = read_units.next().unwrap().unwrap(); assert_eq!(read_unit1.offset(), debug_info_offsets.unit(unit_id1)); let abbrevs = dwarf.abbreviations(&read_unit1).unwrap(); let mut read_entries = read_unit1.entries(&abbrevs); { let (_, _read_root) = read_entries.next_dfs().unwrap().unwrap(); } { let (_, read_child1) = read_entries.next_dfs().unwrap().unwrap(); let offset = debug_info_offsets .entry(unit_id1, unit1_child2) .to_unit_offset(&read_unit1) .unwrap(); assert_eq!( read_child1.attr_value(constants::DW_AT_type).unwrap(), Some(read::AttributeValue::UnitRef(offset)) ); } { let (_, read_child2) = read_entries.next_dfs().unwrap().unwrap(); let offset = debug_info_offsets.entry(unit_id2, unit2_child1); assert_eq!( read_child2.attr_value(constants::DW_AT_type).unwrap(), Some(read::AttributeValue::DebugInfoRef(offset)) ); } } { let read_unit2 = read_units.next().unwrap().unwrap(); assert_eq!(read_unit2.offset(), debug_info_offsets.unit(unit_id2)); let abbrevs = dwarf.abbreviations(&read_unit2).unwrap(); let mut read_entries = read_unit2.entries(&abbrevs); { let (_, _read_root) = read_entries.next_dfs().unwrap().unwrap(); } { let (_, read_child1) = read_entries.next_dfs().unwrap().unwrap(); let offset = debug_info_offsets .entry(unit_id2, unit2_child2) .to_unit_offset(&read_unit2) .unwrap(); assert_eq!( read_child1.attr_value(constants::DW_AT_type).unwrap(), Some(read::AttributeValue::UnitRef(offset)) ); } { let (_, read_child2) = read_entries.next_dfs().unwrap().unwrap(); let offset = debug_info_offsets.entry(unit_id1, unit1_child1); assert_eq!( read_child2.attr_value(constants::DW_AT_type).unwrap(), Some(read::AttributeValue::DebugInfoRef(offset)) ); } } let mut convert_line_strings = LineStringTable::default(); let mut convert_strings = StringTable::default(); let convert_units = UnitTable::from( &dwarf, &mut convert_line_strings, &mut convert_strings, &|address| Some(Address::Constant(address)), ) .unwrap(); assert_eq!(convert_units.count(), units.count()); for i in 0..convert_units.count() { let unit = units.get(units.id(i)); let convert_unit = convert_units.get(convert_units.id(i)); assert_eq!(convert_unit.version(), unit.version()); assert_eq!(convert_unit.address_size(), unit.address_size()); assert_eq!(convert_unit.format(), unit.format()); assert_eq!(convert_unit.count(), unit.count()); let root = unit.get(unit.root()); let convert_root = convert_unit.get(convert_unit.root()); assert_eq!(convert_root.tag(), root.tag()); for (convert_attr, attr) in convert_root.attrs().zip(root.attrs()) { assert_eq!(convert_attr, attr); } let child1 = unit.get(UnitEntryId::new(unit.base_id, 1)); let convert_child1 = convert_unit.get(UnitEntryId::new(convert_unit.base_id, 1)); assert_eq!(convert_child1.tag(), child1.tag()); for (convert_attr, attr) in convert_child1.attrs().zip(child1.attrs()) { assert_eq!(convert_attr.name, attr.name); match (convert_attr.value.clone(), attr.value.clone()) { ( AttributeValue::DebugInfoRef(Reference::Entry(convert_unit, convert_entry)), AttributeValue::DebugInfoRef(Reference::Entry(unit, entry)), ) => { assert_eq!(convert_unit.index, unit.index); assert_eq!(convert_entry.index, entry.index); } (AttributeValue::UnitRef(convert_id), AttributeValue::UnitRef(id)) => { assert_eq!(convert_id.index, id.index); } (convert_value, value) => assert_eq!(convert_value, value), } } let child2 = unit.get(UnitEntryId::new(unit.base_id, 2)); let convert_child2 = convert_unit.get(UnitEntryId::new(convert_unit.base_id, 2)); assert_eq!(convert_child2.tag(), child2.tag()); for (convert_attr, attr) in convert_child2.attrs().zip(child2.attrs()) { assert_eq!(convert_attr.name, attr.name); match (convert_attr.value.clone(), attr.value.clone()) { ( AttributeValue::DebugInfoRef(Reference::Entry(convert_unit, convert_entry)), AttributeValue::DebugInfoRef(Reference::Entry(unit, entry)), ) => { assert_eq!(convert_unit.index, unit.index); assert_eq!(convert_entry.index, entry.index); } (AttributeValue::UnitRef(convert_id), AttributeValue::UnitRef(id)) => { assert_eq!(convert_id.index, id.index); } (convert_value, value) => assert_eq!(convert_value, value), } } } } #[test] fn test_sibling() { fn add_child( unit: &mut Unit, parent: UnitEntryId, tag: constants::DwTag, name: &str, ) -> UnitEntryId { let id = unit.add(parent, tag); let child = unit.get_mut(id); child.set(constants::DW_AT_name, AttributeValue::String(name.into())); child.set_sibling(true); id } fn add_children(units: &mut UnitTable, unit_id: UnitId) { let unit = units.get_mut(unit_id); let root = unit.root(); let child1 = add_child(unit, root, constants::DW_TAG_subprogram, "child1"); add_child(unit, child1, constants::DW_TAG_variable, "grandchild1"); add_child(unit, root, constants::DW_TAG_subprogram, "child2"); add_child(unit, root, constants::DW_TAG_subprogram, "child3"); } fn next_child<R: read::Reader<Offset = usize>>( entries: &mut read::EntriesCursor<R>, ) -> (read::UnitOffset, Option<read::UnitOffset>) { let (_, entry) = entries.next_dfs().unwrap().unwrap(); let offset = entry.offset(); let sibling = entry .attr_value(constants::DW_AT_sibling) .unwrap() .map(|attr| match attr { read::AttributeValue::UnitRef(offset) => offset, _ => panic!("bad sibling value"), }); (offset, sibling) } fn check_sibling<R: read::Reader<Offset = usize>>( unit: &read::CompilationUnitHeader<R>, debug_abbrev: &read::DebugAbbrev<R>, ) { let abbrevs = unit.abbreviations(debug_abbrev).unwrap(); let mut entries = unit.entries(&abbrevs); // root entries.next_dfs().unwrap().unwrap(); // child1 let (_, sibling1) = next_child(&mut entries); // grandchild1 entries.next_dfs().unwrap().unwrap(); // child2 let (offset2, sibling2) = next_child(&mut entries); // child3 let (_, _) = next_child(&mut entries); assert_eq!(sibling1, Some(offset2)); assert_eq!(sibling2, None); } let encoding = Encoding { format: Format::Dwarf32, version: 4, address_size: 8, }; let mut units = UnitTable::default(); let unit_id1 = units.add(Unit::new(encoding, LineProgram::none())); add_children(&mut units, unit_id1); let unit_id2 = units.add(Unit::new(encoding, LineProgram::none())); add_children(&mut units, unit_id2); let debug_line_str_offsets = DebugLineStrOffsets::none(); let debug_str_offsets = DebugStrOffsets::none(); let mut sections = Sections::new(EndianVec::new(LittleEndian)); units .write(&mut sections, &debug_line_str_offsets, &debug_str_offsets) .unwrap(); println!("{:?}", sections.debug_info); println!("{:?}", sections.debug_abbrev); let read_debug_info = read::DebugInfo::new(sections.debug_info.slice(), LittleEndian); let read_debug_abbrev = read::DebugAbbrev::new(sections.debug_abbrev.slice(), LittleEndian); let mut read_units = read_debug_info.units(); check_sibling(&read_units.next().unwrap().unwrap(), &read_debug_abbrev); check_sibling(&read_units.next().unwrap().unwrap(), &read_debug_abbrev); } #[test] fn test_line_ref() { for &version in &[2, 3, 4, 5] { for &address_size in &[4, 8] { for &format in &[Format::Dwarf32, Format::Dwarf64] { let encoding = Encoding { format, version, address_size, }; // The line program we'll be referencing. let mut line_program = LineProgram::new( encoding, LineEncoding::default(), LineString::String(b"comp_dir".to_vec()), LineString::String(b"comp_name".to_vec()), None, ); let dir = line_program.default_directory(); let file1 = line_program.add_file(LineString::String(b"file1".to_vec()), dir, None); let file2 = line_program.add_file(LineString::String(b"file2".to_vec()), dir, None); // Write, read, and convert the line program, so that we have the info // required to convert the attributes. let line_strings = DebugLineStrOffsets::none(); let strings = DebugStrOffsets::none(); let mut debug_line = DebugLine::from(EndianVec::new(LittleEndian)); let line_program_offset = line_program .write(&mut debug_line, encoding, &line_strings, &strings) .unwrap(); let read_debug_line = read::DebugLine::new(debug_line.slice(), LittleEndian); let read_line_program = read_debug_line .program( line_program_offset, address_size, Some(read::EndianSlice::new(b"comp_dir", LittleEndian)), Some(read::EndianSlice::new(b"comp_name", LittleEndian)), ) .unwrap(); let dwarf = read::Dwarf::default(); let mut convert_line_strings = LineStringTable::default(); let mut convert_strings = StringTable::default(); let (_, line_program_files) = LineProgram::from( read_line_program, &dwarf, &mut convert_line_strings, &mut convert_strings, &|address| Some(Address::Constant(address)), ) .unwrap(); // Fake the unit. let mut units = UnitTable::default(); let unit = units.add(Unit::new(encoding, LineProgram::none())); let unit = units.get(unit); let from_unit = read::UnitHeader::new( encoding, 0, DebugAbbrevOffset(0), read::EndianSlice::new(&[], LittleEndian), ); for &(ref name, ref value, ref expect_value) in &[ ( constants::DW_AT_stmt_list, AttributeValue::LineProgramRef, read::AttributeValue::SecOffset(line_program_offset.0), ), ( constants::DW_AT_decl_file, AttributeValue::FileIndex(Some(file1)), read::AttributeValue::Udata(file1.raw()), ), ( constants::DW_AT_decl_file, AttributeValue::FileIndex(Some(file2)), read::AttributeValue::Udata(file2.raw()), ), ][..] { let mut ranges = RangeListTable::default(); let mut locations = LocationListTable::default(); let mut strings = StringTable::default(); let mut line_strings = LineStringTable::default(); let form = value.form(encoding).unwrap(); let attr = Attribute { name: *name, value: value.clone(), }; let mut debug_info_refs = Vec::new(); let mut unit_refs = Vec::new(); let mut debug_info = DebugInfo::from(EndianVec::new(LittleEndian)); let offsets = UnitOffsets::none(); let debug_line_str_offsets = DebugLineStrOffsets::none(); let debug_str_offsets = DebugStrOffsets::none(); let range_list_offsets = RangeListOffsets::none(); let loc_list_offsets = LocationListOffsets::none(); attr.value .write( &mut debug_info, &mut debug_info_refs, &mut unit_refs, &unit, &offsets, Some(line_program_offset), &debug_line_str_offsets, &debug_str_offsets, &range_list_offsets, &loc_list_offsets, ) .unwrap(); let spec = read::AttributeSpecification::new(*name, form, None); let mut r = read::EndianSlice::new(debug_info.slice(), LittleEndian); let read_attr = read::parse_attribute(&mut r, encoding, spec).unwrap(); let read_value = &read_attr.raw_value(); // read::AttributeValue is invariant in the lifetime of R. // The lifetimes here are all okay, so transmute it. let read_value = unsafe { mem::transmute::< &read::AttributeValue<read::EndianSlice<LittleEndian>>, &read::AttributeValue<read::EndianSlice<LittleEndian>>, >(read_value) }; assert_eq!(read_value, expect_value); let unit = read::Unit { offset: UnitSectionOffset::DebugInfoOffset(DebugInfoOffset(0)), header: from_unit, abbreviations: read::Abbreviations::default(), name: None, comp_dir: None, low_pc: 0, str_offsets_base: DebugStrOffsetsBase(0), addr_base: DebugAddrBase(0), loclists_base: DebugLocListsBase(0), rnglists_base: DebugRngListsBase(0), line_program: None, }; let mut context = convert::ConvertUnitContext { dwarf: &dwarf, unit: &unit, line_strings: &mut line_strings, strings: &mut strings, ranges: &mut ranges, locations: &mut locations, convert_address: &|address| Some(Address::Constant(address)), base_address: Address::Constant(0), line_program_offset: Some(line_program_offset), line_program_files: line_program_files.clone(), entry_ids: &HashMap::new(), }; let convert_attr = Attribute::from(&mut context, &read_attr).unwrap().unwrap(); assert_eq!(convert_attr, attr); } } } } } #[test] fn test_line_program_used() { for used in vec![false, true] { let encoding = Encoding { format: Format::Dwarf32, version: 5, address_size: 8, }; let line_program = LineProgram::new( encoding, LineEncoding::default(), LineString::String(b"comp_dir".to_vec()), LineString::String(b"comp_name".to_vec()), None, ); let mut unit = Unit::new(encoding, line_program); let file_id = if used { Some(FileId::new(0)) } else { None }; let root = unit.root(); unit.get_mut(root).set( constants::DW_AT_decl_file, AttributeValue::FileIndex(file_id), ); let mut units = UnitTable::default(); units.add(unit); let debug_line_str_offsets = DebugLineStrOffsets::none(); let debug_str_offsets = DebugStrOffsets::none(); let mut sections = Sections::new(EndianVec::new(LittleEndian)); units .write(&mut sections, &debug_line_str_offsets, &debug_str_offsets) .unwrap(); assert_eq!(!used, sections.debug_line.slice().is_empty()); } } }
{ self.sibling }