code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
#include "muscle.h" #include "enumopts.h" #define s(t) EnumOpt t##_Opts[] = { #define c(t, x) #x, t##_##x, #define e(t) 0, 0 }; #include "enums.h"
mfursov/ugene
src/plugins_3rdparty/umuscle/src/muscle/enumopts.cpp
C++
gpl-2.0
152
<?php /** * @file * @brief sigplus Image Gallery Plus global and local parameters * @author Levente Hunyadi * @version 1.4.2 * @remarks Copyright (C) 2009-2011 Levente Hunyadi * @remarks Licensed under GNU/GPLv3, see http://www.gnu.org/licenses/gpl-3.0.html * @see http://hunyadi.info.hu/projects/sigplus */ /* * sigplus Image Gallery Plus plug-in for Joomla * Copyright 2009-2010 Levente Hunyadi * * sigplus 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. * * sigplus 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/>. */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); require_once dirname(__FILE__).DS.'constants.php'; // sort order for file system functions define('SIGPLUS_SORT_ASCENDING', SORT_ASC); define('SIGPLUS_SORT_DESCENDING', SORT_DESC); // sort criterion override modes define('SIGPLUS_SORT_LABELS_OR_FILENAME', 0); // sort based on labels file with fallback to file name define('SIGPLUS_SORT_LABELS_OR_MTIME', 1); // sort based on labels file with fallback to last modified time define('SIGPLUS_SORT_FILENAME', 2); // sort based on file name ignoring order in labels file define('SIGPLUS_SORT_MTIME', 3); // sort based on last modified time ignoring order in labels file define('SIGPLUS_SORT_RANDOM', 4); // random order define('SIGPLUS_SORT_RANDOMLABELS', 5); // random order restricting images to those listed in labels file /** * Converts a string containing key-value pairs into an associative array. * @param string $string The string to split into key-value pairs. * @param string $separator The optional string that separates the key from the value. * @return array An associative array that maps keys to values. */ function string_to_array($string, $separator = '=', $quotechars = array("'",'"')) { $separator = preg_quote($separator); if (is_array($quotechars)) { $quotedvalue = ''; foreach ($quotechars as $quotechar) { $quotechar = preg_quote($quotechar[0]); // escape characters with special meaning to regex $quotedvalue .= $quotechar.'[^'.$quotechar.']*'.$quotechar.'|'; } } else { $quotechar = preg_quote($quotechar[0]); // make sure quote character is a single character $quotedvalue = $quotechar.'[^'.$quotechar.']*'.$quotechar.'|'; } $regularchar = '[A-Za-z0-9_.:/-]'; $namepattern = '([A-Za-z_]'.$regularchar.'*)'; // html attribute name $valuepattern = '('.$quotedvalue.'-?[0-9]+(?:[.][0-9]+)?|'.$regularchar.'+)'; $pattern = '#(?:'.$namepattern.$separator.')?'.$valuepattern.'#'; $array = array(); $matches = array(); $result = preg_match_all($pattern, $string, $matches, PREG_SET_ORDER); if (!$result) { return false; } foreach ($matches as $match) { $name = $match[1]; $value = trim($match[2], implode('', $quotechars)); if (strlen($name) > 0) { $array[$name] = $value; } else { $array[] = $value; } } return $array; } function as_nonnegative_integer($value) { if (is_null($value) || $value === '') { return false; } elseif ($value !== false) { $value = (int) $value; if ($value <= 0) { $value = 0; } } return $value; } define('SIGPLUS_THUMB_MAXSIZE', 60); class SIGPlusPreviewParameters { /** Width of preview/thumbnail image (px). */ public $width = 100; /** Height of preview/thumbnail image (px). */ public $height = 100; /** Whether the original images was cropped when the preview/thumbnail was generated. */ public $crop = true; /** JPEG quality measure. */ public $quality = 85; function __construct(SIGPlusGalleryParameters $params = null) { if ($params) { $this->width = $params->width; $this->height = $params->height; $this->crop = $params->crop; $this->quality = $params->quality; } } /** * Whether a gallery requires separate thumbnail and preview image sets. */ public function isThumbnailRequired() { return $this->width > SIGPLUS_THUMB_MAXSIZE || $this->height > SIGPLUS_THUMB_MAXSIZE; } /** * Returns thumbnail parameters, reducing image dimensions as necessary. */ public function getThumbnailParameters() { if ($this->isThumbnailRequired()) { $ratio = ($this->width >= $this->height ? $this->width : $this->height) / SIGPLUS_THUMB_MAXSIZE; $thumbparams = clone $this; $thumbparams->width = (int)($thumbparams->width / $ratio); $thumbparams->height = (int)($thumbparams->height / $ratio); return $thumbparams; } else { return $this; } } } /** * Parameter values for images galleries. * Global values are defined in the administration back-end, which are overridden in-place with local parameter values. */ class SIGPlusGalleryParameters { /** The JavaScript lightbox engine to use, false to disable the lightbox engine, or null for default. */ public $lightbox = null; /** The JavaScript image slider engine to use, false to disable the slider engine, or null for default. */ public $slider = null; /** The JavaScript captions engine to use, false to disable the captions engine, or null for default. */ public $captions = null; /** Unique identifier to use for gallery. */ public $id = false; /** The way the gallery is rendered in HTML. */ public $layout = 'fixed'; /** * Number of preview images to display at once without scrolling. * A value of 0 displays all preview images without navigation controls. * Negative values force displaying the set number of images, regardless of the actual number * of images in the gallery. * This parameter is deprecated as of sigplus version 1.3.0. */ public $count = false; /** Number of rows per slider page. */ public $rows = false; /** Number of columns per slider page. */ public $cols = false; /** Maximum number of preview images to show in the gallery. */ public $maxcount = 0; /** Width of preview images [px]. */ public $width = 100; /** Height of preview images [px]. */ public $height = 100; /** Whether to allow cropping images for more aesthetic thumbnails. */ public $crop = true; /** JPEG quality. */ public $quality = 85; /** Alignment of image gallery. */ public $alignment = 'before'; /** Time an image is shown before navigating to the next in a slideshow. */ public $slideshow = 0; /** Orientation of image gallery viewport. */ public $orientation = 'horizontal'; /** Position of navigation bar. */ public $navigation = 'bottom'; /** Show control buttons in navigation bar. */ public $buttons = true; /** Show control links in navigation bar. */ public $links = true; /** Show page counter in navigation bar. */ public $counter = true; /** Show overlay paging controls. */ public $overlay = false; /** Time taken for the slider to move from one page to another [ms]. */ public $duration = 800; /** Animation delay. */ public $animation = 0; /** Position of image captions. */ public $imagecaptions = 'overlay'; /** Labels file name. */ public $labels = 'labels'; /** Default title to assign to images. */ public $deftitle = false; /** Default description to assign to images. */ public $defdescription = false; /** Show icon to download original image. */ public $download = false; /** Show icon to display metadata information. */ public $metadata = false; /** Margin [px], or false for default (inherit from sigplus.css). */ public $margin = false; /** Border width [px], or false for default (inherit from sigplus.css). */ public $borderwidth = false; /** Border style, or false for default (inherit from sigplus.css). */ public $borderstyle = false; /** Border color as a hexadecimal value in between 000000 or ffffff inclusive, or false for default. */ public $bordercolor = false; /** Padding [px], or false for default (inherit from sigplus.css). */ public $padding = false; /** Sort criterion. */ public $sortcriterion = SIGPLUS_SORT_LABELS_OR_FILENAME; /** Sort order, ascending or descending. */ public $sortorder = SIGPLUS_SORT_ASCENDING; /** Depth limit for scanning directory hierarchies recursively. Use -1 to set no recursion limit. */ public $depth = 0; /** How to link gallery to document. */ public $linkage = 'inline'; /** Whether to require Joomla authentication to view images. */ public $authentication = false; /** Whether to create watermarked images. */ public $watermark = false; /** Whether to use progressive loading. */ public $progressive = true; /** Unique identifier of the gallery to link to. */ public $link = false; /** One-based index of representative image in the gallery. */ public $index = 1; /** Custom settings. */ public $settings = false; public $lightbox_params = array(); public $slider_params = array(); public $captions_params = array(); public $watermark_params = array(); public function __set($name, $value) { // ignore unrecognized name/value pairs } /** * True if the parameters involve a random element. * Galleries with a random element cannot be cached. */ public function hasRandom() { return $this->sortcriterion == SIGPLUS_SORT_RANDOM || $this->sortcriterion == SIGPLUS_SORT_RANDOMLABELS; } private function getDefaultSlider() { return 'boxplus.slider'; } /** * Enforces that parameters are of the valid type and value. */ private function validate() { if (is_string($this->settings)) { $params = string_to_array($this->settings); $this->settings = false; if ($params !== false) { $this->setValues($params); } } // get engines to use if (isset($this->lightbox)) { switch ($this->lightbox) { case false: case 'none': $this->lightbox = false; break; case 'default': $this->lightbox = null; break; } } if (isset($this->slider)) { switch ($this->slider) { case false: case 'none': $this->slider = false; break; case 'default': $this->slider = null; break; } } if (isset($this->captions)) { switch ($this->captions) { case false: case 'none': $this->captions = false; break; case 'default': $this->captions = null; break; } } // gallery layout, desired thumbnail count, dimensions and other thumbnail properties switch ($this->layout) { case 'hidden': $this->captions = false; // fall through case 'flow': $this->slider = false; $this->rows = false; $this->cols = false; break; default: // case 'fixed': $this->layout = 'fixed'; $this->rows = as_nonnegative_integer($this->rows); if ($this->rows < 1) { $this->rows = 1; } $this->cols = as_nonnegative_integer($this->cols); if ($this->cols < 1) { $this->cols = 1; } } $language = JFactory::getLanguage(); $this->alignment = str_replace(array('lang','langinv'), array('before','after'), $this->alignment); // compatibility switch ($this->alignment) { case 'before': // 'left' (LTR) or 'right' (RTL) depending on language case 'after': // 'right' (LTR) or 'left' (RTL) depending on language case 'before-clear': case 'after-clear': case 'before-float': case 'after-float': case 'center': case 'left': case 'right': // 'left' or 'right' independent of language case 'left-clear': case 'right-clear': case 'left-float': case 'right-float': break; default: $this->alignment = 'before'; } $this->maxcount = as_nonnegative_integer($this->maxcount); $this->width = (int) $this->width; if ($this->width <= 0) { $this->width = 200; } $this->height = (int) $this->height; if ($this->height <= 0) { $this->height = 200; } if ($this->crop) { $this->crop = true; } else { $this->crop = false; } $this->quality = (int) $this->quality; if ($this->quality < 0) { $this->quality = 0; } if ($this->quality > 100) { $this->quality = 100; } // lightbox properties $this->slideshow = (int) $this->slideshow; if ($this->slideshow < 0) { $this->slideshow = 0; } // image slider alignment, navigation bar positioning, and navigation control settings switch ($this->orientation) { case 'horizontal': case 'vertical': break; default: $this->orientation = 'horizontal'; } switch ($this->navigation) { case 'top': case 'bottom': case 'both': break; default: $this->navigation = 'bottom'; } $this->buttons = (bool) $this->buttons; $this->links = (bool) $this->links; $this->counter = (bool) $this->counter; $this->overlay = (bool) $this->overlay; // miscellaneous visual clues for the image slider $this->duration = as_nonnegative_integer($this->duration); $this->animation = as_nonnegative_integer($this->animation); // image labeling switch ($this->imagecaptions) { case 'above': case 'below': case 'overlay': break; default: $this->imagecaptions = 'overlay'; } $this->labels = preg_replace('/[^A-Za-z0-9_\-]/', '', str_replace('.', '_', $this->labels)); $this->download = (bool) $this->download; $this->metadata = (bool) $this->metadata; // image styling $this->margin = as_nonnegative_integer($this->margin); $this->borderwidth = as_nonnegative_integer($this->borderwidth); switch ($this->borderstyle) { case 'none': case 'dotted': case 'dashed': case 'solid': case 'double': case 'groove': case 'ridge': case 'inset': case 'outset': break; default: $this->borderstyle = false; } if (is_null($this->bordercolor) || $this->bordercolor === '' || $this->bordercolor !== false && !preg_match('/^[0-9A-Fa-f]{6}$/', $this->bordercolor)) { $this->bordercolor = false; } $this->padding = as_nonnegative_integer($this->padding); // sort criterion and sort order if (is_numeric($this->sortcriterion)) { $this->sortcriterion = (int) $this->sortcriterion; } else { switch ($this->sortcriterion) { case 'labels': case 'labels-filename': case 'labels-fname': $this->sortcriterion = SIGPLUS_SORT_LABELS_OR_FILENAME; break; case 'labels-mtime': $this->sortcriterion = SIGPLUS_SORT_LABELS_OR_MTIME; break; case 'filename': case 'fname': $this->sortcriterion = SIGPLUS_SORT_FILENAME; break; case 'mtime': $this->sortcriterion = SIGPLUS_SORT_MTIME; break; case 'random': $this->sortcriterion = SIGPLUS_SORT_RANDOM; break; case 'randomlabels': $this->sortcriterion = SIGPLUS_SORT_RANDOMLABELS; break; default: $this->sortcriterion = SIGPLUS_SORT_LABELS_OR_FILENAME; } } if (is_numeric($this->sortorder)) { $this->sortorder = (int) $this->sortorder; } else { switch ($this->sortorder) { case 'asc': case 'ascending': $this->sortorder = SIGPLUS_SORT_ASCENDING; break; case 'desc': case 'descending': $this->sortorder = SIGPLUS_SORT_DESCENDING; break; default: $this->sortorder = SIGPLUS_SORT_ASCENDING; } } $this->depth = (int) $this->depth; if ($this->depth < -1) { // -1 for recursive listing with no limit, 0 for flat listing (no subdirectories), >0 for recursive listing with limit $this->depth = 0; } // miscellaneous advanced settings switch ($this->linkage) { case 'inline': case 'head': case 'external': break; default: $this->linkage = 'inline'; } $this->authentication = (bool) $this->authentication; $this->watermark = (bool) $this->watermark; $this->progressive = (bool) $this->progressive; $this->index = as_nonnegative_integer($this->index); // deprecated parameters if ($this->count !== false) { $this->count = (int) $this->count; if ($this->count < 0) { // disable slider and set maximum number of thumbnails to show $this->maxcount = -$this->count; $this->rows = 1; $this->cols = $this->maxcount; } elseif ($this->count > 0) { // set rows and columns automatically switch ($this->orientation) { case 'vertical': $this->rows = $this->count; $this->cols = 1; break; default: // case 'horizontal': $this->rows = 1; $this->cols = $this->count; } } elseif ($this->layout != 'hidden') { $this->layout = 'flow'; $this->rows = false; $this->cols = false; $this->slider = false; } $this->count = false; } // resolve parameter incompatibilities if ($this->layout == 'fixed' && !$this->slider) { // fixed layout requires slider $this->slider = $this->getDefaultSlider(); $this->buttons = false; $this->links = false; $this->counter = false; } } /** * Set parameters based on Joomla JRegistry object. */ public function setParameters(JRegistry $params) { $substitute = array( // class property aliases in XML 'maxcount' => 'thumb_count', 'width' => 'thumb_width', 'height' => 'thumb_height', 'crop' => 'thumb_crop', 'quality' => 'thumb_quality', 'slideshow' => 'lightbox_slideshow', 'orientation' => 'slider_orientation', 'navigation' => 'slider_navigation', 'buttons' => 'slider_buttons', 'links' => 'slider_links', 'counter' => 'slider_counter', 'overlay' => 'slider_overlay', 'duration' => 'slider_duration', 'animation' => 'slider_animation', 'deftitle' => 'caption_title', 'defdescription' => 'caption_description', 'borderwidth' => 'border_width', 'borderstyle' => 'border_style', 'bordercolor' => 'border_color', 'sortcriterion' => 'sort_criterion', 'sortorder' => 'sort_order', // class properties to skip 'id' => false, 'lightbox_params' => false, 'slider_params' => false, 'captions_params' => false, 'watermark_params' => false); foreach (get_class_vars(__CLASS__) as $name => $value) { // enumerate properties in class if (isset($substitute[$name])) { $alias = $substitute[$name]; if ($alias !== false) { $this->$name = $params->get($alias, $value); } } else { $this->$name = $params->get($name, $value); // set property class value as default if not present in XML } } $this->validate(); } /** * Return the natural typed representation of a value, guessing at its type. */ private function getValue($value) { if (ctype_digit($value)) { // digits only, treat as integer return (int) $value; } elseif (is_numeric($value)) { // can represent a number, treat as floating-point return (float) $value; } else { switch (strtolower($value)) { // check for boolean values case 'true': return true; case 'false': return false; case 'null': return null; } return $value; } } private function setValues(array $params) { foreach ($params as $key => $value) { if (ctype_alpha($key)) { // ignore keys that are not valid PHP identifiers $this->$key = $value; } elseif (strpos($key, ':') !== false) { // contains special instruction for pop-up window, slider or captions engine list($engine, $key) = explode(':', $key, 2); switch ($engine) { case 'lightbox': $this->lightbox_params[$key] = $this->getValue($value); break; case 'slider': $this->slider_params[$key] = $this->getValue($value); break; case 'captions': $this->captions_params[$key] = $this->getValue($value); break; case 'watermark': $this->watermark_params[$key] = $this->getValue($value); break; } } } } public function setArray(array $params) { $this->setValues($params); $this->validate(); } /** * Set parameters based on a string with whitespace-delimited "key=value" pairs. */ public function setString($paramstring) { $params = string_to_array($paramstring); if ($params !== false) { $this->setArray($params); } } }
sahebkanodia/HostelWebsite
plugins/content/sigplus/params.php
PHP
gpl-2.0
19,862
<?php /** * WARNING: This file is part of the core Genesis framework. DO NOT edit * this file under any circumstances. Please do all modifications * in the form of a child theme. * * Handles the comment structure. * * @package Genesis */ if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && 'comments.php' == basename( $_SERVER['SCRIPT_FILENAME'] ) ) die ( 'Please do not load this page directly. Thanks!' ); if ( post_password_required() ) { printf( '<p class="alert">%s</p>', __( 'This post is password protected. Enter the password to view comments.', 'genesis' ) ); return; } do_action( 'genesis_before_comments' ); do_action( 'genesis_comments' ); do_action( 'genesis_after_comments' ); do_action( 'genesis_before_pings' ); do_action( 'genesis_pings' ); do_action( 'genesis_after_pings' ); do_action( 'genesis_before_comment_form' ); do_action( 'genesis_comment_form' ); do_action( 'genesis_after_comment_form' );
quesada/josequesada.name
wp-content/themes/genesis/comments.php
PHP
gpl-2.0
927
<?php /** * Language Helper for Development Tools Controller * * PHP version 7 * * Copyright (C) Villanova University 2015. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package DevTools * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/indexing:alphabetical_heading_browse Wiki */ namespace VuFindDevTools; use Laminas\I18n\Translator\TextDomain; use VuFind\I18n\Translator\Loader\ExtendedIni; /** * Language Helper for Development Tools Controller * * @category VuFind * @package DevTools * @author Demian Katz <[email protected]> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/indexing:alphabetical_heading_browse Wiki */ class LanguageHelper { /** * Language loader * * @var ExtendedIni */ protected $loader; /** * Configured languages (code => description) * * @var string[] */ protected $configuredLanguages; /** * Constructor * * @param ExtendedIni $loader Language loader * @param array $langs Configured languages (code => description) */ public function __construct(ExtendedIni $loader, array $langs = []) { $this->loader = $loader; $this->configuredLanguages = $langs; } /** * Get a list of help files in the specified language. * * @param string $language Language to check. * * @return array */ protected function getHelpFiles($language) { $dir = APPLICATION_PATH . '/themes/root/templates/HelpTranslations/' . $language; if (!file_exists($dir) || !is_dir($dir)) { return []; } $handle = opendir($dir); $files = []; while ($file = readdir($handle)) { if (substr($file, -6) == '.phtml') { $files[] = $file; } } closedir($handle); return $files; } /** * Get a list of languages supported by VuFind: * * @return array */ protected function getLanguages() { $langs = []; $dir = opendir(APPLICATION_PATH . '/languages'); while ($file = readdir($dir)) { if (substr($file, -4) == '.ini') { $lang = current(explode('.', $file)); if ('native' != $lang) { $langs[] = $lang; } } } closedir($dir); return $langs; } /** * Find strings that are absent from a language file. * * @param TextDomain $lang1 Left side of comparison * @param TextDomain $lang2 Right side of comparison * * @return array */ protected function findMissingLanguageStrings($lang1, $lang2) { // Find strings missing from language 2: return array_values( array_diff(array_keys((array)$lang1), array_keys((array)$lang2)) ); } /** * Compare two languages and return an array of details about how they differ. * * @param TextDomain $lang1 Left side of comparison * @param TextDomain $lang2 Right side of comparison * * @return array */ public function compareLanguages($lang1, $lang2) { return [ 'notInL1' => $this->findMissingLanguageStrings($lang2, $lang1), 'notInL2' => $this->findMissingLanguageStrings($lang1, $lang2), 'l1Percent' => number_format(count($lang1) / count($lang2) * 100, 2), 'l2Percent' => number_format(count($lang2) / count($lang1) * 100, 2), ]; } /** * Get English name of language * * @param string $lang Language code * * @return string */ public function getLangName($lang) { if (isset($this->configuredLanguages[$lang])) { return $this->configuredLanguages[$lang]; } switch ($lang) { case 'en-gb': return 'British English'; case 'pt-br': return 'Brazilian Portuguese'; default: return $lang; } } /** * Get text domains for a language. * * @return array */ protected function getTextDomains() { static $domains = false; if (!$domains) { $base = APPLICATION_PATH . '/languages'; $dir = opendir($base); $domains = []; while ($current = readdir($dir)) { if ($current != '.' && $current != '..' && is_dir("$base/$current") ) { $domains[] = $current; } } closedir($dir); } return $domains; } /** * Load a language, including text domains. * * @param string $lang Language to load * * @return array */ protected function loadLanguage($lang) { $base = $this->loader->load($lang, null); foreach ($this->getTextDomains() as $domain) { $current = $this->loader->load($lang, $domain); foreach ($current as $k => $v) { if ($k != '@parent_ini') { $base["$domain::$k"] = $v; } } } if (isset($base['@parent_ini'])) { // don't count macros in comparison: unset($base['@parent_ini']); } return $base; } /** * Return details on how $langCode differs from $main. * * @param array $main The main language (full details) * @param string $langCode The code of a language to compare against $main * * @return array */ protected function getLanguageDetails($main, $langCode) { $lang = $this->loadLanguage($langCode); $details = $this->compareLanguages($main, $lang); $details['object'] = $lang; $details['name'] = $this->getLangName($langCode); $details['helpFiles'] = $this->getHelpFiles($langCode); return $details; } /** * Return details on how all languages differ from $main. * * @param array $main The main language (full details) * * @return array */ protected function getAllLanguageDetails($main) { $details = []; $allLangs = $this->getLanguages(); sort($allLangs); foreach ($allLangs as $langCode) { $details[$langCode] = $this->getLanguageDetails($main, $langCode); } return $details; } /** * Return language comparison information, using $mainLanguage as the * baseline. * * @param string $mainLanguage Language code * * @return array */ public function getAllDetails($mainLanguage) { $main = $this->loadLanguage($mainLanguage); return [ 'details' => $this->getAllLanguageDetails($main), 'mainCode' => $mainLanguage, 'mainName' => $this->getLangName($mainLanguage), 'main' => $main, ]; } }
finc/vufind
module/VuFindDevTools/src/VuFindDevTools/LanguageHelper.php
PHP
gpl-2.0
7,841
/* Theme Name: Inkness Theme URI: http://inkhive.com/product/inkness/ Author: Rohit Tripathi Author URI: http://inkhive.com Description: Inkness is a Responsive theme with 3 Column Grid based homepage layout. This theme is overloaded with plenty of featured, including an amazing reponsive slider, Multiple Page Layouts, Configurable Sidebar Locations, Footer Widgets & Easy to use admin Panel. This theme is upgradable to a pro version to enable more features. .pot file has been provided, so that you can translate theme into any language. Version: 1.0.2.2 License: GNU General Public License License URI: license.txt Text Domain: inkness Domain Path: /languages/ Tags: light, custom-background, two-columns, right-sidebar, responsive-layout, custom-menu, sticky-post, theme-options, threaded-comments, translation-ready, gray, left-sidebar, custom-menu, editor-style, featured-images, full-width-template, sticky-post, theme-options, threaded-comments Inkness is based on Underscores http://underscores.me/, (C) 2012-2013 Automattic, Inc. Inkness WordPress Theme, Copyright 2013 Rohit Tripathi. Inkness WordPress Theme is distributed under the terms of the GNU GPL v3. */ /* =Reset -------------------------------------------------------------- */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border: 0; font-family: inherit; font-size: 100%; font-style: inherit; font-weight: inherit; margin: 0; outline: 0; padding: 0; vertical-align: baseline; } html { font-size: 62.5%; /* Corrects text resizing oddly in IE6/7 when body font-size is set using em units http://clagnut.com/blog/348/#c790 */ overflow-y: scroll; /* Keeps page centred in all browsers regardless of content height */ -webkit-text-size-adjust: 100%; /* Prevents iOS text size adjust after orientation change, without disabling user zoom */ -ms-text-size-adjust: 100%; /* www.456bereastreet.com/archive/201012/controlling_text_size_in_safari_for_ios_without_disabling_user_zoom/ */ } body { word-wrap: break-word; -ms-word-wrap: break-word; } article, aside, details, figcaption, figure, footer, header, main, nav, section { display: block; } ol, ul { list-style: none; } table { /* tables still need 'cellspacing="0"' in the markup */ border-collapse: separate; border-spacing: 0; } caption, th, td { font-weight: normal; text-align: left; } blockquote:before, blockquote:after, q:before, q:after { content: ""; } blockquote, q { quotes: "" ""; } a:focus { outline: thin dotted; } a:hover, a:active { /* Improves readability when focused and also mouse hovered in all browsers people.opera.com/patrickl/experiments/keyboard/test */ outline: 0; } a img { border: 0; } /* =Global ----------------------------------------------- */ body, button, input, select, textarea { color: #404040; font-family: sans-serif; font-size: 16px; font-size: 1.6rem; line-height: 1.5; } /* Headings */ h1, h2, h3, h4, h5, h6 { clear: both; } hr { background-color: #ccc; border: 0; height: 1px; margin-bottom: 1.5em; } /* Text elements */ p { margin-bottom: 1.5em; } ul, ol { margin: 0 0 1.5em 3em; } ul { list-style: disc; } ol { list-style: decimal; } li > ul, li > ol { margin-bottom: 0; margin-left: 1.5em; } dt { font-weight: bold; } dd { margin: 0 1.5em 1.5em; } b, strong { font-weight: bold; } dfn, cite, em, i { font-style: italic; } blockquote { margin: 0 1.5em; } address { margin: 0 0 1.5em; } pre { background: #eee; font-family: "Courier 10 Pitch", Courier, monospace; font-size: 15px; font-size: 1.5rem; line-height: 1.6; margin-bottom: 1.6em; max-width: 100%; overflow: auto; padding: 1.6em; } code, kbd, tt, var { font: 15px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; } abbr, acronym { border-bottom: 1px dotted #666; cursor: help; } mark, ins { background: #fff9c0; text-decoration: none; } sup, sub { font-size: 75%; height: 0; line-height: 0; position: relative; vertical-align: baseline; } sup { bottom: 1ex; } sub { top: .5ex; } small { font-size: 75%; } big { font-size: 125%; } figure { margin: 0; } table { margin: 0 0 1.5em; width: 100%; } th { font-weight: bold; } img { height: auto; /* Make sure images are scaled correctly. */ max-width: 100%; /* Adhere to container width. */ } button, input, select, textarea { font-size: 100%; /* Corrects font size not being inherited in all browsers */ margin: 0; /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ vertical-align: baseline; /* Improves appearance and consistency in all browsers */ *vertical-align: middle; /* Improves appearance and consistency in all browsers */ } button, input { line-height: normal; /* Addresses FF3/4 setting line-height using !important in the UA stylesheet */ } button, html input[type="button"], input[type="reset"], input[type="submit"] { border: 1px solid #ccc; border-color: #ccc #ccc #bbb #ccc; border-radius: 3px; background: #e6e6e6; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.5), inset 0 15px 17px rgba(255, 255, 255, 0.5), inset 0 -5px 12px rgba(0, 0, 0, 0.05); color: rgba(0, 0, 0, .8); cursor: pointer; /* Improves usability and consistency of cursor style between image-type 'input' and others */ -webkit-appearance: button; /* Corrects inability to style clickable 'input' types in iOS */ font-size: 12px; font-size: 1.2rem; line-height: 1; padding: .6em 1em .4em; text-shadow: 0 1px 0 rgba(255, 255, 255, 0.8); } button:hover, html input[type="button"]:hover, input[type="reset"]:hover, input[type="submit"]:hover { border-color: #ccc #bbb #aaa #bbb; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.8), inset 0 15px 17px rgba(255, 255, 255, 0.8), inset 0 -5px 12px rgba(0, 0, 0, 0.02); } button:focus, html input[type="button"]:focus, input[type="reset"]:focus, input[type="submit"]:focus, button:active, html input[type="button"]:active, input[type="reset"]:active, input[type="submit"]:active { border-color: #aaa #bbb #bbb #bbb; box-shadow: inset 0 -1px 0 rgba(255, 255, 255, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.15); } input[type="checkbox"], input[type="radio"] { box-sizing: border-box; /* Addresses box sizing set to content-box in IE8/9 */ padding: 0; /* Addresses excess padding in IE8/9 */ } input[type="search"] { -webkit-appearance: textfield; /* Addresses appearance set to searchfield in S5, Chrome */ -webkit-box-sizing: content-box; /* Addresses box sizing set to border-box in S5, Chrome (include -moz to future-proof) */ -moz-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-webkit-search-decoration { /* Corrects inner padding displayed oddly in S5, Chrome on OSX */ -webkit-appearance: none; } button::-moz-focus-inner, input::-moz-focus-inner { /* Corrects inner padding and border displayed oddly in FF3/4 www.sitepen.com/blog/2008/05/14/the-devils-in-the-details-fixing-dojos-toolbar-buttons/ */ border: 0; padding: 0; } input[type="text"], input[type="email"], input[type="url"], input[type="password"], input[type="search"], textarea { color: #666; border: 1px solid #ccc; border-radius: 3px; } input[type="text"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="password"]:focus, input[type="search"]:focus, textarea:focus { color: #111; } input[type="text"], input[type="email"], input[type="url"], input[type="password"], input[type="search"] { padding: 3px; } textarea { overflow: auto; /* Removes default vertical scrollbar in IE6/7/8/9 */ padding-left: 3px; vertical-align: top; /* Improves readability and alignment in all browsers */ width: 98%; } /* Alignment */ .alignleft { display: inline; float: left; margin-right: 1.5em; } .alignright { display: inline; float: right; margin-left: 1.5em; } .aligncenter { clear: both; display: block; margin: 0 auto; } /* Text meant only for screen readers */ .screen-reader-text { clip: rect(1px, 1px, 1px, 1px); position: absolute !important; } .screen-reader-text:hover, .screen-reader-text:active, .screen-reader-text:focus { background-color: #f1f1f1; border-radius: 3px; box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6); clip: auto !important; color: #21759b; display: block; font-size: 14px; font-weight: bold; height: auto; left: 5px; line-height: normal; padding: 15px 23px 14px; text-decoration: none; top: 5px; width: auto; z-index: 100000; /* Above WP toolbar */ } /* Clearing */ .clear:before, .clear:after, .entry-content:before, .entry-content:after, .comment-content:before, .comment-content:after, .site-header:before, .site-header:after, .site-content:before, .site-content:after, .site-footer:before, .site-footer:after { content: ''; display: table; } .clear:after, .entry-content:after, .comment-content:after, .site-header:after, .site-content:after, .site-footer:after { clear: both; } /* =Content ----------------------------------------------- */ .sticky { } .hentry { margin: 0 0 1.5em; } .byline, .updated { display: none; } .single .byline, .group-blog .byline { display: inline; } .page-content, .entry-content, .entry-summary { margin: 1.5em 0 0; } .page-links { clear: both; margin: 0 0 1.5em; } /* =Asides ----------------------------------------------- */ .blog .format-aside .entry-title, .archive .format-aside .entry-title { display: none; } /* =Media ----------------------------------------------- */ .page-content img.wp-smiley, .entry-content img.wp-smiley, .comment-content img.wp-smiley { border: none; margin-bottom: 0; margin-top: 0; padding: 0; } .wp-caption { border: 1px solid #ccc; margin-bottom: 1.5em; max-width: 100%; } .wp-caption img[class*="wp-image-"] { display: block; margin: 1.2% auto 0; max-width: 98%; } .wp-caption-text { text-align: center; } .wp-caption .wp-caption-text { margin: 0.8075em 0; } .site-main .gallery { margin-bottom: 1.5em; } .gallery-caption { } .site-main .gallery a img { border: none; height: auto; max-width: 90%; } .site-main .gallery dd { margin: 0; } .site-main .gallery-columns-4 .gallery-item { } .site-main .gallery-columns-4 .gallery-item img { } /* Make sure embeds and iframes fit their containers */ embed, iframe, object { max-width: 100%; } /* =Navigation ----------------------------------------------- */ .site-main [class*="navigation"] { margin: 0 0 1.5em; overflow: hidden; } [class*="navigation"] .nav-previous { float: left; width: 50%; } [class*="navigation"] .nav-next { float: right; text-align: right; width: 50%; } /* =Comments ----------------------------------------------- */ .comment-content a { word-wrap: break-word; } .bypostauthor { } /* =Widgets ----------------------------------------------- */ .widget { margin: 0 0 1.5em; } /* Make sure select elements fit in widgets */ .widget select { max-width: 100%; } /* Search widget */ .widget_search .search-submit { display: none; } /* =Infinite Scroll ----------------------------------------------- */ /* Globally hidden elements when Infinite Scroll is supported and in use. */ .infinite-scroll .paging-navigation, /* Older / Newer Posts Navigation (always hidden) */ .infinite-scroll.neverending .site-footer { /* Theme Footer (when set to scrolling) */ display: none; } /* When Infinite Scroll has reached its end we need to re-display elements that were hidden (via .neverending) before */ .infinity-end.neverending .site-footer { display: block; } /* = Fix for equalHeights ----------------------------------------------- */ @media screen and (min-width: 1200px) { .featured-thumb { min-height: 207px !important; overflow: hidden; } } @media screen and (min-width: 992px) and (max-width: 1199px) { .featured-thumb { min-height: 170px !important; overflow: hidden; } }
garydai/wordpress
wp-content/themes/inkness/style.css
CSS
gpl-2.0
12,003
/* * Copyright (C) 2011 LAPIS Semiconductor Co., Ltd. * * 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; version 2 of the License. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/delay.h> #include <linux/errno.h> #include <linux/list.h> #include <linux/interrupt.h> #include <linux/usb/ch9.h> #include <linux/usb/gadget.h> #include <linux/gpio.h> #include <linux/irq.h> /* GPIO port for VBUS detecting */ static int vbus_gpio_port = -1; /* GPIO port number (-1:Not used) */ #define PCH_VBUS_PERIOD 3000 /* VBUS polling period (msec) */ #define PCH_VBUS_INTERVAL 10 /* VBUS polling interval (msec) */ /* Address offset of Registers */ #define UDC_EP_REG_SHIFT 0x20 /* Offset to next EP */ #define UDC_EPCTL_ADDR 0x00 /* Endpoint control */ #define UDC_EPSTS_ADDR 0x04 /* Endpoint status */ #define UDC_BUFIN_FRAMENUM_ADDR 0x08 /* buffer size in / frame number out */ #define UDC_BUFOUT_MAXPKT_ADDR 0x0C /* buffer size out / maxpkt in */ #define UDC_SUBPTR_ADDR 0x10 /* setup buffer pointer */ #define UDC_DESPTR_ADDR 0x14 /* Data descriptor pointer */ #define UDC_CONFIRM_ADDR 0x18 /* Write/Read confirmation */ #define UDC_DEVCFG_ADDR 0x400 /* Device configuration */ #define UDC_DEVCTL_ADDR 0x404 /* Device control */ #define UDC_DEVSTS_ADDR 0x408 /* Device status */ #define UDC_DEVIRQSTS_ADDR 0x40C /* Device irq status */ #define UDC_DEVIRQMSK_ADDR 0x410 /* Device irq mask */ #define UDC_EPIRQSTS_ADDR 0x414 /* Endpoint irq status */ #define UDC_EPIRQMSK_ADDR 0x418 /* Endpoint irq mask */ #define UDC_DEVLPM_ADDR 0x41C /* LPM control / status */ #define UDC_CSR_BUSY_ADDR 0x4f0 /* UDC_CSR_BUSY Status register */ #define UDC_SRST_ADDR 0x4fc /* SOFT RESET register */ #define UDC_CSR_ADDR 0x500 /* USB_DEVICE endpoint register */ /* Endpoint control register */ /* Bit position */ #define UDC_EPCTL_MRXFLUSH (1 << 12) #define UDC_EPCTL_RRDY (1 << 9) #define UDC_EPCTL_CNAK (1 << 8) #define UDC_EPCTL_SNAK (1 << 7) #define UDC_EPCTL_NAK (1 << 6) #define UDC_EPCTL_P (1 << 3) #define UDC_EPCTL_F (1 << 1) #define UDC_EPCTL_S (1 << 0) #define UDC_EPCTL_ET_SHIFT 4 /* Mask patern */ #define UDC_EPCTL_ET_MASK 0x00000030 /* Value for ET field */ #define UDC_EPCTL_ET_CONTROL 0 #define UDC_EPCTL_ET_ISO 1 #define UDC_EPCTL_ET_BULK 2 #define UDC_EPCTL_ET_INTERRUPT 3 /* Endpoint status register */ /* Bit position */ #define UDC_EPSTS_XFERDONE (1 << 27) #define UDC_EPSTS_RSS (1 << 26) #define UDC_EPSTS_RCS (1 << 25) #define UDC_EPSTS_TXEMPTY (1 << 24) #define UDC_EPSTS_TDC (1 << 10) #define UDC_EPSTS_HE (1 << 9) #define UDC_EPSTS_MRXFIFO_EMP (1 << 8) #define UDC_EPSTS_BNA (1 << 7) #define UDC_EPSTS_IN (1 << 6) #define UDC_EPSTS_OUT_SHIFT 4 /* Mask patern */ #define UDC_EPSTS_OUT_MASK 0x00000030 #define UDC_EPSTS_ALL_CLR_MASK 0x1F0006F0 /* Value for OUT field */ #define UDC_EPSTS_OUT_SETUP 2 #define UDC_EPSTS_OUT_DATA 1 /* Device configuration register */ /* Bit position */ #define UDC_DEVCFG_CSR_PRG (1 << 17) #define UDC_DEVCFG_SP (1 << 3) /* SPD Valee */ #define UDC_DEVCFG_SPD_HS 0x0 #define UDC_DEVCFG_SPD_FS 0x1 #define UDC_DEVCFG_SPD_LS 0x2 /* Device control register */ /* Bit position */ #define UDC_DEVCTL_THLEN_SHIFT 24 #define UDC_DEVCTL_BRLEN_SHIFT 16 #define UDC_DEVCTL_CSR_DONE (1 << 13) #define UDC_DEVCTL_SD (1 << 10) #define UDC_DEVCTL_MODE (1 << 9) #define UDC_DEVCTL_BREN (1 << 8) #define UDC_DEVCTL_THE (1 << 7) #define UDC_DEVCTL_DU (1 << 4) #define UDC_DEVCTL_TDE (1 << 3) #define UDC_DEVCTL_RDE (1 << 2) #define UDC_DEVCTL_RES (1 << 0) /* Device status register */ /* Bit position */ #define UDC_DEVSTS_TS_SHIFT 18 #define UDC_DEVSTS_ENUM_SPEED_SHIFT 13 #define UDC_DEVSTS_ALT_SHIFT 8 #define UDC_DEVSTS_INTF_SHIFT 4 #define UDC_DEVSTS_CFG_SHIFT 0 /* Mask patern */ #define UDC_DEVSTS_TS_MASK 0xfffc0000 #define UDC_DEVSTS_ENUM_SPEED_MASK 0x00006000 #define UDC_DEVSTS_ALT_MASK 0x00000f00 #define UDC_DEVSTS_INTF_MASK 0x000000f0 #define UDC_DEVSTS_CFG_MASK 0x0000000f /* value for maximum speed for SPEED field */ #define UDC_DEVSTS_ENUM_SPEED_FULL 1 #define UDC_DEVSTS_ENUM_SPEED_HIGH 0 #define UDC_DEVSTS_ENUM_SPEED_LOW 2 #define UDC_DEVSTS_ENUM_SPEED_FULLX 3 /* Device irq register */ /* Bit position */ #define UDC_DEVINT_RWKP (1 << 7) #define UDC_DEVINT_ENUM (1 << 6) #define UDC_DEVINT_SOF (1 << 5) #define UDC_DEVINT_US (1 << 4) #define UDC_DEVINT_UR (1 << 3) #define UDC_DEVINT_ES (1 << 2) #define UDC_DEVINT_SI (1 << 1) #define UDC_DEVINT_SC (1 << 0) /* Mask patern */ #define UDC_DEVINT_MSK 0x7f /* Endpoint irq register */ /* Bit position */ #define UDC_EPINT_IN_SHIFT 0 #define UDC_EPINT_OUT_SHIFT 16 #define UDC_EPINT_IN_EP0 (1 << 0) #define UDC_EPINT_OUT_EP0 (1 << 16) /* Mask patern */ #define UDC_EPINT_MSK_DISABLE_ALL 0xffffffff /* UDC_CSR_BUSY Status register */ /* Bit position */ #define UDC_CSR_BUSY (1 << 0) /* SOFT RESET register */ /* Bit position */ #define UDC_PSRST (1 << 1) #define UDC_SRST (1 << 0) /* USB_DEVICE endpoint register */ /* Bit position */ #define UDC_CSR_NE_NUM_SHIFT 0 #define UDC_CSR_NE_DIR_SHIFT 4 #define UDC_CSR_NE_TYPE_SHIFT 5 #define UDC_CSR_NE_CFG_SHIFT 7 #define UDC_CSR_NE_INTF_SHIFT 11 #define UDC_CSR_NE_ALT_SHIFT 15 #define UDC_CSR_NE_MAX_PKT_SHIFT 19 /* Mask patern */ #define UDC_CSR_NE_NUM_MASK 0x0000000f #define UDC_CSR_NE_DIR_MASK 0x00000010 #define UDC_CSR_NE_TYPE_MASK 0x00000060 #define UDC_CSR_NE_CFG_MASK 0x00000780 #define UDC_CSR_NE_INTF_MASK 0x00007800 #define UDC_CSR_NE_ALT_MASK 0x00078000 #define UDC_CSR_NE_MAX_PKT_MASK 0x3ff80000 #define PCH_UDC_CSR(ep) (UDC_CSR_ADDR + ep*4) #define PCH_UDC_EPINT(in, num)\ (1 << (num + (in ? UDC_EPINT_IN_SHIFT : UDC_EPINT_OUT_SHIFT))) /* Index of endpoint */ #define UDC_EP0IN_IDX 0 #define UDC_EP0OUT_IDX 1 #define UDC_EPIN_IDX(ep) (ep * 2) #define UDC_EPOUT_IDX(ep) (ep * 2 + 1) #define PCH_UDC_EP0 0 #define PCH_UDC_EP1 1 #define PCH_UDC_EP2 2 #define PCH_UDC_EP3 3 /* Number of endpoint */ #define PCH_UDC_EP_NUM 32 /* Total number of EPs (16 IN,16 OUT) */ #define PCH_UDC_USED_EP_NUM 4 /* EP number of EP's really used */ /* Length Value */ #define PCH_UDC_BRLEN 0x0F /* Burst length */ #define PCH_UDC_THLEN 0x1F /* Threshold length */ /* Value of EP Buffer Size */ #define UDC_EP0IN_BUFF_SIZE 16 #define UDC_EPIN_BUFF_SIZE 256 #define UDC_EP0OUT_BUFF_SIZE 16 #define UDC_EPOUT_BUFF_SIZE 256 /* Value of EP maximum packet size */ #define UDC_EP0IN_MAX_PKT_SIZE 64 #define UDC_EP0OUT_MAX_PKT_SIZE 64 #define UDC_BULK_MAX_PKT_SIZE 512 /* DMA */ #define DMA_DIR_RX 1 /* DMA for data receive */ #define DMA_DIR_TX 2 /* DMA for data transmit */ #define DMA_ADDR_INVALID (~(dma_addr_t)0) #define UDC_DMA_MAXPACKET 65536 /* maximum packet size for DMA */ /** * struct pch_udc_data_dma_desc - Structure to hold DMA descriptor information * for data * @status: Status quadlet * @reserved: Reserved * @dataptr: Buffer descriptor * @next: Next descriptor */ struct pch_udc_data_dma_desc { u32 status; u32 reserved; u32 dataptr; u32 next; }; /** * struct pch_udc_stp_dma_desc - Structure to hold DMA descriptor information * for control data * @status: Status * @reserved: Reserved * @data12: First setup word * @data34: Second setup word */ struct pch_udc_stp_dma_desc { u32 status; u32 reserved; struct usb_ctrlrequest request; } __attribute((packed)); /* DMA status definitions */ /* Buffer status */ #define PCH_UDC_BUFF_STS 0xC0000000 #define PCH_UDC_BS_HST_RDY 0x00000000 #define PCH_UDC_BS_DMA_BSY 0x40000000 #define PCH_UDC_BS_DMA_DONE 0x80000000 #define PCH_UDC_BS_HST_BSY 0xC0000000 /* Rx/Tx Status */ #define PCH_UDC_RXTX_STS 0x30000000 #define PCH_UDC_RTS_SUCC 0x00000000 #define PCH_UDC_RTS_DESERR 0x10000000 #define PCH_UDC_RTS_BUFERR 0x30000000 /* Last Descriptor Indication */ #define PCH_UDC_DMA_LAST 0x08000000 /* Number of Rx/Tx Bytes Mask */ #define PCH_UDC_RXTX_BYTES 0x0000ffff /** * struct pch_udc_cfg_data - Structure to hold current configuration * and interface information * @cur_cfg: current configuration in use * @cur_intf: current interface in use * @cur_alt: current alt interface in use */ struct pch_udc_cfg_data { u16 cur_cfg; u16 cur_intf; u16 cur_alt; }; /** * struct pch_udc_ep - Structure holding a PCH USB device Endpoint information * @ep: embedded ep request * @td_stp_phys: for setup request * @td_data_phys: for data request * @td_stp: for setup request * @td_data: for data request * @dev: reference to device struct * @offset_addr: offset address of ep register * @desc: for this ep * @queue: queue for requests * @num: endpoint number * @in: endpoint is IN * @halted: endpoint halted? * @epsts: Endpoint status */ struct pch_udc_ep { struct usb_ep ep; dma_addr_t td_stp_phys; dma_addr_t td_data_phys; struct pch_udc_stp_dma_desc *td_stp; struct pch_udc_data_dma_desc *td_data; struct pch_udc_dev *dev; unsigned long offset_addr; struct list_head queue; unsigned num:5, in:1, halted:1; unsigned long epsts; }; /** * struct pch_vbus_gpio_data - Structure holding GPIO informaton * for detecting VBUS * @port: gpio port number * @intr: gpio interrupt number * @irq_work_fall Structure for WorkQueue * @irq_work_rise Structure for WorkQueue */ struct pch_vbus_gpio_data { int port; int intr; struct work_struct irq_work_fall; struct work_struct irq_work_rise; }; /** * struct pch_udc_dev - Structure holding complete information * of the PCH USB device * @gadget: gadget driver data * @driver: reference to gadget driver bound * @pdev: reference to the PCI device * @ep: array of endpoints * @lock: protects all state * @active: enabled the PCI device * @stall: stall requested * @prot_stall: protcol stall requested * @irq_registered: irq registered with system * @mem_region: device memory mapped * @registered: driver regsitered with system * @suspended: driver in suspended state * @connected: gadget driver associated * @vbus_session: required vbus_session state * @set_cfg_not_acked: pending acknowledgement 4 setup * @waiting_zlp_ack: pending acknowledgement 4 ZLP * @data_requests: DMA pool for data requests * @stp_requests: DMA pool for setup requests * @dma_addr: DMA pool for received * @ep0out_buf: Buffer for DMA * @setup_data: Received setup data * @phys_addr: of device memory * @base_addr: for mapped device memory * @irq: IRQ line for the device * @cfg_data: current cfg, intf, and alt in use * @vbus_gpio: GPIO informaton for detecting VBUS */ struct pch_udc_dev { struct usb_gadget gadget; struct usb_gadget_driver *driver; struct pci_dev *pdev; struct pch_udc_ep ep[PCH_UDC_EP_NUM]; spinlock_t lock; /* protects all state */ unsigned active:1, stall:1, prot_stall:1, irq_registered:1, mem_region:1, suspended:1, connected:1, vbus_session:1, set_cfg_not_acked:1, waiting_zlp_ack:1; struct pci_pool *data_requests; struct pci_pool *stp_requests; dma_addr_t dma_addr; void *ep0out_buf; struct usb_ctrlrequest setup_data; unsigned long phys_addr; void __iomem *base_addr; unsigned irq; struct pch_udc_cfg_data cfg_data; struct pch_vbus_gpio_data vbus_gpio; }; #define to_pch_udc(g) (container_of((g), struct pch_udc_dev, gadget)) #define PCH_UDC_PCI_BAR 1 #define PCI_DEVICE_ID_INTEL_EG20T_UDC 0x8808 #define PCI_VENDOR_ID_ROHM 0x10DB #define PCI_DEVICE_ID_ML7213_IOH_UDC 0x801D #define PCI_DEVICE_ID_ML7831_IOH_UDC 0x8808 static const char ep0_string[] = "ep0in"; static DEFINE_SPINLOCK(udc_stall_spinlock); /* stall spin lock */ static bool speed_fs; module_param_named(speed_fs, speed_fs, bool, S_IRUGO); MODULE_PARM_DESC(speed_fs, "true for Full speed operation"); /** * struct pch_udc_request - Structure holding a PCH USB device request packet * @req: embedded ep request * @td_data_phys: phys. address * @td_data: first dma desc. of chain * @td_data_last: last dma desc. of chain * @queue: associated queue * @dma_going: DMA in progress for request * @dma_mapped: DMA memory mapped for request * @dma_done: DMA completed for request * @chain_len: chain length * @buf: Buffer memory for align adjustment * @dma: DMA memory for align adjustment */ struct pch_udc_request { struct usb_request req; dma_addr_t td_data_phys; struct pch_udc_data_dma_desc *td_data; struct pch_udc_data_dma_desc *td_data_last; struct list_head queue; unsigned dma_going:1, dma_mapped:1, dma_done:1; unsigned chain_len; void *buf; dma_addr_t dma; }; static inline u32 pch_udc_readl(struct pch_udc_dev *dev, unsigned long reg) { return ioread32(dev->base_addr + reg); } static inline void pch_udc_writel(struct pch_udc_dev *dev, unsigned long val, unsigned long reg) { iowrite32(val, dev->base_addr + reg); } static inline void pch_udc_bit_set(struct pch_udc_dev *dev, unsigned long reg, unsigned long bitmask) { pch_udc_writel(dev, pch_udc_readl(dev, reg) | bitmask, reg); } static inline void pch_udc_bit_clr(struct pch_udc_dev *dev, unsigned long reg, unsigned long bitmask) { pch_udc_writel(dev, pch_udc_readl(dev, reg) & ~(bitmask), reg); } static inline u32 pch_udc_ep_readl(struct pch_udc_ep *ep, unsigned long reg) { return ioread32(ep->dev->base_addr + ep->offset_addr + reg); } static inline void pch_udc_ep_writel(struct pch_udc_ep *ep, unsigned long val, unsigned long reg) { iowrite32(val, ep->dev->base_addr + ep->offset_addr + reg); } static inline void pch_udc_ep_bit_set(struct pch_udc_ep *ep, unsigned long reg, unsigned long bitmask) { pch_udc_ep_writel(ep, pch_udc_ep_readl(ep, reg) | bitmask, reg); } static inline void pch_udc_ep_bit_clr(struct pch_udc_ep *ep, unsigned long reg, unsigned long bitmask) { pch_udc_ep_writel(ep, pch_udc_ep_readl(ep, reg) & ~(bitmask), reg); } /** * pch_udc_csr_busy() - Wait till idle. * @dev: Reference to pch_udc_dev structure */ static void pch_udc_csr_busy(struct pch_udc_dev *dev) { unsigned int count = 200; /* Wait till idle */ while ((pch_udc_readl(dev, UDC_CSR_BUSY_ADDR) & UDC_CSR_BUSY) && --count) cpu_relax(); if (!count) dev_err(&dev->pdev->dev, "%s: wait error\n", __func__); } /** * pch_udc_write_csr() - Write the command and status registers. * @dev: Reference to pch_udc_dev structure * @val: value to be written to CSR register * @addr: address of CSR register */ static void pch_udc_write_csr(struct pch_udc_dev *dev, unsigned long val, unsigned int ep) { unsigned long reg = PCH_UDC_CSR(ep); pch_udc_csr_busy(dev); /* Wait till idle */ pch_udc_writel(dev, val, reg); pch_udc_csr_busy(dev); /* Wait till idle */ } /** * pch_udc_read_csr() - Read the command and status registers. * @dev: Reference to pch_udc_dev structure * @addr: address of CSR register * * Return codes: content of CSR register */ static u32 pch_udc_read_csr(struct pch_udc_dev *dev, unsigned int ep) { unsigned long reg = PCH_UDC_CSR(ep); pch_udc_csr_busy(dev); /* Wait till idle */ pch_udc_readl(dev, reg); /* Dummy read */ pch_udc_csr_busy(dev); /* Wait till idle */ return pch_udc_readl(dev, reg); } /** * pch_udc_rmt_wakeup() - Initiate for remote wakeup * @dev: Reference to pch_udc_dev structure */ static inline void pch_udc_rmt_wakeup(struct pch_udc_dev *dev) { pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); mdelay(1); pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); } /** * pch_udc_get_frame() - Get the current frame from device status register * @dev: Reference to pch_udc_dev structure * Retern current frame */ static inline int pch_udc_get_frame(struct pch_udc_dev *dev) { u32 frame = pch_udc_readl(dev, UDC_DEVSTS_ADDR); return (frame & UDC_DEVSTS_TS_MASK) >> UDC_DEVSTS_TS_SHIFT; } /** * pch_udc_clear_selfpowered() - Clear the self power control * @dev: Reference to pch_udc_regs structure */ static inline void pch_udc_clear_selfpowered(struct pch_udc_dev *dev) { pch_udc_bit_clr(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_SP); } /** * pch_udc_set_selfpowered() - Set the self power control * @dev: Reference to pch_udc_regs structure */ static inline void pch_udc_set_selfpowered(struct pch_udc_dev *dev) { pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_SP); } /** * pch_udc_set_disconnect() - Set the disconnect status. * @dev: Reference to pch_udc_regs structure */ static inline void pch_udc_set_disconnect(struct pch_udc_dev *dev) { pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD); } /** * pch_udc_clear_disconnect() - Clear the disconnect status. * @dev: Reference to pch_udc_regs structure */ static void pch_udc_clear_disconnect(struct pch_udc_dev *dev) { /* Clear the disconnect */ pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD); mdelay(1); /* Resume USB signalling */ pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); } /** * pch_udc_reconnect() - This API initializes usb device controller, * and clear the disconnect status. * @dev: Reference to pch_udc_regs structure */ static void pch_udc_init(struct pch_udc_dev *dev); static void pch_udc_reconnect(struct pch_udc_dev *dev) { pch_udc_init(dev); /* enable device interrupts */ /* pch_udc_enable_interrupts() */ pch_udc_bit_clr(dev, UDC_DEVIRQMSK_ADDR, UDC_DEVINT_UR | UDC_DEVINT_ENUM); /* Clear the disconnect */ pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_SD); mdelay(1); /* Resume USB signalling */ pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RES); } /** * pch_udc_vbus_session() - set or clearr the disconnect status. * @dev: Reference to pch_udc_regs structure * @is_active: Parameter specifying the action * 0: indicating VBUS power is ending * !0: indicating VBUS power is starting */ static inline void pch_udc_vbus_session(struct pch_udc_dev *dev, int is_active) { if (is_active) { pch_udc_reconnect(dev); dev->vbus_session = 1; } else { if (dev->driver && dev->driver->disconnect) { spin_unlock(&dev->lock); dev->driver->disconnect(&dev->gadget); spin_lock(&dev->lock); } pch_udc_set_disconnect(dev); dev->vbus_session = 0; } } /** * pch_udc_ep_set_stall() - Set the stall of endpoint * @ep: Reference to structure of type pch_udc_ep_regs */ static void pch_udc_ep_set_stall(struct pch_udc_ep *ep) { if (ep->in) { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_F); pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S); } else { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S); } } /** * pch_udc_ep_clear_stall() - Clear the stall of endpoint * @ep: Reference to structure of type pch_udc_ep_regs */ static inline void pch_udc_ep_clear_stall(struct pch_udc_ep *ep) { /* Clear the stall */ pch_udc_ep_bit_clr(ep, UDC_EPCTL_ADDR, UDC_EPCTL_S); /* Clear NAK by writing CNAK */ pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_CNAK); } /** * pch_udc_ep_set_trfr_type() - Set the transfer type of endpoint * @ep: Reference to structure of type pch_udc_ep_regs * @type: Type of endpoint */ static inline void pch_udc_ep_set_trfr_type(struct pch_udc_ep *ep, u8 type) { pch_udc_ep_writel(ep, ((type << UDC_EPCTL_ET_SHIFT) & UDC_EPCTL_ET_MASK), UDC_EPCTL_ADDR); } /** * pch_udc_ep_set_bufsz() - Set the maximum packet size for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs * @buf_size: The buffer word size */ static void pch_udc_ep_set_bufsz(struct pch_udc_ep *ep, u32 buf_size, u32 ep_in) { u32 data; if (ep_in) { data = pch_udc_ep_readl(ep, UDC_BUFIN_FRAMENUM_ADDR); data = (data & 0xffff0000) | (buf_size & 0xffff); pch_udc_ep_writel(ep, data, UDC_BUFIN_FRAMENUM_ADDR); } else { data = pch_udc_ep_readl(ep, UDC_BUFOUT_MAXPKT_ADDR); data = (buf_size << 16) | (data & 0xffff); pch_udc_ep_writel(ep, data, UDC_BUFOUT_MAXPKT_ADDR); } } /** * pch_udc_ep_set_maxpkt() - Set the Max packet size for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs * @pkt_size: The packet byte size */ static void pch_udc_ep_set_maxpkt(struct pch_udc_ep *ep, u32 pkt_size) { u32 data = pch_udc_ep_readl(ep, UDC_BUFOUT_MAXPKT_ADDR); data = (data & 0xffff0000) | (pkt_size & 0xffff); pch_udc_ep_writel(ep, data, UDC_BUFOUT_MAXPKT_ADDR); } /** * pch_udc_ep_set_subptr() - Set the Setup buffer pointer for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs * @addr: Address of the register */ static inline void pch_udc_ep_set_subptr(struct pch_udc_ep *ep, u32 addr) { pch_udc_ep_writel(ep, addr, UDC_SUBPTR_ADDR); } /** * pch_udc_ep_set_ddptr() - Set the Data descriptor pointer for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs * @addr: Address of the register */ static inline void pch_udc_ep_set_ddptr(struct pch_udc_ep *ep, u32 addr) { pch_udc_ep_writel(ep, addr, UDC_DESPTR_ADDR); } /** * pch_udc_ep_set_pd() - Set the poll demand bit for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs */ static inline void pch_udc_ep_set_pd(struct pch_udc_ep *ep) { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_P); } /** * pch_udc_ep_set_rrdy() - Set the receive ready bit for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs */ static inline void pch_udc_ep_set_rrdy(struct pch_udc_ep *ep) { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_RRDY); } /** * pch_udc_ep_clear_rrdy() - Clear the receive ready bit for the endpoint * @ep: Reference to structure of type pch_udc_ep_regs */ static inline void pch_udc_ep_clear_rrdy(struct pch_udc_ep *ep) { pch_udc_ep_bit_clr(ep, UDC_EPCTL_ADDR, UDC_EPCTL_RRDY); } /** * pch_udc_set_dma() - Set the 'TDE' or RDE bit of device control * register depending on the direction specified * @dev: Reference to structure of type pch_udc_regs * @dir: whether Tx or Rx * DMA_DIR_RX: Receive * DMA_DIR_TX: Transmit */ static inline void pch_udc_set_dma(struct pch_udc_dev *dev, int dir) { if (dir == DMA_DIR_RX) pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RDE); else if (dir == DMA_DIR_TX) pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_TDE); } /** * pch_udc_clear_dma() - Clear the 'TDE' or RDE bit of device control * register depending on the direction specified * @dev: Reference to structure of type pch_udc_regs * @dir: Whether Tx or Rx * DMA_DIR_RX: Receive * DMA_DIR_TX: Transmit */ static inline void pch_udc_clear_dma(struct pch_udc_dev *dev, int dir) { if (dir == DMA_DIR_RX) pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_RDE); else if (dir == DMA_DIR_TX) pch_udc_bit_clr(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_TDE); } /** * pch_udc_set_csr_done() - Set the device control register * CSR done field (bit 13) * @dev: reference to structure of type pch_udc_regs */ static inline void pch_udc_set_csr_done(struct pch_udc_dev *dev) { pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, UDC_DEVCTL_CSR_DONE); } /** * pch_udc_disable_interrupts() - Disables the specified interrupts * @dev: Reference to structure of type pch_udc_regs * @mask: Mask to disable interrupts */ static inline void pch_udc_disable_interrupts(struct pch_udc_dev *dev, u32 mask) { pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, mask); } /** * pch_udc_enable_interrupts() - Enable the specified interrupts * @dev: Reference to structure of type pch_udc_regs * @mask: Mask to enable interrupts */ static inline void pch_udc_enable_interrupts(struct pch_udc_dev *dev, u32 mask) { pch_udc_bit_clr(dev, UDC_DEVIRQMSK_ADDR, mask); } /** * pch_udc_disable_ep_interrupts() - Disable endpoint interrupts * @dev: Reference to structure of type pch_udc_regs * @mask: Mask to disable interrupts */ static inline void pch_udc_disable_ep_interrupts(struct pch_udc_dev *dev, u32 mask) { pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, mask); } /** * pch_udc_enable_ep_interrupts() - Enable endpoint interrupts * @dev: Reference to structure of type pch_udc_regs * @mask: Mask to enable interrupts */ static inline void pch_udc_enable_ep_interrupts(struct pch_udc_dev *dev, u32 mask) { pch_udc_bit_clr(dev, UDC_EPIRQMSK_ADDR, mask); } /** * pch_udc_read_device_interrupts() - Read the device interrupts * @dev: Reference to structure of type pch_udc_regs * Retern The device interrupts */ static inline u32 pch_udc_read_device_interrupts(struct pch_udc_dev *dev) { return pch_udc_readl(dev, UDC_DEVIRQSTS_ADDR); } /** * pch_udc_write_device_interrupts() - Write device interrupts * @dev: Reference to structure of type pch_udc_regs * @val: The value to be written to interrupt register */ static inline void pch_udc_write_device_interrupts(struct pch_udc_dev *dev, u32 val) { pch_udc_writel(dev, val, UDC_DEVIRQSTS_ADDR); } /** * pch_udc_read_ep_interrupts() - Read the endpoint interrupts * @dev: Reference to structure of type pch_udc_regs * Retern The endpoint interrupt */ static inline u32 pch_udc_read_ep_interrupts(struct pch_udc_dev *dev) { return pch_udc_readl(dev, UDC_EPIRQSTS_ADDR); } /** * pch_udc_write_ep_interrupts() - Clear endpoint interupts * @dev: Reference to structure of type pch_udc_regs * @val: The value to be written to interrupt register */ static inline void pch_udc_write_ep_interrupts(struct pch_udc_dev *dev, u32 val) { pch_udc_writel(dev, val, UDC_EPIRQSTS_ADDR); } /** * pch_udc_read_device_status() - Read the device status * @dev: Reference to structure of type pch_udc_regs * Retern The device status */ static inline u32 pch_udc_read_device_status(struct pch_udc_dev *dev) { return pch_udc_readl(dev, UDC_DEVSTS_ADDR); } /** * pch_udc_read_ep_control() - Read the endpoint control * @ep: Reference to structure of type pch_udc_ep_regs * Retern The endpoint control register value */ static inline u32 pch_udc_read_ep_control(struct pch_udc_ep *ep) { return pch_udc_ep_readl(ep, UDC_EPCTL_ADDR); } /** * pch_udc_clear_ep_control() - Clear the endpoint control register * @ep: Reference to structure of type pch_udc_ep_regs * Retern The endpoint control register value */ static inline void pch_udc_clear_ep_control(struct pch_udc_ep *ep) { return pch_udc_ep_writel(ep, 0, UDC_EPCTL_ADDR); } /** * pch_udc_read_ep_status() - Read the endpoint status * @ep: Reference to structure of type pch_udc_ep_regs * Retern The endpoint status */ static inline u32 pch_udc_read_ep_status(struct pch_udc_ep *ep) { return pch_udc_ep_readl(ep, UDC_EPSTS_ADDR); } /** * pch_udc_clear_ep_status() - Clear the endpoint status * @ep: Reference to structure of type pch_udc_ep_regs * @stat: Endpoint status */ static inline void pch_udc_clear_ep_status(struct pch_udc_ep *ep, u32 stat) { return pch_udc_ep_writel(ep, stat, UDC_EPSTS_ADDR); } /** * pch_udc_ep_set_nak() - Set the bit 7 (SNAK field) * of the endpoint control register * @ep: Reference to structure of type pch_udc_ep_regs */ static inline void pch_udc_ep_set_nak(struct pch_udc_ep *ep) { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_SNAK); } /** * pch_udc_ep_clear_nak() - Set the bit 8 (CNAK field) * of the endpoint control register * @ep: reference to structure of type pch_udc_ep_regs */ static void pch_udc_ep_clear_nak(struct pch_udc_ep *ep) { unsigned int loopcnt = 0; struct pch_udc_dev *dev = ep->dev; if (!(pch_udc_ep_readl(ep, UDC_EPCTL_ADDR) & UDC_EPCTL_NAK)) return; if (!ep->in) { loopcnt = 10000; while (!(pch_udc_read_ep_status(ep) & UDC_EPSTS_MRXFIFO_EMP) && --loopcnt) udelay(5); if (!loopcnt) dev_err(&dev->pdev->dev, "%s: RxFIFO not Empty\n", __func__); } loopcnt = 10000; while ((pch_udc_read_ep_control(ep) & UDC_EPCTL_NAK) && --loopcnt) { pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_CNAK); udelay(5); } if (!loopcnt) dev_err(&dev->pdev->dev, "%s: Clear NAK not set for ep%d%s\n", __func__, ep->num, (ep->in ? "in" : "out")); } /** * pch_udc_ep_fifo_flush() - Flush the endpoint fifo * @ep: reference to structure of type pch_udc_ep_regs * @dir: direction of endpoint * 0: endpoint is OUT * !0: endpoint is IN */ static void pch_udc_ep_fifo_flush(struct pch_udc_ep *ep, int dir) { if (dir) { /* IN ep */ pch_udc_ep_bit_set(ep, UDC_EPCTL_ADDR, UDC_EPCTL_F); return; } } /** * pch_udc_ep_enable() - This api enables endpoint * @regs: Reference to structure pch_udc_ep_regs * @desc: endpoint descriptor */ static void pch_udc_ep_enable(struct pch_udc_ep *ep, struct pch_udc_cfg_data *cfg, const struct usb_endpoint_descriptor *desc) { u32 val = 0; u32 buff_size = 0; pch_udc_ep_set_trfr_type(ep, desc->bmAttributes); if (ep->in) buff_size = UDC_EPIN_BUFF_SIZE; else buff_size = UDC_EPOUT_BUFF_SIZE; pch_udc_ep_set_bufsz(ep, buff_size, ep->in); pch_udc_ep_set_maxpkt(ep, usb_endpoint_maxp(desc)); pch_udc_ep_set_nak(ep); pch_udc_ep_fifo_flush(ep, ep->in); /* Configure the endpoint */ val = ep->num << UDC_CSR_NE_NUM_SHIFT | ep->in << UDC_CSR_NE_DIR_SHIFT | ((desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) << UDC_CSR_NE_TYPE_SHIFT) | (cfg->cur_cfg << UDC_CSR_NE_CFG_SHIFT) | (cfg->cur_intf << UDC_CSR_NE_INTF_SHIFT) | (cfg->cur_alt << UDC_CSR_NE_ALT_SHIFT) | usb_endpoint_maxp(desc) << UDC_CSR_NE_MAX_PKT_SHIFT; if (ep->in) pch_udc_write_csr(ep->dev, val, UDC_EPIN_IDX(ep->num)); else pch_udc_write_csr(ep->dev, val, UDC_EPOUT_IDX(ep->num)); } /** * pch_udc_ep_disable() - This api disables endpoint * @regs: Reference to structure pch_udc_ep_regs */ static void pch_udc_ep_disable(struct pch_udc_ep *ep) { if (ep->in) { /* flush the fifo */ pch_udc_ep_writel(ep, UDC_EPCTL_F, UDC_EPCTL_ADDR); /* set NAK */ pch_udc_ep_writel(ep, UDC_EPCTL_SNAK, UDC_EPCTL_ADDR); pch_udc_ep_bit_set(ep, UDC_EPSTS_ADDR, UDC_EPSTS_IN); } else { /* set NAK */ pch_udc_ep_writel(ep, UDC_EPCTL_SNAK, UDC_EPCTL_ADDR); } /* reset desc pointer */ pch_udc_ep_writel(ep, 0, UDC_DESPTR_ADDR); } /** * pch_udc_wait_ep_stall() - Wait EP stall. * @dev: Reference to pch_udc_dev structure */ static void pch_udc_wait_ep_stall(struct pch_udc_ep *ep) { unsigned int count = 10000; /* Wait till idle */ while ((pch_udc_read_ep_control(ep) & UDC_EPCTL_S) && --count) udelay(5); if (!count) dev_err(&ep->dev->pdev->dev, "%s: wait error\n", __func__); } /** * pch_udc_init() - This API initializes usb device controller * @dev: Rreference to pch_udc_regs structure */ static void pch_udc_init(struct pch_udc_dev *dev) { if (NULL == dev) { pr_err("%s: Invalid address\n", __func__); return; } /* Soft Reset and Reset PHY */ pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR); pch_udc_writel(dev, UDC_SRST | UDC_PSRST, UDC_SRST_ADDR); mdelay(1); pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR); pch_udc_writel(dev, 0x00, UDC_SRST_ADDR); mdelay(1); /* mask and clear all device interrupts */ pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, UDC_DEVINT_MSK); pch_udc_bit_set(dev, UDC_DEVIRQSTS_ADDR, UDC_DEVINT_MSK); /* mask and clear all ep interrupts */ pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, UDC_EPINT_MSK_DISABLE_ALL); pch_udc_bit_set(dev, UDC_EPIRQSTS_ADDR, UDC_EPINT_MSK_DISABLE_ALL); /* enable dynamic CSR programmingi, self powered and device speed */ if (speed_fs) pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_CSR_PRG | UDC_DEVCFG_SP | UDC_DEVCFG_SPD_FS); else /* defaul high speed */ pch_udc_bit_set(dev, UDC_DEVCFG_ADDR, UDC_DEVCFG_CSR_PRG | UDC_DEVCFG_SP | UDC_DEVCFG_SPD_HS); pch_udc_bit_set(dev, UDC_DEVCTL_ADDR, (PCH_UDC_THLEN << UDC_DEVCTL_THLEN_SHIFT) | (PCH_UDC_BRLEN << UDC_DEVCTL_BRLEN_SHIFT) | UDC_DEVCTL_MODE | UDC_DEVCTL_BREN | UDC_DEVCTL_THE); } /** * pch_udc_exit() - This API exit usb device controller * @dev: Reference to pch_udc_regs structure */ static void pch_udc_exit(struct pch_udc_dev *dev) { /* mask all device interrupts */ pch_udc_bit_set(dev, UDC_DEVIRQMSK_ADDR, UDC_DEVINT_MSK); /* mask all ep interrupts */ pch_udc_bit_set(dev, UDC_EPIRQMSK_ADDR, UDC_EPINT_MSK_DISABLE_ALL); /* put device in disconnected state */ pch_udc_set_disconnect(dev); } /** * pch_udc_pcd_get_frame() - This API is invoked to get the current frame number * @gadget: Reference to the gadget driver * * Return codes: * 0: Success * -EINVAL: If the gadget passed is NULL */ static int pch_udc_pcd_get_frame(struct usb_gadget *gadget) { struct pch_udc_dev *dev; if (!gadget) return -EINVAL; dev = container_of(gadget, struct pch_udc_dev, gadget); return pch_udc_get_frame(dev); } /** * pch_udc_pcd_wakeup() - This API is invoked to initiate a remote wakeup * @gadget: Reference to the gadget driver * * Return codes: * 0: Success * -EINVAL: If the gadget passed is NULL */ static int pch_udc_pcd_wakeup(struct usb_gadget *gadget) { struct pch_udc_dev *dev; unsigned long flags; if (!gadget) return -EINVAL; dev = container_of(gadget, struct pch_udc_dev, gadget); spin_lock_irqsave(&dev->lock, flags); pch_udc_rmt_wakeup(dev); spin_unlock_irqrestore(&dev->lock, flags); return 0; } /** * pch_udc_pcd_selfpowered() - This API is invoked to specify whether the device * is self powered or not * @gadget: Reference to the gadget driver * @value: Specifies self powered or not * * Return codes: * 0: Success * -EINVAL: If the gadget passed is NULL */ static int pch_udc_pcd_selfpowered(struct usb_gadget *gadget, int value) { struct pch_udc_dev *dev; if (!gadget) return -EINVAL; dev = container_of(gadget, struct pch_udc_dev, gadget); if (value) pch_udc_set_selfpowered(dev); else pch_udc_clear_selfpowered(dev); return 0; } /** * pch_udc_pcd_pullup() - This API is invoked to make the device * visible/invisible to the host * @gadget: Reference to the gadget driver * @is_on: Specifies whether the pull up is made active or inactive * * Return codes: * 0: Success * -EINVAL: If the gadget passed is NULL */ static int pch_udc_pcd_pullup(struct usb_gadget *gadget, int is_on) { struct pch_udc_dev *dev; if (!gadget) return -EINVAL; dev = container_of(gadget, struct pch_udc_dev, gadget); if (is_on) { pch_udc_reconnect(dev); } else { if (dev->driver && dev->driver->disconnect) { spin_unlock(&dev->lock); dev->driver->disconnect(&dev->gadget); spin_lock(&dev->lock); } pch_udc_set_disconnect(dev); } return 0; } /** * pch_udc_pcd_vbus_session() - This API is used by a driver for an external * transceiver (or GPIO) that * detects a VBUS power session starting/ending * @gadget: Reference to the gadget driver * @is_active: specifies whether the session is starting or ending * * Return codes: * 0: Success * -EINVAL: If the gadget passed is NULL */ static int pch_udc_pcd_vbus_session(struct usb_gadget *gadget, int is_active) { struct pch_udc_dev *dev; if (!gadget) return -EINVAL; dev = container_of(gadget, struct pch_udc_dev, gadget); pch_udc_vbus_session(dev, is_active); return 0; } /** * pch_udc_pcd_vbus_draw() - This API is used by gadget drivers during * SET_CONFIGURATION calls to * specify how much power the device can consume * @gadget: Reference to the gadget driver * @mA: specifies the current limit in 2mA unit * * Return codes: * -EINVAL: If the gadget passed is NULL * -EOPNOTSUPP: */ static int pch_udc_pcd_vbus_draw(struct usb_gadget *gadget, unsigned int mA) { return -EOPNOTSUPP; } static int pch_udc_start(struct usb_gadget *g, struct usb_gadget_driver *driver); static int pch_udc_stop(struct usb_gadget *g, struct usb_gadget_driver *driver); static const struct usb_gadget_ops pch_udc_ops = { .get_frame = pch_udc_pcd_get_frame, .wakeup = pch_udc_pcd_wakeup, .set_selfpowered = pch_udc_pcd_selfpowered, .pullup = pch_udc_pcd_pullup, .vbus_session = pch_udc_pcd_vbus_session, .vbus_draw = pch_udc_pcd_vbus_draw, .udc_start = pch_udc_start, .udc_stop = pch_udc_stop, }; /** * pch_vbus_gpio_get_value() - This API gets value of GPIO port as VBUS status. * @dev: Reference to the driver structure * * Return value: * 1: VBUS is high * 0: VBUS is low * -1: It is not enable to detect VBUS using GPIO */ static int pch_vbus_gpio_get_value(struct pch_udc_dev *dev) { int vbus = 0; if (dev->vbus_gpio.port) vbus = gpio_get_value(dev->vbus_gpio.port) ? 1 : 0; else vbus = -1; return vbus; } /** * pch_vbus_gpio_work_fall() - This API keeps watch on VBUS becoming Low. * If VBUS is Low, disconnect is processed * @irq_work: Structure for WorkQueue * */ static void pch_vbus_gpio_work_fall(struct work_struct *irq_work) { struct pch_vbus_gpio_data *vbus_gpio = container_of(irq_work, struct pch_vbus_gpio_data, irq_work_fall); struct pch_udc_dev *dev = container_of(vbus_gpio, struct pch_udc_dev, vbus_gpio); int vbus_saved = -1; int vbus; int count; if (!dev->vbus_gpio.port) return; for (count = 0; count < (PCH_VBUS_PERIOD / PCH_VBUS_INTERVAL); count++) { vbus = pch_vbus_gpio_get_value(dev); if ((vbus_saved == vbus) && (vbus == 0)) { dev_dbg(&dev->pdev->dev, "VBUS fell"); if (dev->driver && dev->driver->disconnect) { dev->driver->disconnect( &dev->gadget); } if (dev->vbus_gpio.intr) pch_udc_init(dev); else pch_udc_reconnect(dev); return; } vbus_saved = vbus; mdelay(PCH_VBUS_INTERVAL); } } /** * pch_vbus_gpio_work_rise() - This API checks VBUS is High. * If VBUS is High, connect is processed * @irq_work: Structure for WorkQueue * */ static void pch_vbus_gpio_work_rise(struct work_struct *irq_work) { struct pch_vbus_gpio_data *vbus_gpio = container_of(irq_work, struct pch_vbus_gpio_data, irq_work_rise); struct pch_udc_dev *dev = container_of(vbus_gpio, struct pch_udc_dev, vbus_gpio); int vbus; if (!dev->vbus_gpio.port) return; mdelay(PCH_VBUS_INTERVAL); vbus = pch_vbus_gpio_get_value(dev); if (vbus == 1) { dev_dbg(&dev->pdev->dev, "VBUS rose"); pch_udc_reconnect(dev); return; } } /** * pch_vbus_gpio_irq() - IRQ handler for GPIO intrerrupt for changing VBUS * @irq: Interrupt request number * @dev: Reference to the device structure * * Return codes: * 0: Success * -EINVAL: GPIO port is invalid or can't be initialized. */ static irqreturn_t pch_vbus_gpio_irq(int irq, void *data) { struct pch_udc_dev *dev = (struct pch_udc_dev *)data; if (!dev->vbus_gpio.port || !dev->vbus_gpio.intr) return IRQ_NONE; if (pch_vbus_gpio_get_value(dev)) schedule_work(&dev->vbus_gpio.irq_work_rise); else schedule_work(&dev->vbus_gpio.irq_work_fall); return IRQ_HANDLED; } /** * pch_vbus_gpio_init() - This API initializes GPIO port detecting VBUS. * @dev: Reference to the driver structure * @vbus_gpio Number of GPIO port to detect gpio * * Return codes: * 0: Success * -EINVAL: GPIO port is invalid or can't be initialized. */ static int pch_vbus_gpio_init(struct pch_udc_dev *dev, int vbus_gpio_port) { int err; int irq_num = 0; dev->vbus_gpio.port = 0; dev->vbus_gpio.intr = 0; if (vbus_gpio_port <= -1) return -EINVAL; err = gpio_is_valid(vbus_gpio_port); if (!err) { pr_err("%s: gpio port %d is invalid\n", __func__, vbus_gpio_port); return -EINVAL; } err = gpio_request(vbus_gpio_port, "pch_vbus"); if (err) { pr_err("%s: can't request gpio port %d, err: %d\n", __func__, vbus_gpio_port, err); return -EINVAL; } dev->vbus_gpio.port = vbus_gpio_port; gpio_direction_input(vbus_gpio_port); INIT_WORK(&dev->vbus_gpio.irq_work_fall, pch_vbus_gpio_work_fall); irq_num = gpio_to_irq(vbus_gpio_port); if (irq_num > 0) { irq_set_irq_type(irq_num, IRQ_TYPE_EDGE_BOTH); err = request_irq(irq_num, pch_vbus_gpio_irq, 0, "vbus_detect", dev); if (!err) { dev->vbus_gpio.intr = irq_num; INIT_WORK(&dev->vbus_gpio.irq_work_rise, pch_vbus_gpio_work_rise); } else { pr_err("%s: can't request irq %d, err: %d\n", __func__, irq_num, err); } } return 0; } /** * pch_vbus_gpio_free() - This API frees resources of GPIO port * @dev: Reference to the driver structure */ static void pch_vbus_gpio_free(struct pch_udc_dev *dev) { if (dev->vbus_gpio.intr) free_irq(dev->vbus_gpio.intr, dev); if (dev->vbus_gpio.port) gpio_free(dev->vbus_gpio.port); } /** * complete_req() - This API is invoked from the driver when processing * of a request is complete * @ep: Reference to the endpoint structure * @req: Reference to the request structure * @status: Indicates the success/failure of completion */ static void complete_req(struct pch_udc_ep *ep, struct pch_udc_request *req, int status) __releases(&dev->lock) __acquires(&dev->lock) { struct pch_udc_dev *dev; unsigned halted = ep->halted; list_del_init(&req->queue); /* set new status if pending */ if (req->req.status == -EINPROGRESS) req->req.status = status; else status = req->req.status; dev = ep->dev; if (req->dma_mapped) { if (req->dma == DMA_ADDR_INVALID) { if (ep->in) dma_unmap_single(&dev->pdev->dev, req->req.dma, req->req.length, DMA_TO_DEVICE); else dma_unmap_single(&dev->pdev->dev, req->req.dma, req->req.length, DMA_FROM_DEVICE); req->req.dma = DMA_ADDR_INVALID; } else { if (ep->in) dma_unmap_single(&dev->pdev->dev, req->dma, req->req.length, DMA_TO_DEVICE); else { dma_unmap_single(&dev->pdev->dev, req->dma, req->req.length, DMA_FROM_DEVICE); memcpy(req->req.buf, req->buf, req->req.length); } kfree(req->buf); req->dma = DMA_ADDR_INVALID; } req->dma_mapped = 0; } ep->halted = 1; spin_unlock(&dev->lock); if (!ep->in) pch_udc_ep_clear_rrdy(ep); req->req.complete(&ep->ep, &req->req); spin_lock(&dev->lock); ep->halted = halted; } /** * empty_req_queue() - This API empties the request queue of an endpoint * @ep: Reference to the endpoint structure */ static void empty_req_queue(struct pch_udc_ep *ep) { struct pch_udc_request *req; ep->halted = 1; while (!list_empty(&ep->queue)) { req = list_entry(ep->queue.next, struct pch_udc_request, queue); complete_req(ep, req, -ESHUTDOWN); /* Remove from list */ } } /** * pch_udc_free_dma_chain() - This function frees the DMA chain created * for the request * @dev Reference to the driver structure * @req Reference to the request to be freed * * Return codes: * 0: Success */ static void pch_udc_free_dma_chain(struct pch_udc_dev *dev, struct pch_udc_request *req) { struct pch_udc_data_dma_desc *td = req->td_data; unsigned i = req->chain_len; dma_addr_t addr2; dma_addr_t addr = (dma_addr_t)td->next; td->next = 0x00; for (; i > 1; --i) { /* do not free first desc., will be done by free for request */ td = phys_to_virt(addr); addr2 = (dma_addr_t)td->next; pci_pool_free(dev->data_requests, td, addr); td->next = 0x00; addr = addr2; } req->chain_len = 1; } /** * pch_udc_create_dma_chain() - This function creates or reinitializes * a DMA chain * @ep: Reference to the endpoint structure * @req: Reference to the request * @buf_len: The buffer length * @gfp_flags: Flags to be used while mapping the data buffer * * Return codes: * 0: success, * -ENOMEM: pci_pool_alloc invocation fails */ static int pch_udc_create_dma_chain(struct pch_udc_ep *ep, struct pch_udc_request *req, unsigned long buf_len, gfp_t gfp_flags) { struct pch_udc_data_dma_desc *td = req->td_data, *last; unsigned long bytes = req->req.length, i = 0; dma_addr_t dma_addr; unsigned len = 1; if (req->chain_len > 1) pch_udc_free_dma_chain(ep->dev, req); if (req->dma == DMA_ADDR_INVALID) td->dataptr = req->req.dma; else td->dataptr = req->dma; td->status = PCH_UDC_BS_HST_BSY; for (; ; bytes -= buf_len, ++len) { td->status = PCH_UDC_BS_HST_BSY | min(buf_len, bytes); if (bytes <= buf_len) break; last = td; td = pci_pool_alloc(ep->dev->data_requests, gfp_flags, &dma_addr); if (!td) goto nomem; i += buf_len; td->dataptr = req->td_data->dataptr + i; last->next = dma_addr; } req->td_data_last = td; td->status |= PCH_UDC_DMA_LAST; td->next = req->td_data_phys; req->chain_len = len; return 0; nomem: if (len > 1) { req->chain_len = len; pch_udc_free_dma_chain(ep->dev, req); } req->chain_len = 1; return -ENOMEM; } /** * prepare_dma() - This function creates and initializes the DMA chain * for the request * @ep: Reference to the endpoint structure * @req: Reference to the request * @gfp: Flag to be used while mapping the data buffer * * Return codes: * 0: Success * Other 0: linux error number on failure */ static int prepare_dma(struct pch_udc_ep *ep, struct pch_udc_request *req, gfp_t gfp) { int retval; /* Allocate and create a DMA chain */ retval = pch_udc_create_dma_chain(ep, req, ep->ep.maxpacket, gfp); if (retval) { pr_err("%s: could not create DMA chain:%d\n", __func__, retval); return retval; } if (ep->in) req->td_data->status = (req->td_data->status & ~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY; return 0; } /** * process_zlp() - This function process zero length packets * from the gadget driver * @ep: Reference to the endpoint structure * @req: Reference to the request */ static void process_zlp(struct pch_udc_ep *ep, struct pch_udc_request *req) { struct pch_udc_dev *dev = ep->dev; /* IN zlp's are handled by hardware */ complete_req(ep, req, 0); /* if set_config or set_intf is waiting for ack by zlp * then set CSR_DONE */ if (dev->set_cfg_not_acked) { pch_udc_set_csr_done(dev); dev->set_cfg_not_acked = 0; } /* setup command is ACK'ed now by zlp */ if (!dev->stall && dev->waiting_zlp_ack) { pch_udc_ep_clear_nak(&(dev->ep[UDC_EP0IN_IDX])); dev->waiting_zlp_ack = 0; } } /** * pch_udc_start_rxrequest() - This function starts the receive requirement. * @ep: Reference to the endpoint structure * @req: Reference to the request structure */ static void pch_udc_start_rxrequest(struct pch_udc_ep *ep, struct pch_udc_request *req) { struct pch_udc_data_dma_desc *td_data; pch_udc_clear_dma(ep->dev, DMA_DIR_RX); td_data = req->td_data; /* Set the status bits for all descriptors */ while (1) { td_data->status = (td_data->status & ~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY; if ((td_data->status & PCH_UDC_DMA_LAST) == PCH_UDC_DMA_LAST) break; td_data = phys_to_virt(td_data->next); } /* Write the descriptor pointer */ pch_udc_ep_set_ddptr(ep, req->td_data_phys); req->dma_going = 1; pch_udc_enable_ep_interrupts(ep->dev, UDC_EPINT_OUT_EP0 << ep->num); pch_udc_set_dma(ep->dev, DMA_DIR_RX); pch_udc_ep_clear_nak(ep); pch_udc_ep_set_rrdy(ep); } /** * pch_udc_pcd_ep_enable() - This API enables the endpoint. It is called * from gadget driver * @usbep: Reference to the USB endpoint structure * @desc: Reference to the USB endpoint descriptor structure * * Return codes: * 0: Success * -EINVAL: * -ESHUTDOWN: */ static int pch_udc_pcd_ep_enable(struct usb_ep *usbep, const struct usb_endpoint_descriptor *desc) { struct pch_udc_ep *ep; struct pch_udc_dev *dev; unsigned long iflags; if (!usbep || (usbep->name == ep0_string) || !desc || (desc->bDescriptorType != USB_DT_ENDPOINT) || !desc->wMaxPacketSize) return -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if (!dev->driver || (dev->gadget.speed == USB_SPEED_UNKNOWN)) return -ESHUTDOWN; spin_lock_irqsave(&dev->lock, iflags); ep->ep.desc = desc; ep->halted = 0; pch_udc_ep_enable(ep, &ep->dev->cfg_data, desc); ep->ep.maxpacket = usb_endpoint_maxp(desc); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); spin_unlock_irqrestore(&dev->lock, iflags); return 0; } /** * pch_udc_pcd_ep_disable() - This API disables endpoint and is called * from gadget driver * @usbep Reference to the USB endpoint structure * * Return codes: * 0: Success * -EINVAL: */ static int pch_udc_pcd_ep_disable(struct usb_ep *usbep) { struct pch_udc_ep *ep; struct pch_udc_dev *dev; unsigned long iflags; if (!usbep) return -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if ((usbep->name == ep0_string) || !ep->ep.desc) return -EINVAL; spin_lock_irqsave(&ep->dev->lock, iflags); empty_req_queue(ep); ep->halted = 1; pch_udc_ep_disable(ep); pch_udc_disable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); ep->ep.desc = NULL; INIT_LIST_HEAD(&ep->queue); spin_unlock_irqrestore(&ep->dev->lock, iflags); return 0; } /** * pch_udc_alloc_request() - This function allocates request structure. * It is called by gadget driver * @usbep: Reference to the USB endpoint structure * @gfp: Flag to be used while allocating memory * * Return codes: * NULL: Failure * Allocated address: Success */ static struct usb_request *pch_udc_alloc_request(struct usb_ep *usbep, gfp_t gfp) { struct pch_udc_request *req; struct pch_udc_ep *ep; struct pch_udc_data_dma_desc *dma_desc; struct pch_udc_dev *dev; if (!usbep) return NULL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; req = kzalloc(sizeof *req, gfp); if (!req) return NULL; req->req.dma = DMA_ADDR_INVALID; req->dma = DMA_ADDR_INVALID; INIT_LIST_HEAD(&req->queue); if (!ep->dev->dma_addr) return &req->req; /* ep0 in requests are allocated from data pool here */ dma_desc = pci_pool_alloc(ep->dev->data_requests, gfp, &req->td_data_phys); if (NULL == dma_desc) { kfree(req); return NULL; } /* prevent from using desc. - set HOST BUSY */ dma_desc->status |= PCH_UDC_BS_HST_BSY; dma_desc->dataptr = __constant_cpu_to_le32(DMA_ADDR_INVALID); req->td_data = dma_desc; req->td_data_last = dma_desc; req->chain_len = 1; return &req->req; } /** * pch_udc_free_request() - This function frees request structure. * It is called by gadget driver * @usbep: Reference to the USB endpoint structure * @usbreq: Reference to the USB request */ static void pch_udc_free_request(struct usb_ep *usbep, struct usb_request *usbreq) { struct pch_udc_ep *ep; struct pch_udc_request *req; struct pch_udc_dev *dev; if (!usbep || !usbreq) return; ep = container_of(usbep, struct pch_udc_ep, ep); req = container_of(usbreq, struct pch_udc_request, req); dev = ep->dev; if (!list_empty(&req->queue)) dev_err(&dev->pdev->dev, "%s: %s req=0x%p queue not empty\n", __func__, usbep->name, req); if (req->td_data != NULL) { if (req->chain_len > 1) pch_udc_free_dma_chain(ep->dev, req); pci_pool_free(ep->dev->data_requests, req->td_data, req->td_data_phys); } kfree(req); } /** * pch_udc_pcd_queue() - This function queues a request packet. It is called * by gadget driver * @usbep: Reference to the USB endpoint structure * @usbreq: Reference to the USB request * @gfp: Flag to be used while mapping the data buffer * * Return codes: * 0: Success * linux error number: Failure */ static int pch_udc_pcd_queue(struct usb_ep *usbep, struct usb_request *usbreq, gfp_t gfp) { int retval = 0; struct pch_udc_ep *ep; struct pch_udc_dev *dev; struct pch_udc_request *req; unsigned long iflags; if (!usbep || !usbreq || !usbreq->complete || !usbreq->buf) return -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if (!ep->ep.desc && ep->num) return -EINVAL; req = container_of(usbreq, struct pch_udc_request, req); if (!list_empty(&req->queue)) return -EINVAL; if (!dev->driver || (dev->gadget.speed == USB_SPEED_UNKNOWN)) return -ESHUTDOWN; spin_lock_irqsave(&dev->lock, iflags); /* map the buffer for dma */ if (usbreq->length && ((usbreq->dma == DMA_ADDR_INVALID) || !usbreq->dma)) { if (!((unsigned long)(usbreq->buf) & 0x03)) { if (ep->in) usbreq->dma = dma_map_single(&dev->pdev->dev, usbreq->buf, usbreq->length, DMA_TO_DEVICE); else usbreq->dma = dma_map_single(&dev->pdev->dev, usbreq->buf, usbreq->length, DMA_FROM_DEVICE); } else { req->buf = kzalloc(usbreq->length, GFP_ATOMIC); if (!req->buf) { retval = -ENOMEM; goto probe_end; } if (ep->in) { memcpy(req->buf, usbreq->buf, usbreq->length); req->dma = dma_map_single(&dev->pdev->dev, req->buf, usbreq->length, DMA_TO_DEVICE); } else req->dma = dma_map_single(&dev->pdev->dev, req->buf, usbreq->length, DMA_FROM_DEVICE); } req->dma_mapped = 1; } if (usbreq->length > 0) { retval = prepare_dma(ep, req, GFP_ATOMIC); if (retval) goto probe_end; } usbreq->actual = 0; usbreq->status = -EINPROGRESS; req->dma_done = 0; if (list_empty(&ep->queue) && !ep->halted) { /* no pending transfer, so start this req */ if (!usbreq->length) { process_zlp(ep, req); retval = 0; goto probe_end; } if (!ep->in) { pch_udc_start_rxrequest(ep, req); } else { /* * For IN trfr the descriptors will be programmed and * P bit will be set when * we get an IN token */ pch_udc_wait_ep_stall(ep); pch_udc_ep_clear_nak(ep); pch_udc_enable_ep_interrupts(ep->dev, (1 << ep->num)); } } /* Now add this request to the ep's pending requests */ if (req != NULL) list_add_tail(&req->queue, &ep->queue); probe_end: spin_unlock_irqrestore(&dev->lock, iflags); return retval; } /** * pch_udc_pcd_dequeue() - This function de-queues a request packet. * It is called by gadget driver * @usbep: Reference to the USB endpoint structure * @usbreq: Reference to the USB request * * Return codes: * 0: Success * linux error number: Failure */ static int pch_udc_pcd_dequeue(struct usb_ep *usbep, struct usb_request *usbreq) { struct pch_udc_ep *ep; struct pch_udc_request *req; struct pch_udc_dev *dev; unsigned long flags; int ret = -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if (!usbep || !usbreq || (!ep->ep.desc && ep->num)) return ret; req = container_of(usbreq, struct pch_udc_request, req); spin_lock_irqsave(&ep->dev->lock, flags); /* make sure it's still queued on this endpoint */ list_for_each_entry(req, &ep->queue, queue) { if (&req->req == usbreq) { pch_udc_ep_set_nak(ep); if (!list_empty(&req->queue)) complete_req(ep, req, -ECONNRESET); ret = 0; break; } } spin_unlock_irqrestore(&ep->dev->lock, flags); return ret; } /** * pch_udc_pcd_set_halt() - This function Sets or clear the endpoint halt * feature * @usbep: Reference to the USB endpoint structure * @halt: Specifies whether to set or clear the feature * * Return codes: * 0: Success * linux error number: Failure */ static int pch_udc_pcd_set_halt(struct usb_ep *usbep, int halt) { struct pch_udc_ep *ep; struct pch_udc_dev *dev; unsigned long iflags; int ret; if (!usbep) return -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if (!ep->ep.desc && !ep->num) return -EINVAL; if (!ep->dev->driver || (ep->dev->gadget.speed == USB_SPEED_UNKNOWN)) return -ESHUTDOWN; spin_lock_irqsave(&udc_stall_spinlock, iflags); if (list_empty(&ep->queue)) { if (halt) { if (ep->num == PCH_UDC_EP0) ep->dev->stall = 1; pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } else { pch_udc_ep_clear_stall(ep); } ret = 0; } else { ret = -EAGAIN; } spin_unlock_irqrestore(&udc_stall_spinlock, iflags); return ret; } /** * pch_udc_pcd_set_wedge() - This function Sets or clear the endpoint * halt feature * @usbep: Reference to the USB endpoint structure * @halt: Specifies whether to set or clear the feature * * Return codes: * 0: Success * linux error number: Failure */ static int pch_udc_pcd_set_wedge(struct usb_ep *usbep) { struct pch_udc_ep *ep; struct pch_udc_dev *dev; unsigned long iflags; int ret; if (!usbep) return -EINVAL; ep = container_of(usbep, struct pch_udc_ep, ep); dev = ep->dev; if (!ep->ep.desc && !ep->num) return -EINVAL; if (!ep->dev->driver || (ep->dev->gadget.speed == USB_SPEED_UNKNOWN)) return -ESHUTDOWN; spin_lock_irqsave(&udc_stall_spinlock, iflags); if (!list_empty(&ep->queue)) { ret = -EAGAIN; } else { if (ep->num == PCH_UDC_EP0) ep->dev->stall = 1; pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); ep->dev->prot_stall = 1; ret = 0; } spin_unlock_irqrestore(&udc_stall_spinlock, iflags); return ret; } /** * pch_udc_pcd_fifo_flush() - This function Flush the FIFO of specified endpoint * @usbep: Reference to the USB endpoint structure */ static void pch_udc_pcd_fifo_flush(struct usb_ep *usbep) { struct pch_udc_ep *ep; if (!usbep) return; ep = container_of(usbep, struct pch_udc_ep, ep); if (ep->ep.desc || !ep->num) pch_udc_ep_fifo_flush(ep, ep->in); } static const struct usb_ep_ops pch_udc_ep_ops = { .enable = pch_udc_pcd_ep_enable, .disable = pch_udc_pcd_ep_disable, .alloc_request = pch_udc_alloc_request, .free_request = pch_udc_free_request, .queue = pch_udc_pcd_queue, .dequeue = pch_udc_pcd_dequeue, .set_halt = pch_udc_pcd_set_halt, .set_wedge = pch_udc_pcd_set_wedge, .fifo_status = NULL, .fifo_flush = pch_udc_pcd_fifo_flush, }; /** * pch_udc_init_setup_buff() - This function initializes the SETUP buffer * @td_stp: Reference to the SETP buffer structure */ static void pch_udc_init_setup_buff(struct pch_udc_stp_dma_desc *td_stp) { static u32 pky_marker; if (!td_stp) return; td_stp->reserved = ++pky_marker; memset(&td_stp->request, 0xFF, sizeof td_stp->request); td_stp->status = PCH_UDC_BS_HST_RDY; } /** * pch_udc_start_next_txrequest() - This function starts * the next transmission requirement * @ep: Reference to the endpoint structure */ static void pch_udc_start_next_txrequest(struct pch_udc_ep *ep) { struct pch_udc_request *req; struct pch_udc_data_dma_desc *td_data; if (pch_udc_read_ep_control(ep) & UDC_EPCTL_P) return; if (list_empty(&ep->queue)) return; /* next request */ req = list_entry(ep->queue.next, struct pch_udc_request, queue); if (req->dma_going) return; if (!req->td_data) return; pch_udc_wait_ep_stall(ep); req->dma_going = 1; pch_udc_ep_set_ddptr(ep, 0); td_data = req->td_data; while (1) { td_data->status = (td_data->status & ~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY; if ((td_data->status & PCH_UDC_DMA_LAST) == PCH_UDC_DMA_LAST) break; td_data = phys_to_virt(td_data->next); } pch_udc_ep_set_ddptr(ep, req->td_data_phys); pch_udc_set_dma(ep->dev, DMA_DIR_TX); pch_udc_ep_set_pd(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); pch_udc_ep_clear_nak(ep); } /** * pch_udc_complete_transfer() - This function completes a transfer * @ep: Reference to the endpoint structure */ static void pch_udc_complete_transfer(struct pch_udc_ep *ep) { struct pch_udc_request *req; struct pch_udc_dev *dev = ep->dev; if (list_empty(&ep->queue)) return; req = list_entry(ep->queue.next, struct pch_udc_request, queue); if ((req->td_data_last->status & PCH_UDC_BUFF_STS) != PCH_UDC_BS_DMA_DONE) return; if ((req->td_data_last->status & PCH_UDC_RXTX_STS) != PCH_UDC_RTS_SUCC) { dev_err(&dev->pdev->dev, "Invalid RXTX status (0x%08x) " "epstatus=0x%08x\n", (req->td_data_last->status & PCH_UDC_RXTX_STS), (int)(ep->epsts)); return; } req->req.actual = req->req.length; req->td_data_last->status = PCH_UDC_BS_HST_BSY | PCH_UDC_DMA_LAST; req->td_data->status = PCH_UDC_BS_HST_BSY | PCH_UDC_DMA_LAST; complete_req(ep, req, 0); req->dma_going = 0; if (!list_empty(&ep->queue)) { pch_udc_wait_ep_stall(ep); pch_udc_ep_clear_nak(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } else { pch_udc_disable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } } /** * pch_udc_complete_receiver() - This function completes a receiver * @ep: Reference to the endpoint structure */ static void pch_udc_complete_receiver(struct pch_udc_ep *ep) { struct pch_udc_request *req; struct pch_udc_dev *dev = ep->dev; unsigned int count; struct pch_udc_data_dma_desc *td; dma_addr_t addr; if (list_empty(&ep->queue)) return; /* next request */ req = list_entry(ep->queue.next, struct pch_udc_request, queue); pch_udc_clear_dma(ep->dev, DMA_DIR_RX); pch_udc_ep_set_ddptr(ep, 0); if ((req->td_data_last->status & PCH_UDC_BUFF_STS) == PCH_UDC_BS_DMA_DONE) td = req->td_data_last; else td = req->td_data; while (1) { if ((td->status & PCH_UDC_RXTX_STS) != PCH_UDC_RTS_SUCC) { dev_err(&dev->pdev->dev, "Invalid RXTX status=0x%08x " "epstatus=0x%08x\n", (req->td_data->status & PCH_UDC_RXTX_STS), (int)(ep->epsts)); return; } if ((td->status & PCH_UDC_BUFF_STS) == PCH_UDC_BS_DMA_DONE) if (td->status & PCH_UDC_DMA_LAST) { count = td->status & PCH_UDC_RXTX_BYTES; break; } if (td == req->td_data_last) { dev_err(&dev->pdev->dev, "Not complete RX descriptor"); return; } addr = (dma_addr_t)td->next; td = phys_to_virt(addr); } /* on 64k packets the RXBYTES field is zero */ if (!count && (req->req.length == UDC_DMA_MAXPACKET)) count = UDC_DMA_MAXPACKET; req->td_data->status |= PCH_UDC_DMA_LAST; td->status |= PCH_UDC_BS_HST_BSY; req->dma_going = 0; req->req.actual = count; complete_req(ep, req, 0); /* If there is a new/failed requests try that now */ if (!list_empty(&ep->queue)) { req = list_entry(ep->queue.next, struct pch_udc_request, queue); pch_udc_start_rxrequest(ep, req); } } /** * pch_udc_svc_data_in() - This function process endpoint interrupts * for IN endpoints * @dev: Reference to the device structure * @ep_num: Endpoint that generated the interrupt */ static void pch_udc_svc_data_in(struct pch_udc_dev *dev, int ep_num) { u32 epsts; struct pch_udc_ep *ep; ep = &dev->ep[UDC_EPIN_IDX(ep_num)]; epsts = ep->epsts; ep->epsts = 0; if (!(epsts & (UDC_EPSTS_IN | UDC_EPSTS_BNA | UDC_EPSTS_HE | UDC_EPSTS_TDC | UDC_EPSTS_RCS | UDC_EPSTS_TXEMPTY | UDC_EPSTS_RSS | UDC_EPSTS_XFERDONE))) return; if ((epsts & UDC_EPSTS_BNA)) return; if (epsts & UDC_EPSTS_HE) return; if (epsts & UDC_EPSTS_RSS) { pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } if (epsts & UDC_EPSTS_RCS) { if (!dev->prot_stall) { pch_udc_ep_clear_stall(ep); } else { pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } } if (epsts & UDC_EPSTS_TDC) pch_udc_complete_transfer(ep); /* On IN interrupt, provide data if we have any */ if ((epsts & UDC_EPSTS_IN) && !(epsts & UDC_EPSTS_RSS) && !(epsts & UDC_EPSTS_TDC) && !(epsts & UDC_EPSTS_TXEMPTY)) pch_udc_start_next_txrequest(ep); } /** * pch_udc_svc_data_out() - Handles interrupts from OUT endpoint * @dev: Reference to the device structure * @ep_num: Endpoint that generated the interrupt */ static void pch_udc_svc_data_out(struct pch_udc_dev *dev, int ep_num) { u32 epsts; struct pch_udc_ep *ep; struct pch_udc_request *req = NULL; ep = &dev->ep[UDC_EPOUT_IDX(ep_num)]; epsts = ep->epsts; ep->epsts = 0; if ((epsts & UDC_EPSTS_BNA) && (!list_empty(&ep->queue))) { /* next request */ req = list_entry(ep->queue.next, struct pch_udc_request, queue); if ((req->td_data_last->status & PCH_UDC_BUFF_STS) != PCH_UDC_BS_DMA_DONE) { if (!req->dma_going) pch_udc_start_rxrequest(ep, req); return; } } if (epsts & UDC_EPSTS_HE) return; if (epsts & UDC_EPSTS_RSS) { pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } if (epsts & UDC_EPSTS_RCS) { if (!dev->prot_stall) { pch_udc_ep_clear_stall(ep); } else { pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } } if (((epsts & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) == UDC_EPSTS_OUT_DATA) { if (ep->dev->prot_stall == 1) { pch_udc_ep_set_stall(ep); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); } else { pch_udc_complete_receiver(ep); } } if (list_empty(&ep->queue)) pch_udc_set_dma(dev, DMA_DIR_RX); } /** * pch_udc_svc_control_in() - Handle Control IN endpoint interrupts * @dev: Reference to the device structure */ static void pch_udc_svc_control_in(struct pch_udc_dev *dev) { u32 epsts; struct pch_udc_ep *ep; struct pch_udc_ep *ep_out; ep = &dev->ep[UDC_EP0IN_IDX]; ep_out = &dev->ep[UDC_EP0OUT_IDX]; epsts = ep->epsts; ep->epsts = 0; if (!(epsts & (UDC_EPSTS_IN | UDC_EPSTS_BNA | UDC_EPSTS_HE | UDC_EPSTS_TDC | UDC_EPSTS_RCS | UDC_EPSTS_TXEMPTY | UDC_EPSTS_XFERDONE))) return; if ((epsts & UDC_EPSTS_BNA)) return; if (epsts & UDC_EPSTS_HE) return; if ((epsts & UDC_EPSTS_TDC) && (!dev->stall)) { pch_udc_complete_transfer(ep); pch_udc_clear_dma(dev, DMA_DIR_RX); ep_out->td_data->status = (ep_out->td_data->status & ~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY; pch_udc_ep_clear_nak(ep_out); pch_udc_set_dma(dev, DMA_DIR_RX); pch_udc_ep_set_rrdy(ep_out); } /* On IN interrupt, provide data if we have any */ if ((epsts & UDC_EPSTS_IN) && !(epsts & UDC_EPSTS_TDC) && !(epsts & UDC_EPSTS_TXEMPTY)) pch_udc_start_next_txrequest(ep); } /** * pch_udc_svc_control_out() - Routine that handle Control * OUT endpoint interrupts * @dev: Reference to the device structure */ static void pch_udc_svc_control_out(struct pch_udc_dev *dev) __releases(&dev->lock) __acquires(&dev->lock) { u32 stat; int setup_supported; struct pch_udc_ep *ep; ep = &dev->ep[UDC_EP0OUT_IDX]; stat = ep->epsts; ep->epsts = 0; /* If setup data */ if (((stat & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) == UDC_EPSTS_OUT_SETUP) { dev->stall = 0; dev->ep[UDC_EP0IN_IDX].halted = 0; dev->ep[UDC_EP0OUT_IDX].halted = 0; dev->setup_data = ep->td_stp->request; pch_udc_init_setup_buff(ep->td_stp); pch_udc_clear_dma(dev, DMA_DIR_RX); pch_udc_ep_fifo_flush(&(dev->ep[UDC_EP0IN_IDX]), dev->ep[UDC_EP0IN_IDX].in); if ((dev->setup_data.bRequestType & USB_DIR_IN)) dev->gadget.ep0 = &dev->ep[UDC_EP0IN_IDX].ep; else /* OUT */ dev->gadget.ep0 = &ep->ep; spin_unlock(&dev->lock); /* If Mass storage Reset */ if ((dev->setup_data.bRequestType == 0x21) && (dev->setup_data.bRequest == 0xFF)) dev->prot_stall = 0; /* call gadget with setup data received */ setup_supported = dev->driver->setup(&dev->gadget, &dev->setup_data); spin_lock(&dev->lock); if (dev->setup_data.bRequestType & USB_DIR_IN) { ep->td_data->status = (ep->td_data->status & ~PCH_UDC_BUFF_STS) | PCH_UDC_BS_HST_RDY; pch_udc_ep_set_ddptr(ep, ep->td_data_phys); } /* ep0 in returns data on IN phase */ if (setup_supported >= 0 && setup_supported < UDC_EP0IN_MAX_PKT_SIZE) { pch_udc_ep_clear_nak(&(dev->ep[UDC_EP0IN_IDX])); /* Gadget would have queued a request when * we called the setup */ if (!(dev->setup_data.bRequestType & USB_DIR_IN)) { pch_udc_set_dma(dev, DMA_DIR_RX); pch_udc_ep_clear_nak(ep); } } else if (setup_supported < 0) { /* if unsupported request, then stall */ pch_udc_ep_set_stall(&(dev->ep[UDC_EP0IN_IDX])); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); dev->stall = 0; pch_udc_set_dma(dev, DMA_DIR_RX); } else { dev->waiting_zlp_ack = 1; } } else if ((((stat & UDC_EPSTS_OUT_MASK) >> UDC_EPSTS_OUT_SHIFT) == UDC_EPSTS_OUT_DATA) && !dev->stall) { pch_udc_clear_dma(dev, DMA_DIR_RX); pch_udc_ep_set_ddptr(ep, 0); if (!list_empty(&ep->queue)) { ep->epsts = stat; pch_udc_svc_data_out(dev, PCH_UDC_EP0); } pch_udc_set_dma(dev, DMA_DIR_RX); } pch_udc_ep_set_rrdy(ep); } /** * pch_udc_postsvc_epinters() - This function enables end point interrupts * and clears NAK status * @dev: Reference to the device structure * @ep_num: End point number */ static void pch_udc_postsvc_epinters(struct pch_udc_dev *dev, int ep_num) { struct pch_udc_ep *ep; struct pch_udc_request *req; ep = &dev->ep[UDC_EPIN_IDX(ep_num)]; if (!list_empty(&ep->queue)) { req = list_entry(ep->queue.next, struct pch_udc_request, queue); pch_udc_enable_ep_interrupts(ep->dev, PCH_UDC_EPINT(ep->in, ep->num)); pch_udc_ep_clear_nak(ep); } } /** * pch_udc_read_all_epstatus() - This function read all endpoint status * @dev: Reference to the device structure * @ep_intr: Status of endpoint interrupt */ static void pch_udc_read_all_epstatus(struct pch_udc_dev *dev, u32 ep_intr) { int i; struct pch_udc_ep *ep; for (i = 0; i < PCH_UDC_USED_EP_NUM; i++) { /* IN */ if (ep_intr & (0x1 << i)) { ep = &dev->ep[UDC_EPIN_IDX(i)]; ep->epsts = pch_udc_read_ep_status(ep); pch_udc_clear_ep_status(ep, ep->epsts); } /* OUT */ if (ep_intr & (0x10000 << i)) { ep = &dev->ep[UDC_EPOUT_IDX(i)]; ep->epsts = pch_udc_read_ep_status(ep); pch_udc_clear_ep_status(ep, ep->epsts); } } } /** * pch_udc_activate_control_ep() - This function enables the control endpoints * for traffic after a reset * @dev: Reference to the device structure */ static void pch_udc_activate_control_ep(struct pch_udc_dev *dev) { struct pch_udc_ep *ep; u32 val; /* Setup the IN endpoint */ ep = &dev->ep[UDC_EP0IN_IDX]; pch_udc_clear_ep_control(ep); pch_udc_ep_fifo_flush(ep, ep->in); pch_udc_ep_set_bufsz(ep, UDC_EP0IN_BUFF_SIZE, ep->in); pch_udc_ep_set_maxpkt(ep, UDC_EP0IN_MAX_PKT_SIZE); /* Initialize the IN EP Descriptor */ ep->td_data = NULL; ep->td_stp = NULL; ep->td_data_phys = 0; ep->td_stp_phys = 0; /* Setup the OUT endpoint */ ep = &dev->ep[UDC_EP0OUT_IDX]; pch_udc_clear_ep_control(ep); pch_udc_ep_fifo_flush(ep, ep->in); pch_udc_ep_set_bufsz(ep, UDC_EP0OUT_BUFF_SIZE, ep->in); pch_udc_ep_set_maxpkt(ep, UDC_EP0OUT_MAX_PKT_SIZE); val = UDC_EP0OUT_MAX_PKT_SIZE << UDC_CSR_NE_MAX_PKT_SHIFT; pch_udc_write_csr(ep->dev, val, UDC_EP0OUT_IDX); /* Initialize the SETUP buffer */ pch_udc_init_setup_buff(ep->td_stp); /* Write the pointer address of dma descriptor */ pch_udc_ep_set_subptr(ep, ep->td_stp_phys); /* Write the pointer address of Setup descriptor */ pch_udc_ep_set_ddptr(ep, ep->td_data_phys); /* Initialize the dma descriptor */ ep->td_data->status = PCH_UDC_DMA_LAST; ep->td_data->dataptr = dev->dma_addr; ep->td_data->next = ep->td_data_phys; pch_udc_ep_clear_nak(ep); } /** * pch_udc_svc_ur_interrupt() - This function handles a USB reset interrupt * @dev: Reference to driver structure */ static void pch_udc_svc_ur_interrupt(struct pch_udc_dev *dev) { struct pch_udc_ep *ep; int i; pch_udc_clear_dma(dev, DMA_DIR_TX); pch_udc_clear_dma(dev, DMA_DIR_RX); /* Mask all endpoint interrupts */ pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL); /* clear all endpoint interrupts */ pch_udc_write_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL); for (i = 0; i < PCH_UDC_EP_NUM; i++) { ep = &dev->ep[i]; pch_udc_clear_ep_status(ep, UDC_EPSTS_ALL_CLR_MASK); pch_udc_clear_ep_control(ep); pch_udc_ep_set_ddptr(ep, 0); pch_udc_write_csr(ep->dev, 0x00, i); } dev->stall = 0; dev->prot_stall = 0; dev->waiting_zlp_ack = 0; dev->set_cfg_not_acked = 0; /* disable ep to empty req queue. Skip the control EP's */ for (i = 0; i < (PCH_UDC_USED_EP_NUM*2); i++) { ep = &dev->ep[i]; pch_udc_ep_set_nak(ep); pch_udc_ep_fifo_flush(ep, ep->in); /* Complete request queue */ empty_req_queue(ep); } if (dev->driver && dev->driver->disconnect) { spin_unlock(&dev->lock); dev->driver->disconnect(&dev->gadget); spin_lock(&dev->lock); } } /** * pch_udc_svc_enum_interrupt() - This function handles a USB speed enumeration * done interrupt * @dev: Reference to driver structure */ static void pch_udc_svc_enum_interrupt(struct pch_udc_dev *dev) { u32 dev_stat, dev_speed; u32 speed = USB_SPEED_FULL; dev_stat = pch_udc_read_device_status(dev); dev_speed = (dev_stat & UDC_DEVSTS_ENUM_SPEED_MASK) >> UDC_DEVSTS_ENUM_SPEED_SHIFT; switch (dev_speed) { case UDC_DEVSTS_ENUM_SPEED_HIGH: speed = USB_SPEED_HIGH; break; case UDC_DEVSTS_ENUM_SPEED_FULL: speed = USB_SPEED_FULL; break; case UDC_DEVSTS_ENUM_SPEED_LOW: speed = USB_SPEED_LOW; break; default: BUG(); } dev->gadget.speed = speed; pch_udc_activate_control_ep(dev); pch_udc_enable_ep_interrupts(dev, UDC_EPINT_IN_EP0 | UDC_EPINT_OUT_EP0); pch_udc_set_dma(dev, DMA_DIR_TX); pch_udc_set_dma(dev, DMA_DIR_RX); pch_udc_ep_set_rrdy(&(dev->ep[UDC_EP0OUT_IDX])); /* enable device interrupts */ pch_udc_enable_interrupts(dev, UDC_DEVINT_UR | UDC_DEVINT_US | UDC_DEVINT_ES | UDC_DEVINT_ENUM | UDC_DEVINT_SI | UDC_DEVINT_SC); } /** * pch_udc_svc_intf_interrupt() - This function handles a set interface * interrupt * @dev: Reference to driver structure */ static void pch_udc_svc_intf_interrupt(struct pch_udc_dev *dev) { u32 reg, dev_stat = 0; int i, ret; dev_stat = pch_udc_read_device_status(dev); dev->cfg_data.cur_intf = (dev_stat & UDC_DEVSTS_INTF_MASK) >> UDC_DEVSTS_INTF_SHIFT; dev->cfg_data.cur_alt = (dev_stat & UDC_DEVSTS_ALT_MASK) >> UDC_DEVSTS_ALT_SHIFT; dev->set_cfg_not_acked = 1; /* Construct the usb request for gadget driver and inform it */ memset(&dev->setup_data, 0 , sizeof dev->setup_data); dev->setup_data.bRequest = USB_REQ_SET_INTERFACE; dev->setup_data.bRequestType = USB_RECIP_INTERFACE; dev->setup_data.wValue = cpu_to_le16(dev->cfg_data.cur_alt); dev->setup_data.wIndex = cpu_to_le16(dev->cfg_data.cur_intf); /* programm the Endpoint Cfg registers */ /* Only one end point cfg register */ reg = pch_udc_read_csr(dev, UDC_EP0OUT_IDX); reg = (reg & ~UDC_CSR_NE_INTF_MASK) | (dev->cfg_data.cur_intf << UDC_CSR_NE_INTF_SHIFT); reg = (reg & ~UDC_CSR_NE_ALT_MASK) | (dev->cfg_data.cur_alt << UDC_CSR_NE_ALT_SHIFT); pch_udc_write_csr(dev, reg, UDC_EP0OUT_IDX); for (i = 0; i < PCH_UDC_USED_EP_NUM * 2; i++) { /* clear stall bits */ pch_udc_ep_clear_stall(&(dev->ep[i])); dev->ep[i].halted = 0; } dev->stall = 0; spin_unlock(&dev->lock); ret = dev->driver->setup(&dev->gadget, &dev->setup_data); spin_lock(&dev->lock); } /** * pch_udc_svc_cfg_interrupt() - This function handles a set configuration * interrupt * @dev: Reference to driver structure */ static void pch_udc_svc_cfg_interrupt(struct pch_udc_dev *dev) { int i, ret; u32 reg, dev_stat = 0; dev_stat = pch_udc_read_device_status(dev); dev->set_cfg_not_acked = 1; dev->cfg_data.cur_cfg = (dev_stat & UDC_DEVSTS_CFG_MASK) >> UDC_DEVSTS_CFG_SHIFT; /* make usb request for gadget driver */ memset(&dev->setup_data, 0 , sizeof dev->setup_data); dev->setup_data.bRequest = USB_REQ_SET_CONFIGURATION; dev->setup_data.wValue = cpu_to_le16(dev->cfg_data.cur_cfg); /* program the NE registers */ /* Only one end point cfg register */ reg = pch_udc_read_csr(dev, UDC_EP0OUT_IDX); reg = (reg & ~UDC_CSR_NE_CFG_MASK) | (dev->cfg_data.cur_cfg << UDC_CSR_NE_CFG_SHIFT); pch_udc_write_csr(dev, reg, UDC_EP0OUT_IDX); for (i = 0; i < PCH_UDC_USED_EP_NUM * 2; i++) { /* clear stall bits */ pch_udc_ep_clear_stall(&(dev->ep[i])); dev->ep[i].halted = 0; } dev->stall = 0; /* call gadget zero with setup data received */ spin_unlock(&dev->lock); ret = dev->driver->setup(&dev->gadget, &dev->setup_data); spin_lock(&dev->lock); } /** * pch_udc_dev_isr() - This function services device interrupts * by invoking appropriate routines. * @dev: Reference to the device structure * @dev_intr: The Device interrupt status. */ static void pch_udc_dev_isr(struct pch_udc_dev *dev, u32 dev_intr) { int vbus; /* USB Reset Interrupt */ if (dev_intr & UDC_DEVINT_UR) { pch_udc_svc_ur_interrupt(dev); dev_dbg(&dev->pdev->dev, "USB_RESET\n"); } /* Enumeration Done Interrupt */ if (dev_intr & UDC_DEVINT_ENUM) { pch_udc_svc_enum_interrupt(dev); dev_dbg(&dev->pdev->dev, "USB_ENUM\n"); } /* Set Interface Interrupt */ if (dev_intr & UDC_DEVINT_SI) pch_udc_svc_intf_interrupt(dev); /* Set Config Interrupt */ if (dev_intr & UDC_DEVINT_SC) pch_udc_svc_cfg_interrupt(dev); /* USB Suspend interrupt */ if (dev_intr & UDC_DEVINT_US) { if (dev->driver && dev->driver->suspend) { spin_unlock(&dev->lock); dev->driver->suspend(&dev->gadget); spin_lock(&dev->lock); } vbus = pch_vbus_gpio_get_value(dev); if ((dev->vbus_session == 0) && (vbus != 1)) { if (dev->driver && dev->driver->disconnect) { spin_unlock(&dev->lock); dev->driver->disconnect(&dev->gadget); spin_lock(&dev->lock); } pch_udc_reconnect(dev); } else if ((dev->vbus_session == 0) && (vbus == 1) && !dev->vbus_gpio.intr) schedule_work(&dev->vbus_gpio.irq_work_fall); dev_dbg(&dev->pdev->dev, "USB_SUSPEND\n"); } /* Clear the SOF interrupt, if enabled */ if (dev_intr & UDC_DEVINT_SOF) dev_dbg(&dev->pdev->dev, "SOF\n"); /* ES interrupt, IDLE > 3ms on the USB */ if (dev_intr & UDC_DEVINT_ES) dev_dbg(&dev->pdev->dev, "ES\n"); /* RWKP interrupt */ if (dev_intr & UDC_DEVINT_RWKP) dev_dbg(&dev->pdev->dev, "RWKP\n"); } /** * pch_udc_isr() - This function handles interrupts from the PCH USB Device * @irq: Interrupt request number * @dev: Reference to the device structure */ static irqreturn_t pch_udc_isr(int irq, void *pdev) { struct pch_udc_dev *dev = (struct pch_udc_dev *) pdev; u32 dev_intr, ep_intr; int i; dev_intr = pch_udc_read_device_interrupts(dev); ep_intr = pch_udc_read_ep_interrupts(dev); /* For a hot plug, this find that the controller is hung up. */ if (dev_intr == ep_intr) if (dev_intr == pch_udc_readl(dev, UDC_DEVCFG_ADDR)) { dev_dbg(&dev->pdev->dev, "UDC: Hung up\n"); /* The controller is reset */ pch_udc_writel(dev, UDC_SRST, UDC_SRST_ADDR); return IRQ_HANDLED; } if (dev_intr) /* Clear device interrupts */ pch_udc_write_device_interrupts(dev, dev_intr); if (ep_intr) /* Clear ep interrupts */ pch_udc_write_ep_interrupts(dev, ep_intr); if (!dev_intr && !ep_intr) return IRQ_NONE; spin_lock(&dev->lock); if (dev_intr) pch_udc_dev_isr(dev, dev_intr); if (ep_intr) { pch_udc_read_all_epstatus(dev, ep_intr); /* Process Control In interrupts, if present */ if (ep_intr & UDC_EPINT_IN_EP0) { pch_udc_svc_control_in(dev); pch_udc_postsvc_epinters(dev, 0); } /* Process Control Out interrupts, if present */ if (ep_intr & UDC_EPINT_OUT_EP0) pch_udc_svc_control_out(dev); /* Process data in end point interrupts */ for (i = 1; i < PCH_UDC_USED_EP_NUM; i++) { if (ep_intr & (1 << i)) { pch_udc_svc_data_in(dev, i); pch_udc_postsvc_epinters(dev, i); } } /* Process data out end point interrupts */ for (i = UDC_EPINT_OUT_SHIFT + 1; i < (UDC_EPINT_OUT_SHIFT + PCH_UDC_USED_EP_NUM); i++) if (ep_intr & (1 << i)) pch_udc_svc_data_out(dev, i - UDC_EPINT_OUT_SHIFT); } spin_unlock(&dev->lock); return IRQ_HANDLED; } /** * pch_udc_setup_ep0() - This function enables control endpoint for traffic * @dev: Reference to the device structure */ static void pch_udc_setup_ep0(struct pch_udc_dev *dev) { /* enable ep0 interrupts */ pch_udc_enable_ep_interrupts(dev, UDC_EPINT_IN_EP0 | UDC_EPINT_OUT_EP0); /* enable device interrupts */ pch_udc_enable_interrupts(dev, UDC_DEVINT_UR | UDC_DEVINT_US | UDC_DEVINT_ES | UDC_DEVINT_ENUM | UDC_DEVINT_SI | UDC_DEVINT_SC); } /** * gadget_release() - Free the gadget driver private data * @pdev reference to struct pci_dev */ static void gadget_release(struct device *pdev) { struct pch_udc_dev *dev = dev_get_drvdata(pdev); kfree(dev); } /** * pch_udc_pcd_reinit() - This API initializes the endpoint structures * @dev: Reference to the driver structure */ static void pch_udc_pcd_reinit(struct pch_udc_dev *dev) { const char *const ep_string[] = { ep0_string, "ep0out", "ep1in", "ep1out", "ep2in", "ep2out", "ep3in", "ep3out", "ep4in", "ep4out", "ep5in", "ep5out", "ep6in", "ep6out", "ep7in", "ep7out", "ep8in", "ep8out", "ep9in", "ep9out", "ep10in", "ep10out", "ep11in", "ep11out", "ep12in", "ep12out", "ep13in", "ep13out", "ep14in", "ep14out", "ep15in", "ep15out", }; int i; dev->gadget.speed = USB_SPEED_UNKNOWN; INIT_LIST_HEAD(&dev->gadget.ep_list); /* Initialize the endpoints structures */ memset(dev->ep, 0, sizeof dev->ep); for (i = 0; i < PCH_UDC_EP_NUM; i++) { struct pch_udc_ep *ep = &dev->ep[i]; ep->dev = dev; ep->halted = 1; ep->num = i / 2; ep->in = ~i & 1; ep->ep.name = ep_string[i]; ep->ep.ops = &pch_udc_ep_ops; if (ep->in) ep->offset_addr = ep->num * UDC_EP_REG_SHIFT; else ep->offset_addr = (UDC_EPINT_OUT_SHIFT + ep->num) * UDC_EP_REG_SHIFT; /* need to set ep->ep.maxpacket and set Default Configuration?*/ ep->ep.maxpacket = UDC_BULK_MAX_PKT_SIZE; list_add_tail(&ep->ep.ep_list, &dev->gadget.ep_list); INIT_LIST_HEAD(&ep->queue); } dev->ep[UDC_EP0IN_IDX].ep.maxpacket = UDC_EP0IN_MAX_PKT_SIZE; dev->ep[UDC_EP0OUT_IDX].ep.maxpacket = UDC_EP0OUT_MAX_PKT_SIZE; /* remove ep0 in and out from the list. They have own pointer */ list_del_init(&dev->ep[UDC_EP0IN_IDX].ep.ep_list); list_del_init(&dev->ep[UDC_EP0OUT_IDX].ep.ep_list); dev->gadget.ep0 = &dev->ep[UDC_EP0IN_IDX].ep; INIT_LIST_HEAD(&dev->gadget.ep0->ep_list); } /** * pch_udc_pcd_init() - This API initializes the driver structure * @dev: Reference to the driver structure * * Return codes: * 0: Success */ static int pch_udc_pcd_init(struct pch_udc_dev *dev) { pch_udc_init(dev); pch_udc_pcd_reinit(dev); pch_vbus_gpio_init(dev, vbus_gpio_port); return 0; } /** * init_dma_pools() - create dma pools during initialization * @pdev: reference to struct pci_dev */ static int init_dma_pools(struct pch_udc_dev *dev) { struct pch_udc_stp_dma_desc *td_stp; struct pch_udc_data_dma_desc *td_data; /* DMA setup */ dev->data_requests = pci_pool_create("data_requests", dev->pdev, sizeof(struct pch_udc_data_dma_desc), 0, 0); if (!dev->data_requests) { dev_err(&dev->pdev->dev, "%s: can't get request data pool\n", __func__); return -ENOMEM; } /* dma desc for setup data */ dev->stp_requests = pci_pool_create("setup requests", dev->pdev, sizeof(struct pch_udc_stp_dma_desc), 0, 0); if (!dev->stp_requests) { dev_err(&dev->pdev->dev, "%s: can't get setup request pool\n", __func__); return -ENOMEM; } /* setup */ td_stp = pci_pool_alloc(dev->stp_requests, GFP_KERNEL, &dev->ep[UDC_EP0OUT_IDX].td_stp_phys); if (!td_stp) { dev_err(&dev->pdev->dev, "%s: can't allocate setup dma descriptor\n", __func__); return -ENOMEM; } dev->ep[UDC_EP0OUT_IDX].td_stp = td_stp; /* data: 0 packets !? */ td_data = pci_pool_alloc(dev->data_requests, GFP_KERNEL, &dev->ep[UDC_EP0OUT_IDX].td_data_phys); if (!td_data) { dev_err(&dev->pdev->dev, "%s: can't allocate data dma descriptor\n", __func__); return -ENOMEM; } dev->ep[UDC_EP0OUT_IDX].td_data = td_data; dev->ep[UDC_EP0IN_IDX].td_stp = NULL; dev->ep[UDC_EP0IN_IDX].td_stp_phys = 0; dev->ep[UDC_EP0IN_IDX].td_data = NULL; dev->ep[UDC_EP0IN_IDX].td_data_phys = 0; dev->ep0out_buf = kzalloc(UDC_EP0OUT_BUFF_SIZE * 4, GFP_KERNEL); if (!dev->ep0out_buf) return -ENOMEM; dev->dma_addr = dma_map_single(&dev->pdev->dev, dev->ep0out_buf, UDC_EP0OUT_BUFF_SIZE * 4, DMA_FROM_DEVICE); return 0; } static int pch_udc_start(struct usb_gadget *g, struct usb_gadget_driver *driver) { struct pch_udc_dev *dev = to_pch_udc(g); driver->driver.bus = NULL; dev->driver = driver; /* get ready for ep0 traffic */ pch_udc_setup_ep0(dev); /* clear SD */ if ((pch_vbus_gpio_get_value(dev) != 0) || !dev->vbus_gpio.intr) pch_udc_clear_disconnect(dev); dev->connected = 1; return 0; } static int pch_udc_stop(struct usb_gadget *g, struct usb_gadget_driver *driver) { struct pch_udc_dev *dev = to_pch_udc(g); pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK); /* Assures that there are no pending requests with this driver */ dev->driver = NULL; dev->connected = 0; /* set SD */ pch_udc_set_disconnect(dev); return 0; } static void pch_udc_shutdown(struct pci_dev *pdev) { struct pch_udc_dev *dev = pci_get_drvdata(pdev); pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK); pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL); /* disable the pullup so the host will think we're gone */ pch_udc_set_disconnect(dev); } static void pch_udc_remove(struct pci_dev *pdev) { struct pch_udc_dev *dev = pci_get_drvdata(pdev); usb_del_gadget_udc(&dev->gadget); /* gadget driver must not be registered */ if (dev->driver) dev_err(&pdev->dev, "%s: gadget driver still bound!!!\n", __func__); /* dma pool cleanup */ if (dev->data_requests) pci_pool_destroy(dev->data_requests); if (dev->stp_requests) { /* cleanup DMA desc's for ep0in */ if (dev->ep[UDC_EP0OUT_IDX].td_stp) { pci_pool_free(dev->stp_requests, dev->ep[UDC_EP0OUT_IDX].td_stp, dev->ep[UDC_EP0OUT_IDX].td_stp_phys); } if (dev->ep[UDC_EP0OUT_IDX].td_data) { pci_pool_free(dev->stp_requests, dev->ep[UDC_EP0OUT_IDX].td_data, dev->ep[UDC_EP0OUT_IDX].td_data_phys); } pci_pool_destroy(dev->stp_requests); } if (dev->dma_addr) dma_unmap_single(&dev->pdev->dev, dev->dma_addr, UDC_EP0OUT_BUFF_SIZE * 4, DMA_FROM_DEVICE); kfree(dev->ep0out_buf); pch_vbus_gpio_free(dev); pch_udc_exit(dev); if (dev->irq_registered) free_irq(pdev->irq, dev); if (dev->base_addr) iounmap(dev->base_addr); if (dev->mem_region) release_mem_region(dev->phys_addr, pci_resource_len(pdev, PCH_UDC_PCI_BAR)); if (dev->active) pci_disable_device(pdev); kfree(dev); pci_set_drvdata(pdev, NULL); } #ifdef CONFIG_PM static int pch_udc_suspend(struct pci_dev *pdev, pm_message_t state) { struct pch_udc_dev *dev = pci_get_drvdata(pdev); pch_udc_disable_interrupts(dev, UDC_DEVINT_MSK); pch_udc_disable_ep_interrupts(dev, UDC_EPINT_MSK_DISABLE_ALL); pci_disable_device(pdev); pci_enable_wake(pdev, PCI_D3hot, 0); if (pci_save_state(pdev)) { dev_err(&pdev->dev, "%s: could not save PCI config state\n", __func__); return -ENOMEM; } pci_set_power_state(pdev, pci_choose_state(pdev, state)); return 0; } static int pch_udc_resume(struct pci_dev *pdev) { int ret; pci_set_power_state(pdev, PCI_D0); pci_restore_state(pdev); ret = pci_enable_device(pdev); if (ret) { dev_err(&pdev->dev, "%s: pci_enable_device failed\n", __func__); return ret; } pci_enable_wake(pdev, PCI_D3hot, 0); return 0; } #else #define pch_udc_suspend NULL #define pch_udc_resume NULL #endif /* CONFIG_PM */ static int pch_udc_probe(struct pci_dev *pdev, const struct pci_device_id *id) { unsigned long resource; unsigned long len; int retval; struct pch_udc_dev *dev; /* init */ dev = kzalloc(sizeof *dev, GFP_KERNEL); if (!dev) { pr_err("%s: no memory for device structure\n", __func__); return -ENOMEM; } /* pci setup */ if (pci_enable_device(pdev) < 0) { kfree(dev); pr_err("%s: pci_enable_device failed\n", __func__); return -ENODEV; } dev->active = 1; pci_set_drvdata(pdev, dev); /* PCI resource allocation */ resource = pci_resource_start(pdev, 1); len = pci_resource_len(pdev, 1); if (!request_mem_region(resource, len, KBUILD_MODNAME)) { dev_err(&pdev->dev, "%s: pci device used already\n", __func__); retval = -EBUSY; goto finished; } dev->phys_addr = resource; dev->mem_region = 1; dev->base_addr = ioremap_nocache(resource, len); if (!dev->base_addr) { pr_err("%s: device memory cannot be mapped\n", __func__); retval = -ENOMEM; goto finished; } if (!pdev->irq) { dev_err(&pdev->dev, "%s: irq not set\n", __func__); retval = -ENODEV; goto finished; } /* initialize the hardware */ if (pch_udc_pcd_init(dev)) { retval = -ENODEV; goto finished; } if (request_irq(pdev->irq, pch_udc_isr, IRQF_SHARED, KBUILD_MODNAME, dev)) { dev_err(&pdev->dev, "%s: request_irq(%d) fail\n", __func__, pdev->irq); retval = -ENODEV; goto finished; } dev->irq = pdev->irq; dev->irq_registered = 1; pci_set_master(pdev); pci_try_set_mwi(pdev); /* device struct setup */ spin_lock_init(&dev->lock); dev->pdev = pdev; dev->gadget.ops = &pch_udc_ops; retval = init_dma_pools(dev); if (retval) goto finished; dev->gadget.name = KBUILD_MODNAME; dev->gadget.max_speed = USB_SPEED_HIGH; /* Put the device in disconnected state till a driver is bound */ pch_udc_set_disconnect(dev); retval = usb_add_gadget_udc_release(&pdev->dev, &dev->gadget, gadget_release); if (retval) goto finished; return 0; finished: pch_udc_remove(pdev); return retval; } static const struct pci_device_id pch_udc_pcidev_id[] = { { PCI_DEVICE(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EG20T_UDC), .class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe, .class_mask = 0xffffffff, }, { PCI_DEVICE(PCI_VENDOR_ID_ROHM, PCI_DEVICE_ID_ML7213_IOH_UDC), .class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe, .class_mask = 0xffffffff, }, { PCI_DEVICE(PCI_VENDOR_ID_ROHM, PCI_DEVICE_ID_ML7831_IOH_UDC), .class = (PCI_CLASS_SERIAL_USB << 8) | 0xfe, .class_mask = 0xffffffff, }, { 0 }, }; MODULE_DEVICE_TABLE(pci, pch_udc_pcidev_id); static struct pci_driver pch_udc_driver = { .name = KBUILD_MODNAME, .id_table = pch_udc_pcidev_id, .probe = pch_udc_probe, .remove = pch_udc_remove, .suspend = pch_udc_suspend, .resume = pch_udc_resume, .shutdown = pch_udc_shutdown, }; module_pci_driver(pch_udc_driver); MODULE_DESCRIPTION("Intel EG20T USB Device Controller"); MODULE_AUTHOR("LAPIS Semiconductor, <[email protected]>"); MODULE_LICENSE("GPL");
cneira/ebpf-backports
linux-3.10.0-514.21.1.el7.x86_64/drivers/usb/gadget/pch_udc.c
C
gpl-2.0
90,352
<h3>Pro Registration</h3> <?php if(isValidKey()): ?> <p class="plugin_is_registered">✓ Easy Testimonials Pro is registered and activated. Thank you!</p> <?php else: ?> <p class="easy_testimonials_not_registered_box">Easy Testimonials Pro is not activated. You will not be able to use the Pro features until you activate the plugin. <br /><br /><a class="button" href="https://goldplugins.com/our-plugins/easy-testimonials-details/upgrade-to-easy-testimonials-pro/?utm_campaign=registration&utm_source=easy_testimonials_settings" target="_blank">Click Here To Upgrade To Pro</a> <br /> <br /><em>When you upgrade, you'll unlock powerful new features including over 75 professionally designed themes, advanced styling options, and a Testimonial Submission form.</em></p> <?php endif; ?> <?php if(!isValidKey()): ?><p>If you have purchased Easy Testimonials Pro, please complete the following fields to activate additional features such as Front-End Testimonial Submission.</p><?php endif; ?> <?php if(!isValidMSKey()): ?> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="easy_t_registered_name">Email Address</label></th> <td><input type="text" name="easy_t_registered_name" id="easy_t_registered_name" value="<?php echo get_option('easy_t_registered_name'); ?>" style="width: 250px" /> <p class="description">This is the e-mail address that you used when you registered the plugin.</p> </td> </tr> </table> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="easy_t_registered_key">API Key</label></th> <td><input type="text" name="easy_t_registered_key" id="easy_t_registered_key" value="<?php echo get_option('easy_t_registered_key'); ?>" style="width: 250px" /> <p class="description">This is the API Key that you received after registering the plugin.</p> </td> </tr> </table> <?php endif; ?>
divakar111/codoid.com
wp-content/plugins/easy-testimonials/include/registration_options.php
PHP
gpl-2.0
1,900
<?php require_once NEWSLETTER_INCLUDES_DIR . '/controls.php'; $controls = new NewsletterControls(); $module = NewsletterEmails::instance(); $email = Newsletter::instance()->get_email((int) $_GET['id'], ARRAY_A); // TNP Composer style wp_enqueue_style('tnpc-style', plugins_url('/tnp-composer/_css/newsletter-builder.css', __FILE__)); if (empty($email)) { echo 'Wrong email identifier'; return; } $email_id = $email['id']; // If there is no action we assume we are enter the first time so we populate the // $nc->data with the editable email fields if (!$controls->is_action()) { $controls->data = $email; if (!empty($email['preferences'])) { $controls->data['preferences'] = explode(',', $email['preferences']); } if (!empty($email['sex'])) { $controls->data['sex'] = explode(',', $email['sex']); } $email_options = unserialize($email['options']); if (is_array($email_options)) { $controls->data = array_merge($controls->data, $email_options); } } if ($controls->is_action('test') || $controls->is_action('save') || $controls->is_action('send') || $controls->is_action('editor')) { // If we were editing with visual editor (==0), we must read the extra <body> content if ($email['editor'] == 0) { // no editing possible, just preview } else { $email['message'] = $controls->data['message']; } $email['message_text'] = $controls->data['message_text']; $email['subject'] = $controls->data['subject']; $email['track'] = $controls->data['track']; $email['private'] = $controls->data['private']; // Builds the extended options $email['options'] = array(); $email['options']['preferences_status'] = $controls->data['preferences_status']; if (isset($controls->data['preferences'])) { $email['options']['preferences'] = $controls->data['preferences']; } if (isset($controls->data['sex'])) { $email['options']['sex'] = $controls->data['sex']; } $email['options']['status'] = $controls->data['status']; $email['options']['preferences_status_operator'] = $controls->data['preferences_status_operator']; $email['options']['wp_users'] = $controls->data['wp_users']; $email['options']['composer'] = true; $email['options'] = serialize($email['options']); if (isset($controls->data['preferences'])) { $email['preferences'] = implode(',', $controls->data['preferences']); } else { $email['preferences'] = ''; } if (isset($controls->data['sex'])) { $email['sex'] = implode(',', $controls->data['sex']); } else { $email['sex'] = ''; } // Before send, we build the query to extract subscriber, so the delivery engine does not // have to worry about the email parameters if ($controls->data['status'] == 'S') { $query = "select * from " . NEWSLETTER_USERS_TABLE . " where status='S'"; } else { $query = "select * from " . NEWSLETTER_USERS_TABLE . " where status='C'"; } if ($controls->data['wp_users'] == '1') { $query .= " and wp_user_id<>0"; } if (isset($controls->data['preferences'])) { $preferences = $controls->data['preferences']; // Not set one of the preferences specified $operator = $controls->data['preferences_status_operator'] == 0 ? ' or ' : ' and '; if ($controls->data['preferences_status'] == 1) { $query .= " and ("; foreach ($preferences as $x) { $query .= "list_" . $x . "=0" . $operator; } $query = substr($query, 0, -4); $query .= ")"; } else { $query .= " and ("; foreach ($preferences as $x) { $query .= "list_" . $x . "=1" . $operator; } $query = substr($query, 0, -4); $query .= ")"; } } $sex = $controls->data['sex']; if (is_array($sex)) { $query .= " and sex in ("; foreach ($sex as $x) { $query .= "'" . $x . "', "; } $query = substr($query, 0, -2); $query .= ")"; } $email['query'] = $query; $email['total'] = $wpdb->get_var(str_replace('*', 'count(*)', $query)); if ($controls->is_action('send') && $controls->data['send_on'] < time()) { $controls->data['send_on'] = time(); } $email['send_on'] = $controls->data['send_on']; if ($controls->is_action('editor')) { $email['editor'] = $email['editor'] == 0 ? 1 : 0; } // Cleans up of tag $email['message'] = NewsletterModule::clean_url_tags($email['message']); $res = Newsletter::instance()->save_email($email); if ($res === false) { $controls->errors = 'Unable to save. Try to deactivate and reactivate the plugin may be the database is out of sync.'; } $controls->data['message'] = $email['message']; $controls->add_message_saved(); } if ($controls->is_action('send')) { // Todo subject check if ($email['subject'] == '') { $controls->errors = __('A subject is required to send', 'newsletter'); } else { $wpdb->update(NEWSLETTER_EMAILS_TABLE, array('status' => 'sending'), array('id' => $email_id)); $email['status'] = 'sending'; $controls->messages .= __('Now sending, see the progress on newsletter list', 'newsletter'); } } if ($controls->is_action('pause')) { $wpdb->update(NEWSLETTER_EMAILS_TABLE, array('status' => 'paused'), array('id' => $email_id)); $email['status'] = 'paused'; } if ($controls->is_action('continue')) { $wpdb->update(NEWSLETTER_EMAILS_TABLE, array('status' => 'sending'), array('id' => $email_id)); $email['status'] = 'sending'; } if ($controls->is_action('abort')) { $wpdb->query("update " . NEWSLETTER_EMAILS_TABLE . " set last_id=0, sent=0, status='new' where id=" . $email_id); $email['status'] = 'new'; $email['sent'] = 0; $email['last_id'] = 0; $controls->messages = __('Delivery definitively cancelled', 'newsletter'); } if ($controls->is_action('test')) { if ($email['subject'] == '') { $controls->errors = __('A subject is required to send', 'newsletter'); } else { $users = NewsletterUsers::instance()->get_test_users(); if (count($users) == 0) { $controls->messages = '<strong>' . __('There are no test subscribers to send to', 'newsletter') . '</strong>'; } else { Newsletter::instance()->send(Newsletter::instance()->get_email($email_id), $users); $controls->messages = __('Test newsletter sent to:', 'newsletter'); foreach ($users as &$user) { $controls->messages .= ' ' . $user->email; } $controls->messages .= '.'; } $controls->messages .= '<br>'; $controls->messages .= '<a href="http://www.thenewsletterplugin.com/plugins/newsletter/subscribers-module#test" target="_blank">' . __('Read more about test subscribers', 'newsletter') . '</a>.'; $controls->messages .= '<br>If diagnostic emails are delivered but test emails are not, try to change the encoding to "base 64" on main configuration panel'; } } //$template = '{message}'; // //if ($email['editor'] == 0) { // $x = strpos($controls->data['message'], '<body'); // // Some time the message in $nc->data is already cleaned up, it depends on action called // if ($x !== false) { // $x = strpos($controls->data['message'], '>', $x); // $y = strpos($controls->data['message'], '</body>'); // // $template = substr($controls->data['message'], 0, $x) . '{message}' . substr($controls->data['message'], $y); // $controls->data['message'] = substr($controls->data['message'], $x + 1, $y - $x - 1); // } //} ?> <div class="wrap" id="tnp-wrap"> <?php include NEWSLETTER_DIR . '/tnp-header.php'; ?> <div id="tnp-heading"> <h2><?php _e('Preview Newsletter', 'newsletter') ?></h2> </div> <div id="tnp-body"> <?php if ($controls->data['status'] == 'S') { echo '<div class="newsletter-message">Warning! This email is configured to be sent to NOT CONFIRMED subscribers.</div>'; } ?> <form method="post" action="" id="newsletter-form"> <?php $controls->init(array('cookie_name' => 'newsletter_emails_edit_tab')); ?> <p class="submit"> <?php $controls->button_back('?page=newsletter_emails_composer&id=' . $email['id']) ?> <?php if ($email['status'] != 'sending') $controls->button_save(); ?> <?php if ($email['status'] != 'sending' && $email['status'] != 'sent') $controls->button_confirm('test', 'Save and test', 'Save and send test emails to test addresses?'); ?> <?php if ($email['status'] == 'new') $controls->button_confirm('send', __('Send', 'newsletter'), __('Start real delivery?', 'newsletter')); ?> <?php if ($email['status'] == 'sending') $controls->button_confirm('pause', __('Pause', 'newsletter'), __('Pause the delivery?', 'newsletter')); ?> <?php if ($email['status'] == 'paused') $controls->button_confirm('continue', __('Continue', 'newsletter'), 'Continue the delivery?'); ?> <?php if ($email['status'] == 'paused') $controls->button_confirm('abort', __('Stop', 'newsletter'), __('This totally stop the delivery, ok?', 'newsletter')); ?> <?php if ($email['status'] != 'sending' && $email['status'] != 'sent') $controls->button_confirm('editor', 'Save and switch to ' . ($email['editor'] == 0 ? 'HTML source editor' : 'Preview'), 'Sure?'); ?> </p> <div id="tabs"> <ul> <li><a href="#tabs-a"><?php _e('Message', 'newsletter') ?></a></li> <li><a href="#tabs-b"><?php _e('Message (textual)', 'newsletter') ?></a></li> <li><a href="#tabs-c"><?php _e('Targeting', 'newsletter') ?></a></li> <li><a href="#tabs-d"><?php _e('Other', 'newsletter') ?></a></li> <li><a href="#tabs-status"><?php _e('Status', 'newsletter') ?></a></li> </ul> <div id="tabs-a" class="tnpc-subject"> <?php $controls->text('subject', 100, 'Subject'); ?> <a href="http://www.thenewsletterplugin.com/plugins/newsletter/newsletter-tags" target="_blank"><?php _e('Available tags', 'newsletter') ?></a> <br><br> <?php if ($email['editor'] == 0) { ?> <div class="tnpc-preview"> <!-- Flat Laptop Browser --> <div class="fake-browser-ui"> <div class="frame"> <span class="bt-1"></span> <span class="bt-2"></span> <span class="bt-3"></span> </div> <iframe id="tnpc-preview-desktop" src="" width="700" height="507" alt="Test" frameborder="0"></iframe> </div> <!-- Flat Mobile Browser --> <div class="fake-mobile-browser-ui"> <iframe id="tnpc-preview-mobile" src="" width="250" height="445" alt="Test" frameborder="0"></iframe> <div class="frame"> <span class="bt-4"></span> </div> </div> </div> <script type="text/javascript"> preview_url = ajaxurl + "?action=tnpc_preview&id=<?php echo $email_id ?>"; jQuery('#tnpc-preview-desktop, #tnpc-preview-mobile').attr("src", preview_url); setTimeout(function () { jQuery('#tnpc-preview-desktop, #tnpc-preview-mobile').contents().find("a").click(function (e) { e.preventDefault(); }) }, 500); </script> <?php } else { // $controls->textarea_preview('message', '100%', '700'); ?> <input id="options-message" name="options[message]" type="hidden"> <div id="tnpc-html-editor"><?php echo htmlentities($email['message']) ?></div> <script src="<?php echo plugins_url('newsletter') ?>/js/ace/ace.js" type="text/javascript" charset="utf-8"></script> <script> var editor = ace.edit("tnpc-html-editor"); editor.setTheme("ace/theme/idle_fingers"); editor.getSession().setMode("ace/mode/html"); var message_input = jQuery('#options-message'); // editor.getSession().setValue(message_input.val()); message_input.val(editor.getSession().getValue()); editor.getSession().on('change', function () { message_input.val(editor.getSession().getValue()); }); </script> <?php } ?> </div> <div id="tabs-b"> <p> This is the textual version of your newsletter. If you empty it, only an HTML version will be sent but is an anti-spam best practice to include a text only version. </p> <?php $controls->textarea_fixed('message_text', '100%', '500'); ?> </div> <div id="tabs-c"> <table class="form-table"> <tr valign="top"> <th><?php _e('Gender', 'newsletter'); ?></th> <td> <?php $controls->checkboxes_group('sex', array('f' => 'Women', 'm' => 'Men', 'n' => 'Not specified')); ?> <p class="description"> Leaving all gender options unselected disable this filter. </p> </td> </tr> <tr valign="top"> <th><?php _e('Lists', 'newsletter'); ?></th> <td> Subscribers with <?php $controls->select('preferences_status_operator', array(0 => 'at least one list', 1 => 'all lists')); ?> <?php $controls->select('preferences_status', array(0 => 'active', 1 => 'not active')); ?> <?php _e('checked below', 'newsletter') ?> <?php $controls->preferences_group('preferences', true); ?> <p class="description"> You can address the newsletter to subscribers who selected at least one of the options or to who has not selected at least one of the options. <a href="http://www.thenewsletterplugin.com/plugins/newsletter/newsletter-preferences" target="_blank">Read more about the "NOT ACTIVE" usage</a>. </p> </td> </tr> <tr valign="top"> <th><?php _e('Status', 'newsletter') ?></th> <td> <?php $controls->select('status', array('C' => __('Confirmed', 'newsletter'), 'S' => __('Not confirmed', 'newsletter'))); ?> <p class="description"> <?php _e('Send to not confirmed subscribers ONLY to ask for confirmation including the {subscription_confirm_url} tag.', 'newsletter') ?> </p> </td> </tr> <tr valign="top"> <th>Only to WordPress users?</th> <td> <?php $controls->yesno('wp_users'); ?> <p class="description"> Limit to the subscribers which are WordPress users as well. </p> </td> </tr> <tr valign="top"> <th> <?php _e('Subscribers count', 'newsletter') ?> </th> <td> <?php echo $wpdb->get_var(str_replace('*', 'count(*)', $email['query'])); ?> <p class="description"> <?php _e('Save to update if on targeting filters have been changed', 'newsletter') ?> </p> </td> </tr> </table> </div> <div id="tabs-d"> <table class="form-table"> <tr valign="top"> <th><?php _e('Keep private', 'newsletter') ?></th> <td> <?php $controls->yesno('private'); ?> <p class="description"> <?php _e('Hide/show from public sent newsletter list.', 'newsletter') ?> <?php _e('Required', 'newsletter') ?>: <a href="" target="_blank">Newsletter Archive Extension</a> </p> </td> </tr> <tr valign="top"> <th><?php _e('Track clicks and message opening', 'newsletter') ?></th> <td> <?php $controls->yesno('track'); ?> </td> </tr> <tr valign="top"> <th><?php _e('Send on', 'newsletter') ?></th> <td> <?php $controls->datetime('send_on'); ?> (now: <?php echo date_i18n(get_option('date_format') . ' ' . get_option('time_format')); ?>) <p class="description"> If the current date and time are wrong, check your timezone on the General WordPress settings. </p> </td> </tr> </table> </div> <div id="tabs-status"> <table class="form-table"> <tr valign="top"> <th>Email status</th> <td><?php echo $email['status']; ?></td> </tr> <tr valign="top"> <th>Messages sent</th> <td><?php echo $email['sent']; ?> of <?php echo $email['total']; ?></td> </tr> <tr valign="top"> <th>Query (tech)</th> <td><?php echo $email['query']; ?></td> </tr> </table> </div> <!-- <div id="tabs-5"> <p>Tags documented below can be used on newsletter body. Some of them can be used on subject as well.</p> <p> Special tags, like the preference setting tag, can be used to highly interact with your subscribers, see the Newsletter Preferences page for examples. </p> -- <dl> <dt>{set_preference_N}</dt> <dd> This tag creates a URL which, once clicked, set the preference numner N on the user profile and redirecting the subscriber to his profile panel. Preferences can be configured on Subscription/Form fields panel. </dd> </dl> </ul> </div> --> </div> </form> </div> <?php include NEWSLETTER_DIR . '/tnp-footer.php'; ?> </div>
fdixon7/oktoberfestma
wp-content/plugins/newsletter/emails/cpreview.php
PHP
gpl-2.0
20,766
<?php /** * Plug-in to render fileupload element * * @package Joomla.Plugin * @subpackage Fabrik.element.fileupload * @copyright Copyright (C) 2005-2013 fabrikar.com - All rights reserved. * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // No direct access defined('_JEXEC') or die('Restricted access'); require_once COM_FABRIK_FRONTEND . '/helpers/image.php'; define("FU_DOWNLOAD_SCRIPT_NONE", '0'); define("FU_DOWNLOAD_SCRIPT_TABLE", '1'); define("FU_DOWNLOAD_SCRIPT_DETAIL", '2'); define("FU_DOWNLOAD_SCRIPT_BOTH", '3'); $logLvl = JLog::ERROR + JLog::EMERGENCY + JLog::WARNING; JLog::addLogger(array('text_file' => 'fabrik.element.fileupload.log.php'), $logLvl, array('com_fabrik.element.fileupload')); /** * Plug-in to render fileupload element * * @package Joomla.Plugin * @subpackage Fabrik.element.fileupload * @since 3.0 */ class PlgFabrik_ElementFileupload extends PlgFabrik_Element { /** * Storage method adaptor object (filesystem/amazon s3) * needs to be public as models have to see it * * @var object */ public $storage = null; /** * Is the element an upload element * * @var bool */ protected $is_upload = true; /** * Does the element store its data in a join table (1:n) * * @return bool */ public function isJoin() { $params = $this->getParams(); if ($params->get('ajax_upload') && (int) $params->get('ajax_max', 4) > 1) { return true; } else { return parent::isJoin(); } } /** * Determines if the data in the form element is used when updating a record * * @param mixed $val Element form data * * @return bool True if ignored on update, default = false */ public function ignoreOnUpdate($val) { $app = JFactory::getApplication(); $input = $app->input; // Check if its a CSV import if it is allow the val to be inserted if ($input->get('task') === 'makeTableFromCSV' || $this->getListModel()->importingCSV) { return false; } $fullName = $this->getFullName(true, false); $params = $this->getParams(); $groupModel = $this->getGroupModel(); $return = false; if ($groupModel->canRepeat()) { /*$$$rob could be the case that we aren't uploading an element by have removed *a repeat group (no join) with a file upload element, in this case processUpload has the correct *file path settings. */ return false; } else { if ($groupModel->isJoin()) { $name = $this->getFullName(true, false); $joinid = $groupModel->getGroup()->join_id; $fileJoinData = JArrayHelper::getValue($_FILES['join']['name'], $joinid, array()); $fdata = JArrayHelper::getValue($fileJoinData, $name); // $fdata = $_FILES['join']['name'][$joinid][$name]; } else { $fdata = @$_FILES[$fullName]['name']; } if ($fdata == '') { if ($this->canCrop() == false) { // Was stopping saving of single ajax upload image // return true; } else { /*if we can crop we need to store the cropped coordinated in the field data * @see onStoreRow(); * above depreciated - not sure what to return here for the moment */ return false; } } else { return false; } } return $return; } /** * Remove the reference to the file from the db table - leaves the file on the server * * @since 3.0.7 * * @return void */ public function onAjax_clearFileReference() { $app = JFactory::getApplication(); $rowId = (array) $app->input->get('rowid'); $this->loadMeForAjax(); $col = $this->getFullName(false, false); $listModel = $this->getListModel(); $listModel->updateRows($rowId, $col, ''); } /** * Get the class to manage the form element * to ensure that the file is loaded only once * * @param array &$srcs Scripts previously loaded * @param string $script Script to load once class has loaded * @param array &$shim Dependant class names to load before loading the class - put in requirejs.config shim * * @return void */ public function formJavascriptClass(&$srcs, $script = '', &$shim = array()) { $s = new stdClass; $s->deps = array('fab/element'); $params = $this->getParams(); if ($params->get('ajax_upload')) { $runtimes = $params->get('ajax_runtime', 'html5'); $folder = 'element/fileupload/lib/plupload/js/'; $plupShim = new stdClass; $plupShim->deps = array($folder . 'plupload'); $s->deps[] = $folder . 'plupload'; if (strstr($runtimes, 'html5')) { $s->deps[] = $folder . 'plupload.html5'; $shim[$folder . 'plupload.html5'] = $plupShim; } if (strstr($runtimes, 'html4')) { $s->deps[] = $folder . 'plupload.html4'; $shim[$folder . 'plupload.html4'] = $plupShim; } if (strstr($runtimes, 'flash')) { $s->deps[] = $folder . 'plupload.flash'; $shim[$folder . 'plupload.flash'] = $plupShim; } if (strstr($runtimes, 'silverlight')) { $s->deps[] = $folder . 'plupload.silverlight'; $shim[$folder . 'plupload.silverlight'] = $plupShim; } if (strstr($runtimes, 'browserplus')) { $s->deps[] = $folder . 'plupload.browserplus'; $shim[$folder . 'plupload.browserplus'] = $plupShim; } } if (array_key_exists('element/fileupload/fileupload', $shim) && isset($shim['element/fileupload/fileupload']->deps)) { $shim['element/fileupload/fileupload']->deps = array_values(array_unique(array_merge($shim['element/fileupload/fileupload']->deps, $s->deps))); } else { $shim['element/fileupload/fileupload'] = $s; } if ($this->requiresSlideshow()) { FabrikHelperHTML::slideshow(); } parent::formJavascriptClass($srcs, $script, $shim); // $$$ hugh - added this, and some logic in the view, so we will get called on a per-element basis return false; } /** * Returns javascript which creates an instance of the class defined in formJavascriptClass() * * @param int $repeatCounter Repeat group counter * * @return array */ public function elementJavascript($repeatCounter) { $params = $this->getParams(); $id = $this->getHTMLId($repeatCounter); FabrikHelperHTML::mcl(); $j3 = FabrikWorker::j3(); $element = $this->getElement(); $paramsKey = $this->getFullName(true, false); $paramsKey = Fabrikstring::rtrimword($paramsKey, $this->getElement()->name); $paramsKey .= 'params'; $formData = $this->getFormModel()->data; $imgParams = JArrayHelper::getValue($formData, $paramsKey); // Above paramsKey stuff looks really wonky - lets test if null and use something which seems to build the correct key if (is_null($imgParams)) { $paramsKey = $this->getFullName(true, false) . '___params'; $imgParams = JArrayHelper::getValue($formData, $paramsKey); } $value = $this->getValue(array(), $repeatCounter); $value = is_array($value) ? $value : FabrikWorker::JSONtoData($value, true); $value = $this->checkForSingleCropValue($value); // Repeat_image_repeat_image___params $rawvalues = count($value) == 0 ? array() : array_fill(0, count($value), 0); $fdata = $this->getFormModel()->data; $rawkey = $this->getFullName(true, false) . '_raw'; $rawvalues = JArrayHelper::getValue($fdata, $rawkey, $rawvalues); if (!is_array($rawvalues)) { $rawvalues = explode(GROUPSPLITTER, $rawvalues); } else { /* * $$$ hugh - nasty hack for now, if repeat group with simple * uploads, all raw values are in an array in $rawvalues[0] */ if (is_array(JArrayHelper::getValue($rawvalues, 0))) { $rawvalues = $rawvalues[0]; } } if (!is_array($imgParams)) { $imgParams = explode(GROUPSPLITTER, $imgParams); } $oFiles = new stdClass; $iCounter = 0; // Failed validation for ajax upload elements if (is_array($value) && array_key_exists('id', $value)) { $imgParams = array_values($value['crop']); $value = array_keys($value['id']); $rawvalues = $value; } for ($x = 0; $x < count($value); $x++) { if (is_array($value)) { if (array_key_exists($x, $value) && $value[$x] !== '') { if (is_array($value[$x])) { // From failed validation foreach ($value[$x]['id'] as $tkey => $parts) { $o = new stdClass; $o->id = 'alreadyuploaded_' . $element->id . '_' . $iCounter; $o->name = array_pop(explode(DIRECTORY_SEPARATOR, $tkey)); $o->path = $tkey; if ($fileinfo = $this->getStorage()->getFileInfo($o->path)) { $o->size = $fileinfo['filesize']; } else { $o->size = 'unknown'; } $o->type = strstr($fileinfo['mime_type'], 'image/') ? 'image' : 'file'; $o->url = $this->getStorage()->pathToURL($tkey); $o->recordid = $rawvalues[$x]; $o->params = json_decode($value[$x]['crop'][$tkey]); $oFiles->$iCounter = $o; $iCounter++; } } else { if (is_object($value[$x])) { // Single crop image (not sure about the 0 settings in here) $parts = explode(DIRECTORY_SEPARATOR, $value[$x]->file); $o = new stdClass; $o->id = 'alreadyuploaded_' . $element->id . '_0'; $o->name = array_pop($parts); $o->path = $value[$x]->file; if ($fileinfo = $this->getStorage()->getFileInfo($o->path)) { $o->size = $fileinfo['filesize']; } else { $o->size = 'unknown'; } $o->type = strstr($fileinfo['mime_type'], 'image/') ? 'image' : 'file'; $o->url = $this->getStorage()->pathToURL($value[$x]->file); $o->recordid = 0; $o->params = json_decode($value[$x]->params); $oFiles->$iCounter = $o; $iCounter++; } else { $parts = explode('/', $value[$x]); $o = new stdClass; $o->id = 'alreadyuploaded_' . $element->id . '_' . $rawvalues[$x]; $o->name = array_pop($parts); $o->path = $value[$x]; if ($fileinfo = $this->getStorage()->getFileInfo($o->path)) { $o->size = $fileinfo['filesize']; } else { $o->size = 'unknown'; } $o->type = strstr($fileinfo['mime_type'], 'image/') ? 'image' : 'file'; $o->url = $this->getStorage()->pathToURL($value[$x]); $o->recordid = $rawvalues[$x]; $o->params = json_decode(JArrayHelper::getValue($imgParams, $x, '{}')); $oFiles->$iCounter = $o; $iCounter++; } } } } } $opts = $this->getElementJSOptions($repeatCounter); $opts->id = $this->getId(); if ($this->isJoin()) { $opts->isJoin = true; $opts->joinId = $this->getJoinModel()->getJoin()->id; } $opts->elid = $element->id; $opts->defaultImage = $params->get('default_image'); $opts->folderSelect = $params->get('upload_allow_folderselect', 0); $opts->dir = JPATH_SITE . '/' . $params->get('ul_directory'); $opts->ajax_upload = (bool) $params->get('ajax_upload', false); $opts->ajax_runtime = $params->get('ajax_runtime', 'html5'); $opts->ajax_silverlight_path = COM_FABRIK_LIVESITE . 'plugins/fabrik_element/fileupload/lib/plupload/js/plupload.flash.swf'; $opts->ajax_flash_path = COM_FABRIK_LIVESITE . 'plugins/fabrik_element/fileupload/lib/plupload/js/plupload.flash.swf'; $opts->max_file_size = (float) $params->get('ul_max_file_size'); $opts->ajax_chunk_size = (int) $params->get('ajax_chunk_size', 0); $opts->filters = $this->ajaxFileFilters(); $opts->crop = $this->canCrop(); $opts->canvasSupport = FabrikHelperHTML::canvasSupport(); $opts->elementName = $this->getFullName(); $opts->cropwidth = (int) $params->get('fileupload_crop_width'); $opts->cropheight = (int) $params->get('fileupload_crop_height'); $opts->ajax_max = (int) $params->get('ajax_max', 4); $opts->dragdrop = true; $icon = $j3 ? 'picture' : 'image.png'; $resize = $j3 ? 'expand-2' : 'resize.png'; $opts->previewButton = FabrikHelperHTML::image($icon, 'form', @$this->tmpl, array('alt' => FText::_('PLG_ELEMENT_FILEUPLOAD_VIEW'))); $opts->resizeButton = FabrikHelperHTML::image($resize, 'form', @$this->tmpl, array('alt' => FText::_('PLG_ELEMENT_FILEUPLOAD_RESIZE'))); $opts->files = $oFiles; $opts->winWidth = (int) $params->get('win_width', 400); $opts->winHeight = (int) $params->get('win_height', 400); $opts->elementShortName = $element->name; $opts->listName = $this->getListModel()->getTable()->db_table_name; JText::script('PLG_ELEMENT_FILEUPLOAD_MAX_UPLOAD_REACHED'); JText::script('PLG_ELEMENT_FILEUPLOAD_DRAG_FILES_HERE'); JText::script('PLG_ELEMENT_FILEUPLOAD_UPLOAD_ALL_FILES'); JText::script('PLG_ELEMENT_FILEUPLOAD_RESIZE'); JText::script('PLG_ELEMENT_FILEUPLOAD_CROP_AND_SCALE'); JText::script('PLG_ELEMENT_FILEUPLOAD_PREVIEW'); JText::script('PLG_ELEMENT_FILEUPLOAD_CONFIRM_SOFT_DELETE'); JText::script('PLG_ELEMENT_FILEUPLOAD_CONFIRM_HARD_DELETE'); JText::script('PLG_ELEMENT_FILEUPLOAD_FILE_TOO_LARGE_SHORT'); return array('FbFileUpload', $id, $opts); } /** * Create Plupload js options for file extension filters * * @return array */ protected function ajaxFileFilters() { $return = new stdClass; $exts = $this->_getAllowedExtension(); foreach ($exts as &$ext) { $ext = trim(str_replace('.', '', $ext)); } $return->title = 'Allowed files'; $return->extensions = implode(',', $exts); return array($return); } /** * Can the plug-in crop. Based on parameters and browser check (IE8 or less has no canvas support) * * @since 3.0.9 * * @return boolean */ protected function canCrop() { $params = $this->getParams(); if (!FabrikHelperHTML::canvasSupport()) { return false; } return (bool) $params->get('fileupload_crop', 0); } /** * Shows the data formatted for the list view * * @param string $data Elements data * @param stdClass &$thisRow All the data in the lists current row * * @return string Formatted value */ public function renderListData($data, stdClass &$thisRow) { $data = FabrikWorker::JSONtoData($data, true); $params = $this->getParams(); $rendered = ''; static $id_num = 0; // $$$ hugh - have to run through rendering even if data is empty, in case default image is being used. if (empty($data)) { $data[0] = $this->_renderListData('', $thisRow, 0); } else { /** * 2 == 'slideshow' ('carousel'), so don't run individually through _renderListData(), instead * build whatever carousel the data type uses, which will depend on data type. Like simple image carousel, * or MP3 player with playlist, etc. */ if ($params->get('fu_show_image_in_table', '0') == '2') { $id = $this->getHTMLId($id_num) . '_' . $id_num; $id_num++; $rendered = $this->buildCarousel($id, $data, $params, $thisRow); } else { for ($i = 0; $i < count($data); $i++) { $data[$i] = $this->_renderListData($data[$i], $thisRow, $i); } } } if ($params->get('fu_show_image_in_table', '0') != '2') { $data = json_encode($data); $rendered = parent::renderListData($data, $thisRow); } return $rendered; } /** * Shows the data formatted for the CSV export view * * @param string $data Element data * @param object &$thisRow All the data in the tables current row * * @return string Formatted value */ public function renderListData_csv($data, &$thisRow) { $data = FabrikWorker::JSONtoData($data, true); $params = $this->getParams(); $format = $params->get('ul_export_encode_csv', 'base64'); $raw = $this->getFullName(true, false) . '_raw'; if ($params->get('ajax_upload') && $params->get('ajax_max', 4) == 1) { // Single ajax upload if (is_object($data)) { $data = $data->file; } else { if ($data !== '') { $singleCropImg = JArrayHelper::getValue($data, 0); if (empty($singleCropImg)) { $data = array(); } else { $data = (array) $singleCropImg->file; } } } } foreach ($data as &$d) { $d = $this->encodeFile($d, $format); } // Fix \"" in json encoded string - csv clever enough to treat "" as a quote inside a "string value" $data = str_replace('\"', '"', $data); if ($this->isJoin()) { // Multiple file uploads - raw data should be the file paths. $thisRow->$raw = json_encode($data); } else { $thisRow->$raw = str_replace('\"', '"', $thisRow->$raw); } return implode(GROUPSPLITTER, $data); } /** * Shows the data formatted for the JSON export view * * @param string $data file name * @param string $rows all the data in the tables current row * * @return string formatted value */ public function renderListData_json($data, $rows) { $data = explode(GROUPSPLITTER, $data); $params = $this->getParams(); $format = $params->get('ul_export_encode_json', 'base64'); foreach ($data as &$d) { $d = $this->encodeFile($d, $format); } return implode(GROUPSPLITTER, $data); } /** * Encodes the file * * @param string $file Relative file path * @param mixed $format Encode the file full|url|base64|raw|relative * * @return string Encoded file for export */ protected function encodeFile($file, $format = 'relative') { $path = JPATH_SITE . '/' . $file; if (!JFile::exists($path)) { return $file; } switch ($format) { case 'full': return $path; break; case 'url': return COM_FABRIK_LIVESITE . str_replace('\\', '/', $file); break; case 'base64': return base64_encode(file_get_contents($path)); break; case 'raw': return file_get_contents($path); break; case 'relative': return $file; break; } } /** * Element plugin specific method for setting unecrypted values back into post data * * @param array &$post Data passed by ref * @param string $key Key * @param string $data Elements unencrypted data * * @return void */ public function setValuesFromEncryt(&$post, $key, $data) { if ($this->isJoin()) { $data = FabrikWorker::JSONtoData($data, true); } parent::setValuesFromEncryt($post, $key, $data); } /** * Called by form model to build an array of values to encrypt * * @param array &$values Previously encrypted values * @param array $data Form data * @param int $c Repeat group counter * * @return void */ public function getValuesToEncrypt(&$values, $data, $c) { $name = $this->getFullName(true, false); // Needs to be set to raw = false for fileupload $opts = array('raw' => false); $group = $this->getGroup(); if ($group->canRepeat()) { if (!array_key_exists($name, $values)) { $values[$name]['data'] = array(); } $values[$name]['data'][$c] = $this->getValue($data, $c, $opts); } else { $values[$name]['data'] = $this->getValue($data, $c, $opts); } } /** * Examine the file being displayed and load in the corresponding * class that deals with its display * * @param string $file File * * @return object Element renderer */ protected function loadElement($file) { $ext = JString::strtolower(JFile::getExt($file)); if (JFile::exists(JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/custom/' . $ext . '.php')) { require JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/custom/' . $ext . '.php'; } elseif (JFile::exists(JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/' . $ext . '.php')) { require JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/' . $ext . '.php'; } else { // Default down to allvideos content plugin if (in_array($ext, array('flv', '3gp', 'divx'))) { require JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/allvideos.php'; } else { require JPATH_ROOT . '/plugins/fabrik_element/fileupload/element/default.php'; } } return $render; } /** * Display the file in the list * * @param string $data Current cell data * @param array &$thisRow Current row data * @param int $i Repeat group count * * @return string */ protected function _renderListData($data, &$thisRow, $i = 0) { $app = JFactory::getApplication(); $package = $app->getUserState('com_fabrik.package', 'fabrik'); $this->_repeatGroupCounter = $i; $element = $this->getElement(); $params = $this->getParams(); // $$$ hugh - added 'skip_check' param, as the exists() check in s3 // storage adaptor can add a second or two per file, per row to table render time. $skip_exists_check = (int) $params->get('fileupload_skip_check', '0'); if ($params->get('ajax_upload') && $params->get('ajax_max', 4) == 1) { // Not sure but after update from 2.1 to 3 for podion data was an object if (is_object($data)) { $data = $data->file; } else { if ($data !== '') { $singleCropImg = json_decode($data); if (empty($singleCropImg)) { $data = ''; } else { $singleCropImg = $singleCropImg[0]; $data = $singleCropImg->file; } } } } $data = FabrikWorker::JSONtoData($data); if (is_array($data) && !empty($data)) { // Crop stuff needs to be removed from data to get correct file path $data = $data[0]; } $storage = $this->getStorage(); $use_download_script = $params->get('fu_use_download_script', '0'); if ($use_download_script == FU_DOWNLOAD_SCRIPT_TABLE || $use_download_script == FU_DOWNLOAD_SCRIPT_BOTH) { if (empty($data) || !$storage->exists(COM_FABRIK_BASE . $data)) { return ''; } $aclEl = $this->getFormModel()->getElement($params->get('fu_download_acl', ''), true); if (!empty($aclEl)) { $aclEl = $aclEl->getFullName(); $aclElraw = $aclEl . '_raw'; $user = JFactory::getUser(); $groups = $user->getAuthorisedViewLevels(); $canDownload = in_array($thisRow->$aclElraw, $groups); if (!$canDownload) { $img = $params->get('fu_download_noaccess_image'); $noImg = ($img == '' || !JFile::exists(JPATH_ROOT . '/media/com_fabrik/images/' . $img)); $aClass = $noImg ? 'class="btn button"' : ''; $a = $params->get('fu_download_noaccess_url') == '' ? '' : '<a href="' . $params->get('fu_download_noaccess_url') . '" ' . $aClass . '>'; $a2 = $params->get('fu_download_noaccess_url') == '' ? '' : '</a>'; if ($noImg) { $img = '<i class="icon-circle-arrow-right"></i> ' . FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_PERMISSION'); } else { $img = '<img src="' . COM_FABRIK_LIVESITE . 'media/com_fabrik/images/' . $img . '" alt="' . FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_PERMISSION') . '" />'; } return $a . $img . $a2; } } $formModel = $this->getForm(); $formid = $formModel->getId(); $rowid = $thisRow->__pk_val; $elementid = $this->getId(); $title = ''; if ($params->get('fu_title_element') == '') { $title_name = $this->getFullName(true, false) . '__title'; } else { $title_name = str_replace('.', '___', $params->get('fu_title_element')); } if (array_key_exists($title_name, $thisRow)) { if (!empty($thisRow->$title_name)) { $title = $thisRow->$title_name; $title = FabrikWorker::JSONtoData($title, true); $title = $title[$i]; } } $downloadImg = $params->get('fu_download_access_image'); if ($downloadImg !== '' && JFile::exists(JPATH_ROOT . '/media/com_fabrik/images/' . $downloadImg)) { $aClass = ''; $title = '<img src="' . COM_FABRIK_LIVESITE . 'media/com_fabrik/images/' . $downloadImg . '" alt="' . $title . '" />'; } else { $aClass = 'class="btn btn-primary button"'; $title = '<i class="icon-download icon-white"></i> ' . FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD'); } $link = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $package . '&amp;task=plugin.pluginAjax&amp;plugin=fileupload&amp;method=ajax_download&amp;format=raw&amp;element_id=' . $elementid . '&amp;formid=' . $formid . '&amp;rowid=' . $rowid . '&amp;repeatcount=' . $i; $url = '<a href="' . $link . '"' . $aClass . '>' . $title . '</a>'; return $url; } if ($params->get('fu_show_image_in_table') == '0') { $render = $this->loadElement('default'); } else { $render = $this->loadElement($data); } if (empty($data) || (!$skip_exists_check && !$storage->exists($data))) { $render->output = ''; } else { $render->renderListData($this, $params, $data, $thisRow); } if ($render->output == '' && $params->get('default_image') != '') { $defaultURL = $storage->getFileUrl(str_replace(COM_FABRIK_BASE, '', $params->get('default_image'))); $render->output = '<img src="' . $defaultURL . '" alt="image" />'; } else { /* * If a static 'icon file' has been specified, we need to call the main * element model replaceWithIcons() to make it happen. */ if ($params->get('icon_file', '') !== '') { $listModel = $this->getListModel(); $render->output = $this->replaceWithIcons($render->output, 'list', $listModel->getTmpl()); } } return $render->output; } /** * Do we need to include the lightbox js code * * @return bool */ public function requiresLightBox() { return true; } /** * Do we need to include the slideshow js code * * @return bool */ public function requiresSlideshow() { /* * $$$ - testing slideshow, @TODO finish this! Check for view type */ $params = $this->getParams(); return $params->get('fu_show_image_in_table', '0') === '2' || $params->get('fu_show_image', '0') === '3'; } /** * Manipulates posted form data for insertion into database * * @param mixed $val This elements posted form data * @param array $data Posted form data * * @return mixed */ public function storeDatabaseFormat($val, $data) { // Val already contains group splitter from processUpload() code return $val; } /** * Checks the posted form data against elements INTERNAL validation rule * e.g. file upload size / type * * @param string $data Elements data * @param int $repeatCounter Repeat group counter * * @return bool True if passes / false if fails validation */ public function validate($data = array(), $repeatCounter = 0) { $app = JFactory::getApplication(); $input = $app->input; $params = $this->getParams(); $this->_validationErr = ''; $errors = array(); $name = $this->getFullName(true, false); $ok = true; $files = $input->files->get($name, array(), 'array'); if (array_key_exists($repeatCounter, $files)) { $file = JArrayHelper::getValue($files, $repeatCounter); } else { // Single upload $file = $files; } // Perhaps an ajax upload? In any event $file empty was giving errors with upload element in multipage form. if (!array_key_exists('name', $file)) { return true; } $fileName = $file['name']; $fileSize = $file['size']; if (!$this->_fileUploadFileTypeOK($fileName)) { $errors[] = FText::_('PLG_ELEMENT_FILEUPLOAD_FILE_TYPE_NOT_ALLOWED'); $ok = false; } if (!$this->_fileUploadSizeOK($fileSize)) { $ok = false; $size = $fileSize / 1000; $errors[] = JText::sprintf('PLG_ELEMENT_FILEUPLOAD_FILE_TOO_LARGE', $params->get('ul_max_file_size'), $size); } /** * @FIXME - need to check for Amazon S3 storage? */ $filepath = $this->_getFilePath($repeatCounter); jimport('joomla.filesystem.file'); if (JFile::exists($filepath)) { if ($params->get('ul_file_increment', 0) == 0) { $errors[] = FText::_('PLG_ELEMENT_FILEUPLOAD_EXISTING_FILE_NAME'); $ok = false; } } $this->validationError = implode('<br />', $errors); return $ok; } /** * Get an array of allowed file extensions * * @return array */ protected function _getAllowedExtension() { $params = $this->getParams(); $allowedFiles = $params->get('ul_file_types'); if ($allowedFiles != '') { // $$$ hugh - strip spaces, as folk often do ".foo, .bar" preg_replace('#\s+#', '', $allowedFiles); $aFileTypes = explode(",", $allowedFiles); } else { $mediaparams = JComponentHelper::getParams('com_media'); $aFileTypes = explode(',', $mediaparams->get('upload_extensions')); } return $aFileTypes; } /** * This checks the uploaded file type against the csv specified in the upload * element * * @param string $myFileName Filename * * @return bool True if upload file type ok */ protected function _fileUploadFileTypeOK($myFileName) { $aFileTypes = $this->_getAllowedExtension(); if ($myFileName == '') { return true; } $curr_f_ext = JString::strtolower(JFile::getExt($myFileName)); array_walk($aFileTypes, create_function('&$v', '$v = JString::strtolower($v);')); if (in_array($curr_f_ext, $aFileTypes) || in_array("." . $curr_f_ext, $aFileTypes)) { return true; } return false; } /** * This checks that the fileupload size is not greater than that specified in * the upload element * * @param string $myFileSize File size * * @return bool True if upload file type ok */ protected function _fileUploadSizeOK($myFileSize) { $params = $this->getParams(); $max_size = $params->get('ul_max_file_size') * 1000; if ($myFileSize <= $max_size) { return true; } return false; } /** * if we are using plupload but not with crop * * @param string $name Element * * @return bool If processed or not */ protected function processAjaxUploads($name) { $app = JFactory::getApplication(); $input = $app->input; $params = $this->getParams(); if ($this->canCrop() == false && $input->get('task') !== 'pluginAjax' && $params->get('ajax_upload') == true) { $filter = JFilterInput::getInstance(); $post = $filter->clean($_POST, 'array'); $raw = $this->getValue($post); if ($raw == '') { return true; } if (empty($raw)) { return true; } // $$$ hugh - for some reason, we're now getting $raw[] with a single, uninitialized entry back // from getvalue() when no files are uploaded if (count($raw) == 1 && array_key_exists(0, $raw) && empty($raw[0])) { return true; } $crop = (array) JArrayHelper::getValue($raw, 'crop'); $ids = (array) JArrayHelper::getValue($raw, 'id'); $ids = array_values($ids); $saveParams = array(); $files = array_keys($crop); $groupModel = $this->getGroup(); $formModel = $this->getFormModel(); $isjoin = ($groupModel->isJoin() || $this->isJoin()); if ($isjoin) { if (!$groupModel->canRepeat() && !$this->isJoin()) { $files = $files[0]; } $joinid = $groupModel->getGroup()->join_id; if ($this->isJoin()) { $joinid = $this->getJoinModel()->getJoin()->id; } $j = $this->getJoinModel()->getJoin()->table_join; $joinsid = $j . '___id'; $joinsparam = $j . '___params'; $name = $this->getFullName(true, false); $formModel->updateFormData($name, $files, true); $formModel->updateFormData($joinsid, $ids, true); $formModel->updateFormData($joinsparam, $saveParams, true); } else { // Only one file $store = array(); for ($i = 0; $i < count($files); $i++) { $o = new stdClass; $o->file = $files[$i]; $o->params = $crop[$files[$i]]; $store[] = $o; } $store = json_encode($store); $formModel->updateFormData($name . '_raw', $store); $formModel->updateFormData($name, $store); } return true; } else { return false; } } /** * If an image has been uploaded with ajax upload then we may need to crop it * Since 3.0.7 crop data is posted as base64 encoded info from the actual canvas element - much simpler and more accurate cropping * * @param string $name Element * * @return bool If processed or not */ protected function crop($name) { $app = JFactory::getApplication(); $input = $app->input; $params = $this->getParams(); if ($this->canCrop() == true && $input->get('task') !== 'pluginAjax') { $filter = JFilterInput::getInstance(); $post = $filter->clean($_POST, 'array'); $raw = JArrayHelper::getValue($post, $name . '_raw', array()); if (!$this->canUse()) { // Ensure readonly elements not overwritten return true; } if ($this->getValue($post) != 'Array,Array') { $raw = $this->getValue($post); // $$$ rob 26/07/2012 inline edit producing a string value for $raw on save if ($raw == '' || empty($raw) || is_string($raw)) { return true; } if (array_key_exists(0, $raw)) { $crop = (array) JArrayHelper::getValue($raw[0], 'crop'); $ids = (array) JArrayHelper::getValue($raw[0], 'id'); $cropData = (array) JArrayHelper::getValue($raw[0], 'cropdata'); } else { // Single uploaded image. $crop = (array) JArrayHelper::getValue($raw, 'crop'); $ids = (array) JArrayHelper::getValue($raw, 'id'); $cropData = (array) JArrayHelper::getValue($raw, 'cropdata'); } } else { // Single image $crop = (array) JArrayHelper::getValue($raw, 'crop'); $ids = (array) JArrayHelper::getValue($raw, 'id'); $cropData = (array) JArrayHelper::getValue($raw, 'cropdata'); } if ($raw == '') { return true; } $ids = array_values($ids); $saveParams = array(); $files = array_keys($crop); $storage = $this->getStorage(); $oImage = FabimageHelper::loadLib($params->get('image_library')); $oImage->setStorage($storage); $fileCounter = 0; foreach ($crop as $filepath => $json) { $imgData = $cropData[$filepath]; $imgData = substr($imgData, strpos($imgData, ',') + 1); // Need to decode before saving since the data we received is already base64 encoded $imgData = base64_decode($imgData); $coords = json_decode(urldecode($json)); $saveParams[] = $json; // @todo allow uploading into front end designated folders? $myFileDir = ''; $cropPath = $storage->clean(JPATH_SITE . '/' . $params->get('fileupload_crop_dir') . '/' . $myFileDir . '/', false); $w = new FabrikWorker; $cropPath = $w->parseMessageForPlaceHolder($cropPath); if ($cropPath != '') { if (!$storage->folderExists($cropPath)) { if (!$storage->createFolder($cropPath)) { $this->setError(21, "Could not make dir $cropPath "); continue; } } } $filepath = $storage->clean(JPATH_SITE . '/' . $filepath); $fileURL = $storage->getFileUrl(str_replace(COM_FABRIK_BASE, '', $filepath)); $destCropFile = $storage->_getCropped($fileURL); $destCropFile = $storage->urlToPath($destCropFile); $destCropFile = $storage->clean($destCropFile); if (!JFile::exists($filepath)) { unset($files[$fileCounter]); $fileCounter++; continue; } $fileCounter++; if ($imgData != '') { if (!$storage->write($destCropFile, $imgData)) { throw new RuntimeException('Couldn\'t write image, ' . $destCropFile, 500); } } $storage->setPermissions($destCropFile); } $groupModel = $this->getGroup(); $isjoin = ($groupModel->isJoin() || $this->isJoin()); $formModel = $this->getFormModel(); if ($isjoin) { if (!$groupModel->canRepeat() && !$this->isJoin()) { $files = $files[0]; } $joinid = $groupModel->getGroup()->join_id; if ($this->isJoin()) { $joinid = $this->getJoinModel()->getJoin()->id; } $name = $this->getFullName(true, false); if ($groupModel->isJoin()) { $j = $this->getJoinModel()->getJoin()->table_join; } else { $j = $name; } $joinsid = $j . '___id'; $joinsparam = $j . '___params'; $formModel->updateFormData($name, $files); $formModel->updateFormData($name . '_raw', $files); $formModel->updateFormData($joinsid, $ids); $formModel->updateFormData($joinsid . '_raw', $ids); $formModel->updateFormData($joinsparam, $saveParams); $formModel->updateFormData($joinsparam . '_raw', $saveParams); } else { // Only one file $store = array(); for ($i = 0; $i < count($files); $i++) { $o = new stdClass; $o->file = $files[$i]; $o->params = $saveParams[$i]; $store[] = $o; } $store = json_encode($store); $formModel->updateFormData($name . '_raw', $store); $formModel->updateFormData($name, $store); } return true; } else { return false; } } /** * OPTIONAL * * @return void */ public function processUpload() { $app = JFactory::getApplication(); $input = $app->input; $params = $this->getParams(); $groupModel = $this->getGroup(); $formModel = $this->getFormModel(); $origData = $formModel->getOrigData(); $name = $this->getFullName(true, false); $myFileDirs = $input->get($name, array(), 'array'); if (!$this->canUse()) { // If the user can't use the plugin no point processing an non-existant upload return; } if ($this->processAjaxUploads($name)) { // Stops form data being updated with blank data. return; } if ($input->getInt('fabrik_ajax') == 1) { // Inline edit for example no $_FILE data sent return; } /* If we've turned on crop but not set ajax upload then the cropping wont work so we shouldn't return * otherwise no standard image processed */ if ($this->crop($name) && $params->get('ajax_upload')) { // Stops form data being updated with blank data. return; } $files = array(); $deletedImages = $input->get('fabrik_fileupload_deletedfile', array(), 'array'); $gid = $groupModel->getId(); $deletedImages = JArrayHelper::getValue($deletedImages, $gid, array()); $imagesToKeep = array(); for ($j = 0; $j < count($origData); $j++) { foreach ($origData[$j] as $key => $val) { if ($key == $name && !empty($val)) { if (in_array($val, $deletedImages)) { unset($origData[$j]->$key); } else { $imagesToKeep[$j] = $origData[$j]->$key; } break; } } } $fdata = $_FILES[$name]['name']; /* * $$$ hugh - monkey patch to get simple upload working again after this commit: * https://github.com/Fabrik/fabrik/commit/5970a1845929c494c193b9227c32c983ff30fede * I don't think $fdata is ever going to be an array, after the above changes, but for now * I'm just patching round it. Rob will fix it properly with his hammer. :) * UPDATE - yes, it will be an array, if we have a repeat group with simple uploads. * Continuing to hack around with this! */ if (is_array($fdata)) { foreach ($fdata as $i => $f) { $myFileDir = JArrayHelper::getValue($myFileDirs, $i, ''); $file = array('name' => $_FILES[$name]['name'][$i], 'type' => $_FILES[$name]['type'][$i], 'tmp_name' => $_FILES[$name]['tmp_name'][$i], 'error' => $_FILES[$name]['error'][$i], 'size' => $_FILES[$name]['size'][$i]); if ($file['name'] != '') { $files[$i] = $this->_processIndUpload($file, $myFileDir, $i); } else { if (array_key_exists($i, $imagesToKeep)) { $files[$i] = $imagesToKeep[$i]; } } } foreach ($imagesToKeep as $k => $v) { if (!array_key_exists($k, $files)) { $files[$k] = $v; } } foreach ($files as &$f) { $f = str_replace('\\', '/', $f); } if ($params->get('upload_delete_image', false)) { foreach ($deletedImages as $filename) { $this->deleteFile($filename); } } $formModel->updateFormData($name . '_raw', $files); $formModel->updateFormData($name, $files); } else { $myFileDir = JArrayHelper::getValue($myFileDirs, 0, ''); $file = array('name' => $_FILES[$name]['name'], 'type' => $_FILES[$name]['type'], 'tmp_name' => $_FILES[$name]['tmp_name'], 'error' => $_FILES[$name]['error'], 'size' => $_FILES[$name]['size']); if ($file['name'] != '') { $files[0] = $this->_processIndUpload($file, $myFileDir); } else { $files[0] = $imagesToKeep[0]; } foreach ($imagesToKeep as $k => $v) { if (!array_key_exists($k, $files)) { $files[$k] = $v; } } foreach ($files as &$f) { $f = str_replace('\\', '/', $f); } if ($params->get('upload_delete_image', false)) { foreach ($deletedImages as $filename) { $this->deleteFile($filename); } } /* * Update form model with file data * * $$$ hugh - another monkey patch just to get simple upload going again * We don't ever want to actually end up with the old GROUPSPLITTER arrangement, * but if we've got repeat groups on the form, we'll have multiple entries in * $files for the same single, simple upload. So boil it down with an array_unique() * HORRIBLE hack .. really need to fix this whole chunk of code. */ /* $formModel->updateFormData($name . '_raw', $files); $formModel->updateFormData($name, $files); */ $files = array_unique($files); $strfiles = implode(GROUPSPLITTER, $files); $formModel->updateFormData($name . '_raw', $strfiles); $formModel->updateFormData($name, $strfiles); } } /** * Delete the file * * @param string $filename Path to file (not including JPATH) * * @return void */ protected function deleteFile($filename) { $storage = $this->getStorage(); $user = JFactory::getUser(); $file = $storage->clean(JPATH_SITE . '/' . $filename); $thumb = $storage->clean($storage->_getThumb($filename)); $cropped = $storage->clean($storage->_getCropped($filename)); $logMsg = 'Delete files: ' . $file . ' , ' . $thumb . ', ' . $cropped . '; user = ' . $user->get('id'); JLog::add($logMsg, JLog::WARNING, 'com_fabrik.element.fileupload'); if ($storage->exists($file)) { $storage->delete($file); } if ($storage->exists($thumb)) { $storage->delete($thumb); } else { if ($storage->exists(JPATH_SITE . '/' . $thumb)) { $storage->delete(JPATH_SITE . '/' . $thumb); } } if ($storage->exists($cropped)) { $storage->delete($cropped); } else { if ($storage->exists(JPATH_SITE . '/' . $cropped)) { $storage->delete(JPATH_SITE . '/' . $cropped); } } } /** * Does the element consider the data to be empty * Used in isempty validation rule * * @param array $data Data to test against * @param int $repeatCounter Repeat group # * * @return bool */ public function dataConsideredEmpty($data, $repeatCounter) { $app = JFactory::getApplication(); $params = $this->getParams(); $input = $app->input; if ($input->get('rowid', '') !== '') { if ($input->get('task') == '') { return parent::dataConsideredEmpty($data, $repeatCounter); } $olddaata = JArrayHelper::getValue($this->getFormModel()->_origData, $repeatCounter); if (!is_null($olddaata)) { $name = $this->getFullName(true, false); $aoldData = JArrayHelper::fromObject($olddaata); $r = JArrayHelper::getValue($aoldData, $name, '') === '' ? true : false; if (!$r) { /* If an original value is found then data not empty - if not found continue to check the $_FILES array to see if one * has been uploaded */ return false; } } } $groupModel = $this->getGroup(); if ($groupModel->isJoin()) { $name = $this->getFullName(true, false); $joinid = $groupModel->getGroup()->join_id; $joindata = $input->files->get('join', array(), 'array'); if (empty($joindata)) { return true; } if ($groupModel->canRepeat()) { $file = $joindata[$joinid][$name][$repeatCounter]['name']; } else { $file = $joindata[$joinid][$name]['name']; } return $file == '' ? true : false; } else { $name = $this->getFullName(true, false); if ($this->isJoin()) { $join = $this->getJoinModel()->getJoin(); $joinid = $join->id; $joindata = $input->post->get('join', array(), 'array'); $joindata = JArrayHelper::getValue($joindata, $joinid, array()); $joindata = JArrayHelper::getValue($joindata, $name, array()); $joinids = JArrayHelper::getValue($joindata, 'id', array()); return empty($joinids) ? true : false; } else { // Single ajax upload if ($params->get('ajax_upload')) { $d = (array) $input->get($name, array(), 'array'); if (array_key_exists('id', $d)) { return false; } } else { $file = $input->files->get($name, array(), 'array'); if ($groupModel->canRepeat()) { return $file[$repeatCounter]['name'] == '' ? true : false; } } } } if (empty($file)) { $file = $input->get($name); // Ajax test - nothing in files return $file == '' ? true : false; } // No files selected? return $file['name'] == '' ? true : false; } /** * Process the upload (can be called via ajax from pluploader) * * @param array &$file File info * @param string $myFileDir User selected upload folder * @param int $repeatGroupCounter Repeat group counter * * @return string Location of uploaded file */ protected function _processIndUpload(&$file, $myFileDir = '', $repeatGroupCounter = 0) { $params = $this->getParams(); $user = JFactory::getUser(); $storage = $this->getStorage(); // $$$ hugh - check if we need to blow away the cached filepath, set in validation $myFileName = $storage->cleanName($file['name'], $repeatGroupCounter); if ($myFileName != $file['name']) { $file['name'] = $myFileName; unset($this->_filePaths[$repeatGroupCounter]); } $tmpFile = $file['tmp_name']; $uploader = $this->getFormModel()->getUploader(); if ($params->get('ul_file_types') == '') { $params->set('ul_file_types', implode(',', $this->_getAllowedExtension())); } $err = null; // Set FTP credentials, if given jimport('joomla.client.helper'); JClientHelper::setCredentialsFromRequest('ftp'); if ($myFileName == '') { return; } $filepath = $this->_getFilePath($repeatGroupCounter); if (!FabrikUploader::canUpload($file, $err, $params)) { $this->setError(100, $file['name'] . ': ' . FText::_($err)); } if ($storage->exists($filepath)) { switch ($params->get('ul_file_increment', 0)) { case 0: break; case 1: $filepath = FabrikUploader::incrementFileName($filepath, $filepath, 1); break; case 2: JLog::add('Ind upload Delete file: ' . $filepath . '; user = ' . $user->get('id'), JLog::WARNING, 'com_fabrik.element.fileupload'); $storage->delete($filepath); break; } } if (!$storage->upload($tmpFile, $filepath)) { $uploader->moveError = true; $this->setError(100, JText::sprintf('PLG_ELEMENT_FILEUPLOAD_UPLOAD_ERR', $tmpFile, $filepath)); return; } $filepath = $storage->getUploadedFilePath(); jimport('joomla.filesystem.path'); $storage->setPermissions($filepath); // $$$ hugh @TODO - shouldn't we check to see if it's actually an image before we do any of this stuff??? // Resize main image $oImage = FabimageHelper::loadLib($params->get('image_library')); $oImage->setStorage($storage); $mainWidth = $params->get('fu_main_max_width', ''); $mainHeight = $params->get('fu_main_max_height', ''); if ($mainWidth != '' || $mainHeight != '') { // $$$ rob ensure that both values are integers otherwise resize fails if ($mainHeight == '') { $mainHeight = (int) $mainWidth; } if ($mainWidth == '') { $mainWidth = (int) $mainHeight; } $oImage->resize($mainWidth, $mainHeight, $filepath, $filepath); } // $$$ hugh - if it's a PDF, make sure option is set to attempt PDF thumb $make_thumbnail = $params->get('make_thumbnail') == '1' ? true : false; if (JFile::getExt($filepath) == 'pdf' && $params->get('fu_make_pdf_thumb', '0') == '0') { $make_thumbnail = false; } if ($make_thumbnail) { $thumbPath = $storage->clean(JPATH_SITE . '/' . $params->get('thumb_dir') . '/' . $myFileDir . '/', false); $w = new FabrikWorker; $thumbPath = $w->parseMessageForPlaceHolder($thumbPath); $thumbPrefix = $params->get('thumb_prefix'); $maxWidth = $params->get('thumb_max_width', 125); $maxHeight = $params->get('thumb_max_height', 125); if ($thumbPath != '') { if (!$storage->folderExists($thumbPath)) { if (!$storage->createFolder($thumbPath)) { throw new RuntimeException("Could not make dir $thumbPath"); } } } $fileURL = $storage->getFileUrl(str_replace(COM_FABRIK_BASE, '', $filepath)); $destThumbFile = $storage->_getThumb($fileURL); $destThumbFile = $storage->urlToPath($destThumbFile); $oImage->resize($maxWidth, $maxHeight, $filepath, $destThumbFile); $storage->setPermissions($destThumbFile); } $storage->setPermissions($filepath); $storage->finalFilePathParse($filepath); return $filepath; } /** * Get the file storage object amazon s3/filesystem * * @return object */ public function getStorage() { if (!isset($this->storage)) { $params = $this->getParams(); $storageType = JFilterInput::getInstance()->clean($params->get('fileupload_storage_type', 'filesystemstorage'), 'CMD'); require_once JPATH_ROOT . '/plugins/fabrik_element/fileupload/adaptors/' . $storageType . '.php'; $storageClass = JString::ucfirst($storageType); $this->storage = new $storageClass($params); } return $this->storage; } /** * Get the full server file path for the upload, including the file name * * @param int $repeatCounter Repeat group counter * * @return string Path */ protected function _getFilePath($repeatCounter = 0) { $params = $this->getParams(); if (!isset($this->_filePaths)) { $this->_filePaths = array(); } if (array_key_exists($repeatCounter, $this->_filePaths)) { /* * $$$ hugh - if it uses element placeholders, there's a likelihood the element * data may have changed since we cached the path during validation, so we need * to rebuild it. For instance, if the element data is changed by a onBeforeProcess * submission plugin, or by a 'replace' validation. */ if (!FabrikString::usesElementPlaceholders($params->get('ul_directory'))) { return $this->_filePaths[$repeatCounter]; } } $filter = JFilterInput::getInstance(); $aData = $filter->clean($_POST, 'array'); $elName = $this->getFullName(true, false); $elNameRaw = $elName . '_raw'; // @TODO test with fileuploads in join groups $groupModel = $this->getGroup(); /** * $$$ hugh - if we use the @ way of doing this, and one of the array keys doesn't exist, * PHP still sets an error, even though it doesn't toss it. So if we then have some eval'd * code, like a PHP validation, and do the logError() thing, that will pick up and report this error, * and fail the validation. Which is VERY hard to track. So we'll have to do it long hand. */ // $myFileName = array_key_exists($elName, $_FILES) ? @$_FILES[$elName]['name'] : @$_FILES['file']['name']; $myFileName = ''; if (array_key_exists($elName, $_FILES) && is_array($_FILES[$elName])) { $myFileName = JArrayHelper::getValue($_FILES[$elName], 'name', ''); } else { if (array_key_exists('file', $_FILES) && is_array($_FILES['file'])) { $myFileName = JArrayHelper::getValue($_FILES['file'], 'name', ''); } } if (is_array($myFileName)) { $myFileName = JArrayHelper::getValue($myFileName, $repeatCounter, ''); } $myFileDir = array_key_exists($elNameRaw, $aData) && is_array($aData[$elNameRaw]) ? @$aData[$elNameRaw]['ul_end_dir'] : ''; if (is_array($myFileDir)) { $myFileDir = JArrayHelper::getValue($myFileDir, $repeatCounter, ''); } $storage = $this->getStorage(); // $$$ hugh - check if we need to blow away the cached filepath, set in validation $myFileName = $storage->cleanName($myFileName, $repeatCounter); $folder = $params->get('ul_directory'); $folder = $folder . '/' . $myFileDir; if ($storage->appendServerPath()) { $folder = JPATH_SITE . '/' . $folder; } $folder = JPath::clean($folder); $w = new FabrikWorker; $folder = $w->parseMessageForPlaceHolder($folder); if ($storage->appendServerPath()) { JPath::check($folder); } $storage->makeRecursiveFolders($folder); $p = $folder . '/' . $myFileName; $this->_filePaths[$repeatCounter] = JPath::clean($p); return $this->_filePaths[$repeatCounter]; } /** * Draws the html form element * * @param array $data To pre-populate element with * @param int $repeatCounter Repeat group counter * * @return string Elements html */ public function render($data, $repeatCounter = 0) { $this->_repeatGroupCounter = $repeatCounter; $id = $this->getHTMLId($repeatCounter); $name = $this->getHTMLName($repeatCounter); $groupModel = $this->getGroup(); $element = $this->getElement(); $params = $this->getParams(); if ($element->hidden == '1') { return $this->getHiddenField($name, $data[$name], $id); } $str = array(); $value = $this->getValue($data, $repeatCounter); $value = is_array($value) ? $value : FabrikWorker::JSONtoData($value, true); $value = $this->checkForSingleCropValue($value); if ($params->get('ajax_upload')) { if (isset($value->file)) { $value = $value->file; } } $imagedata = array(); $ulDir = $params->get('ul_directory'); $storage = $this->getStorage(); $formModel = $this->getFormModel(); $formid = $formModel->getId(); $use_download_script = $params->get('fu_use_download_script', '0'); // $$$ rob - explode as it may be grouped data (if element is a repeating upload) $values = is_array($value) ? $value : FabrikWorker::JSONtoData($value, true); if (!$this->isEditable() && ($use_download_script == FU_DOWNLOAD_SCRIPT_DETAIL || $use_download_script == FU_DOWNLOAD_SCRIPT_BOTH)) { $links = array(); if (!is_array($value)) { $value = (array) $value; } foreach ($value as $v) { $links[] = $this->downloadLink($v, $data, $repeatCounter); } return count($links) < 2 ? implode("\n", $links) : '<ul class="fabrikRepeatData"><li>' . implode('</li><li>', $links) . '</li></ul>'; } $render = new stdClass; $render->output = ''; $allRenders = array(); /* * $$$ hugh testing slideshow display */ if ($params->get('fu_show_image') === '3' && !$this->isEditable()) { // Failed validations - format different! if (array_key_exists('id', $values)) { $values = array_keys($values['id']); } $rendered = $this->buildCarousel($id, $values, $params, $data); return $rendered; } if (($params->get('fu_show_image') !== '0' && !$params->get('ajax_upload')) || !$this->isEditable()) { // Failed validations - format different! if (array_key_exists('id', $values)) { $values = array_keys($values['id']); } // End failed validations foreach ($values as $value) { if (is_object($value)) { $value = $value->file; } $render = $this->loadElement($value); if ($value != '' && ($storage->exists(COM_FABRIK_BASE . $value) || JString::substr($value, 0, 4) == 'http')) { $render->render($this, $params, $value); } if ($render->output != '') { if ($this->isEditable()) { $render->output = '<span class="fabrikUploadDelete" id="' . $id . '_delete_span">' . $this->deleteButton($value) . $render->output . '</span>'; } $allRenders[] = $render->output; } } } if (!$this->isEditable()) { if ($render->output == '' && $params->get('default_image') != '') { $render->output = '<img src="' . $params->get('default_image') . '" alt="image" />'; $allRenders[] = $render->output; } $str[] = '<div class="fabrikSubElementContainer">'; $ul = '<ul class="fabrikRepeatData"><li>' . implode('</li><li>', $allRenders) . '</li></ul>'; $str[] = count($allRenders) < 2 ? implode("\n", $allRenders) : $ul; $str[] = '</div>'; return implode("\n", $str); } $allRenders = implode('<br/>', $allRenders); $allRenders .= ($allRenders == '') ? '' : '<br/>'; $str[] = $allRenders . '<input class="fabrikinput" name="' . $name . '" type="file" id="' . $id . '" />' . "\n"; if ($params->get('upload_allow_folderselect') == '1') { $rDir = JPATH_SITE . '/' . $params->get('ul_directory'); $folders = JFolder::folders($rDir); $str[] = FabrikHelperHTML::folderAjaxSelect($folders); if ($groupModel->canRepeat()) { $ulname = FabrikString::rtrimword($name, "[$repeatCounter]") . "[ul_end_dir][$repeatCounter]"; } else { $ulname = $name . '[ul_end_dir]'; } $str[] = '<input name="' . $ulname . '" type="hidden" class="folderpath"/>'; } if ($params->get('ajax_upload')) { $str = array(); $str[] = $allRenders; $str = $this->plupload($str, $repeatCounter, $values); } array_unshift($str, '<div class="fabrikSubElementContainer">'); $str[] = '</div>'; return implode("\n", $str); } /** * Build the HTML to create the delete image button * * @param string $value File to delete * * @return string */ protected function deleteButton($value) { return '<button class="btn button" data-file="' . $value . '">' . FText::_('COM_FABRIK_DELETE') . '</button> '; } /** * Check if a single crop image has been uploaded and set the value accordingly * * @param array $value Uploaded files * * @return mixed */ protected function checkForSingleCropValue($value) { $params = $this->getParams(); // If its a single upload crop element if ($params->get('ajax_upload') && $params->get('ajax_max', 4) == 1) { $singleCropImg = $value; if (empty($singleCropImg)) { $value = ''; } else { $singleCropImg = $singleCropImg[0]; } } return $value; } /** * Make download link * * @param string $value File path * @param array $data Row * @param int $repeatCounter Repeat counter * * @return string Download link */ protected function downloadLink($value, $data, $repeatCounter = 0) { $app = JFactory::getApplication(); $package = $app->getUserState('com_fabrik.package', 'fabrik'); $input = $app->input; $params = $this->getParams(); $storage = $this->getStorage(); $formModel = $this->getFormModel(); if (empty($value) || !$storage->exists(COM_FABRIK_BASE . $value)) { return ''; } $aclEl = $this->getFormModel()->getElement($params->get('fu_download_acl', ''), true); if (!empty($aclEl)) { $aclEl = $aclEl->getFullName(); $canDownload = in_array($data[$aclEl], JFactory::getUser()->getAuthorisedViewLevels()); if (!$canDownload) { $img = $params->get('fu_download_noaccess_image'); return $img == '' ? '' : '<img src="' . COM_FABRIK_LIVESITE . 'media/com_fabrik/images/' . $img . '" alt="' . FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_PERMISSION') . '" />'; } } $formid = $formModel->getId(); $rowid = $input->get('rowid', '0'); $elementid = $this->getId(); $title = basename($value); if ($params->get('fu_title_element') == '') { $title_name = $this->getFullName(true, false) . '__title'; } else { $title_name = str_replace('.', '___', $params->get('fu_title_element')); } if (is_array($formModel->data)) { if (array_key_exists($title_name, $formModel->data)) { if (!empty($formModel->data[$title_name])) { $title = $formModel->data[$title_name]; $titles = FabrikWorker::JSONtoData($title, true); $title = JArrayHelper::getValue($titles, $repeatCounter, $title); } } } $downloadImg = $params->get('fu_download_access_image'); if ($downloadImg !== '' && JFile::exists('media/com_fabrik/images/' . $downloadImg)) { $aClass = ''; $title = '<img src="' . COM_FABRIK_LIVESITE . 'media/com_fabrik/images/' . $downloadImg . '" alt="' . $title . '" />'; } else { $aClass = 'class="btn btn-primary button"'; $title = '<i class="icon-download icon-white"></i> ' . FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD'); } $link = COM_FABRIK_LIVESITE . 'index.php?option=com_' . $package . '&task=plugin.pluginAjax&plugin=fileupload&method=ajax_download&format=raw&element_id=' . $elementid . '&formid=' . $formid . '&rowid=' . $rowid . '&repeatcount=' . $repeatCounter; $url = '<a href="' . $link . '"' . $aClass . '>' . $title . '</a>'; return $url; } /** * Load the required plupload runtime engines * * @param string $runtimes Runtimes * * @depreciated * * @return void */ protected function pluploadLRuntimes($runtimes) { return; } /** * Create the html for Ajax upload widget * * @param array $str Current html output * @param int $repeatCounter Repeat group counter * @param array $values Existing files * * @return array Modified fileupload html */ protected function plupload($str, $repeatCounter, $values) { FabrikHelperHTML::stylesheet(COM_FABRIK_LIVESITE . 'media/com_fabrik/css/slider.css'); $params = $this->getParams(); $w = (int) $params->get('ajax_dropbox_width', 0); $h = (int) $params->get('ajax_dropbox_hight', 200); $dropBoxStyle = 'height:' . $h . 'px'; if ($w !== 0) { $dropBoxStyle .= 'width:' . $w . 'px;'; } $basePath = COM_FABRIK_BASE . '/plugins/fabrik_element/fileupload/layouts/'; $layout = new JLayoutFile('fileupload-widget', $basePath, array('debug' => false, 'component' => 'com_fabrik', 'client' => 'site')); $data = array(); $data['id'] = $this->getHTMLId($repeatCounter); $data['winWidth'] = $params->get('win_width', 400); $data['winHeight'] = $params->get('win_height', 400); $data['canCrop'] = $this->canCrop(); $data['canvasSupport'] = FabrikHelperHTML::canvasSupport(); $data['dropBoxStyle'] = $dropBoxStyle; $data['field'] = implode("\n", $str); $data['j3'] = FabrikWorker::j3(); $pstr = (array) $layout->render($data); return $pstr; } /** * Fabrik 3 - needs to be onAjax_upload not ajax_upload * triggered by plupload widget * * @return void */ public function onAjax_upload() { $app = JFactory::getApplication(); $input = $app->input; $this->loadMeForAjax(); /* * Got this warning on fabrikar.com - not sure why set testing with errors off: * * <b>Warning</b>: utf8_to_unicode: Illegal sequence identifier in UTF-8 at byte 0 in * <b>/home/fabrikar/public_html/downloads/libraries/phputf8/utils/unicode.php</b> on line <b>110</b><br /> */ /* error_reporting(0); */ // $$$ hugh - reinstated this workaround, as I started getting those utf8 warnings as well. error_reporting(E_ERROR | E_PARSE); $o = new stdClass; $this->setId($input->getInt('element_id')); $this->loadMeForAjax(); $groupModel = $this->getGroup(); if (!$this->validate()) { $o->error = $this->_validationErr; echo json_encode($o); return; } $isjoin = $groupModel->isJoin(); if ($isjoin) { $name = $this->getFullName(true, false); $joinid = $groupModel->getGroup()->join_id; } else { $name = $this->getFullName(true, false); } // Get parameters $chunk = $input->getInt('chunk', 0); $chunks = $input->getInt('chunks', 0); $fileName = $input->get('name', ''); if ($chunk + 1 < $chunks) { return; } require_once COM_FABRIK_FRONTEND . '/helpers/uploader.php'; // @TODO test in join if (array_key_exists('file', $_FILES) || array_key_exists('join', $_FILES)) { $file = array('name' => $isjoin ? $_FILES['join']['name'][$joinid] : $_FILES['file']['name'], 'type' => $isjoin ? $_FILES['join']['type'][$joinid] : $_FILES['file']['type'], 'tmp_name' => $isjoin ? $_FILES['join']['tmp_name'][$joinid] : $_FILES['file']['tmp_name'], 'error' => $isjoin ? $_FILES['join']['error'][$joinid] : $_FILES['file']['error'], 'size' => $isjoin ? $_FILES['join']['size'][$joinid] : $_FILES['file']['size']); $filepath = $this->_processIndUpload($file, '', 0); $uri = $this->getStorage()->pathToURL($filepath); $o->filepath = $filepath; $o->uri = $uri; } else { $o->filepath = null; $o->uri = null; } echo json_encode($o); return; } /** * Get database field description * * @return string db field type */ public function getFieldDescription() { if ($this->encryptMe()) { return 'BLOB'; } return "TEXT"; } /** * Attach documents to the email * * @param string $data Data * * @return string Full path to image to attach to email */ public function addEmailAttachement($data) { if (is_object($data)) { $data = $data->file; } // @TODO: check what happens here with open base_dir in effect $params = $this->getParams(); if ($params->get('ul_email_file')) { $config = JFactory::getConfig(); if (empty($data)) { $data = $params->get('default_image'); } if (strstr($data, JPATH_SITE)) { $p = str_replace(COM_FABRIK_LIVESITE, JPATH_SITE, $data); } else { $p = JPATH_SITE . '/' . $data; } return $p; } return false; } /** * If a database join element's value field points to the same db field as this element * then this element can, within modifyJoinQuery, update the query. * E.g. if the database join element points to a file upload element then you can replace * the file path that is the standard $val with the html to create the image * * @param string $val Value * @param string $view Form or list * * @deprecated - doesn't seem to be used * * @return string Modified val */ protected function modifyJoinQuery($val, $view = 'form') { $params = $this->getParams(); if (!$params->get('fu_show_image', 0) && $view == 'form') { return $val; } if ($params->get('make_thumbnail')) { $ulDir = JPath::clean($params->get('ul_directory')) . '/'; $ulDir = str_replace("\\", "\\\\", $ulDir); $thumbDir = $params->get('thumb_dir'); $thumbDir = JPath::clean($params->get('thumb_dir')) . '/'; $w = new FabrikWorker; $thumbDir = $w->parseMessageForPlaceHolder($thumbDir); $thumbDir = str_replace("\\", "\\\\", $thumbDir); $w = new FabrikWorker; $thumbDir = $w->parseMessageForPlaceHolder($thumbDir); $thumbDir .= $params->get('thumb_prefix'); // Replace the backslashes with forward slashes $str = "CONCAT('<img src=\"" . COM_FABRIK_LIVESITE . "'," . "REPLACE(" . "REPLACE($val, '$ulDir', '" . $thumbDir . "')" . ", '\\\', '/')" . ", '\" alt=\"database join image\" />')"; } else { $str = " REPLACE(CONCAT('<img src=\"" . COM_FABRIK_LIVESITE . "' , $val, '\" alt=\"database join image\"/>'), '\\\', '/') "; } return $str; } /** * Trigger called when a row is deleted * * @param array $groups Grouped data of rows to delete * * @return void */ public function onDeleteRows($groups) { // Cant delete files from unpublished elements if (!$this->canUse()) { return; } $db = $this->getListModel()->getDb(); $user = JFactory::getUser(); $storage = $this->getStorage(); require_once COM_FABRIK_FRONTEND . '/helpers/uploader.php'; $params = $this->getParams(); if ($params->get('upload_delete_image', false)) { jimport('joomla.filesystem.file'); $elName = $this->getFullName(true, false); $name = $this->getElement()->name; foreach ($groups as $rows) { foreach ($rows as $row) { if (array_key_exists($elName . '_raw', $row)) { if ($this->isJoin()) { $join = $this->getJoinModel()->getJoin(); $query = $db->getQuery(true); $query->select('*')->from($db->quoteName($join->table_join)) ->where($db->quoteName('parent_id') . ' = ' . $db->quote($row->__pk_val)); $db->setQuery($query); $imageRows = $db->loadObjectList('id'); if (!empty($imageRows)) { foreach ($imageRows as $imageRow) { $this->deleteFile($imageRow->$name); } $query->clear(); $query->delete($db->quoteName($join->table_join)) ->where($db->quoteName('id') . ' IN (' . implode(', ', array_keys($imageRows)) . ')'); $db->setQuery($query); $logMsg = 'onDeleteRows Delete records query: ' . $db->getQuery() . '; user = ' . $user->get('id'); JLog::add($logMsg, JLog::WARNING, 'com_fabrik.element.fileupload'); $db->execute(); } } else { $files = explode(GROUPSPLITTER, $row->{$elName . '_raw'}); foreach ($files as $filename) { $this->deleteFile(trim($filename)); } } } } } } } /** * Return the number of bytes * * @param string $val E.g. 3m * * @return int Bytes */ protected function _return_bytes($val) { $val = trim($val); $last = JString::strtolower(substr($val, -1)); if ($last == 'g') { $val = $val * 1024 * 1024 * 1024; } if ($last == 'm') { $val = $val * 1024 * 1024; } if ($last == 'k') { $val = $val * 1024; } return $val; } /** * Get the max upload size allowed by the server. * * @deprecated - not used? * * @return int kilobyte upload size */ public function maxUpload() { $post_value = $this->_return_bytes(ini_get('post_max_size')); $upload_value = $this->_return_bytes(ini_get('upload_max_filesize')); $value = min($post_value, $upload_value); $value = $value / 1024; return $value; } /** * Turn form value into email formatted value * * @param mixed $value element value * @param array $data form data * @param int $repeatCounter group repeat counter * * @return string email formatted value */ public function getEmailValue($value, $data = array(), $repeatCounter = 0) { $params = $this->getParams(); $storage = $this->getStorage(); $this->_repeatGroupCounter = $repeatCounter; if ($params->get('fu_show_image_in_email', false)) { $origShowImages = $params->get('fu_show_image'); $params->set('fu_show_image', true); // For ajax repeats $value = (array) $value; $formModel = $this->getFormModel(); if (!isset($formModel->data)) { $formModel->data = $data; } if (empty($value)) { return ''; } foreach ($value as $v) { $render = $this->loadElement($v); if ($v != '' && $storage->exists(COM_FABRIK_BASE . $v)) { $render->render($this, $params, $v); } } if ($render->output == '' && $params->get('default_image') != '') { $render->output = '<img src="' . $params->get('default_image') . '" alt="image" />'; } return $render->output; } else { return $storage->preRenderPath($value); } } /** * Determines the value for the element in the form view * * @param array $data Form data * @param int $repeatCounter When repeating joined groups we need to know what part of the array to access * * @return string Value */ public function getROValue($data, $repeatCounter = 0) { $v = $this->getValue($data, $repeatCounter); $storage = $this->getStorage(); return $storage->pathToURL($v); } /** * Not really an AJAX call, we just use the pluginAjax method so we can run this * method for handling scripted downloads. * * @return void */ public function onAjax_download() { $app = JFactory::getApplication(); $input = $app->input; $this->setId($input->getInt('element_id')); $this->loadMeForAjax(); $this->getElement(); $params = $this->getParams(); $url = $input->server->get('HTTP_REFERER', '', 'string'); $lang = JFactory::getLanguage(); $lang->load('com_fabrik.plg.element.fabrikfileupload', JPATH_ADMINISTRATOR); $rowid = $input->get('rowid', '', 'string'); $repeatcount = $input->getInt('repeatcount', 0); $listModel = $this->getListModel(); $row = $listModel->getRow($rowid, false); if (!$this->canView()) { $app->enqueueMessage(FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_PERMISSION')); $app->redirect($url); exit; } if (empty($rowid)) { $app->enqueueMessage(FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_SUCH_FILE')); $app->redirect($url); exit; } if (empty($row)) { $app->enqueueMessage(FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_SUCH_FILE')); $app->redirect($url); exit; } $aclEl = $this->getFormModel()->getElement($params->get('fu_download_acl', ''), true); if (!empty($aclEl)) { $aclEl = $aclEl->getFullName(); $aclElraw = $aclEl . '_raw'; $user = JFactory::getUser(); $groups = $user->getAuthorisedViewLevels(); $canDownload = in_array($row->$aclElraw, $groups); if (!$canDownload) { $app->enqueueMessage(FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_PERMISSION')); $app->redirect($url); } } $storage = $this->getStorage(); $elName = $this->getFullName(true, false); $filepath = $row->$elName; $filepath = FabrikWorker::JSONtoData($filepath, true); $filepath = JArrayHelper::getValue($filepath, $repeatcount); $filepath = $storage->getFullPath($filepath); $filecontent = $storage->read($filepath); if ($filecontent !== false) { $thisFileInfo = $storage->getFileInfo($filepath); if ($thisFileInfo === false) { $app->enqueueMessage(FText::_('DOWNLOAD NO SUCH FILE')); $app->redirect($url); exit; } // Some time in the past header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header('Accept-Ranges: bytes'); header('Content-Length: ' . $thisFileInfo['filesize']); header('Content-Type: ' . $thisFileInfo['mime_type']); header('Content-Disposition: attachment; filename="' . $thisFileInfo['filename'] . '"'); // Serve up the file echo $filecontent; // $this->downloadEmail($row, $filepath); $this->downloadHit($rowid, $repeatcount); $this->downloadLog($row, $filepath); // And we're done. exit(); } else { $app->enqueueMessage(FText::_('PLG_ELEMENT_FILEUPLOAD_DOWNLOAD_NO_SUCH_FILE')); $app->redirect($url); exit; } } /** * Update downloads hits table * * @param int|string $rowid Update table's primary key * @param int $repeatCount Repeat group counter * * @return void */ protected function downloadHit($rowid, $repeatCount = 0) { // $$$ hugh @TODO - make this work for repeats and/or joins! $params = $this->getParams(); if ($hit_counter = $params->get('fu_download_hit_counter', '')) { JError::setErrorHandling(E_ALL, 'ignore'); $listModel = $this->getListModel(); $pk = $listModel->getTable()->db_primary_key; $fabrikDb = $listModel->getDb(); list($table_name, $element_name) = explode('.', $hit_counter); $sql = "UPDATE $table_name SET $element_name = COALESCE($element_name,0) + 1 WHERE $pk = " . $fabrikDb->quote($rowid); $fabrikDb->setQuery($sql); $fabrikDb->execute(); } } /** * Log the download * * @param object $row Log download row * @param string $filepath Downloaded file's path * * @since 2.0.5 * * @return void */ protected function downloadLog($row, $filepath) { $params = $this->getParams(); if ((int) $params->get('fu_download_log', 0)) { $app = JFactory::getApplication(); $input = $app->input; JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_fabrik/tables'); $log = JTable::getInstance('log', 'Table'); $log->message_type = 'fabrik.fileupload.download'; $user = JFactory::getUser(); $msg = new stdClass; $msg->file = $filepath; $msg->userid = $user->get('id'); $msg->username = $user->get('username'); $msg->email = $user->get('email'); $log->referring_url = $input->server->get('REMOTE_ADDR', '', 'string'); $log->message = json_encode($msg); $log->store(); } } /** * Called when save as copy form button clicked * * @param mixed $val Value to copy into new record * * @return mixed Value to copy into new record */ public function onSaveAsCopy($val) { if (empty($val)) { $formModel = $this->getFormModel(); $groupModel = $this->getGroupModel(); $isjoin = $groupModel->isJoin(); $origData = $formModel->getOrigData(); $groupModel = $this->getGroup(); if ($isjoin) { $name = $this->getFullName(true, false); $joinid = $groupModel->getGroup()->join_id; } else { $name = $this->getFullName(true, false); } $val = $origData[$name]; } return $val; } /** * Is the element a repeating element * * @return bool */ public function isRepeatElement() { $params = $this->getParams(); return $params->get('ajax_upload') && ($params->get('ajax_max', 4) > 1); } /** * Fabrik 3: needs to be onAjax_deleteFile * delete a previously uploaded file via ajax * * @return void */ public function onAjax_deleteFile() { $app = JFactory::getApplication(); $user = JFactory::getUser(); $input = $app->input; $this->loadMeForAjax(); $filename = $input->get('file', 'string', ''); // Filename may be a path - if so just get the name if (strstr($filename, '/')) { $filename = explode('/', $filename); $filename = array_pop($filename); } elseif (strstr($filename, '\\')) { $filename = explode('\\', $filename); $filename = array_pop($filename); } $repeatCounter = (int) $input->getInt('repeatCounter'); $join = FabTable::getInstance('join', 'FabrikTable'); $join->load(array('element_id' => $input->getInt('element_id'))); $this->setId($input->getInt('element_id')); $this->getElement(); $filepath = $this->_getFilePath($repeatCounter); $filepath = str_replace(JPATH_SITE, '', $filepath); $storage = $this->getStorage(); $filename = $storage->cleanName($filename, $repeatCounter); $filename = JPath::clean($filepath . '/' . $filename); $this->deleteFile($filename); $db = $this->getListModel()->getDb(); $query = $db->getQuery(true); // Could be a single ajax fileupload if so not joined if ($join->table_join != '') { // Use getString as if we have edited a record, added a file and deleted it the id is alphanumeric and not found in db. $query->delete($db->quoteName($join->table_join)) ->where($db->quoteName('id') . ' = ' . $db->quote($input->getString('recordid'))); $db->setQuery($query); JLog::add('Delete join image entry: ' . $db->getQuery() . '; user = ' . $user->get('id'), JLog::WARNING, 'com_fabrik.element.fileupload'); $db->execute(); } } /** * Determines the value for the element in the form view * * @param array $data Element value * @param int $repeatCounter When repeating joined groups we need to know what part of the array to access * @param array $opts Options * * @return string Value */ public function getValue($data, $repeatCounter = 0, $opts = array()) { $value = parent::getValue($data, $repeatCounter, $opts); return $value; } /** * Build 'slideshow' / carousel. What gets built will depend on content type, * using the first file in the data array as the type. So if the first file is * an image, a Bootstrap carousel will be built. * * @param string $id Widget HTML id * @param array $data Array of file paths * @param object $thisRow Row data * * @return string HTML */ public function buildCarousel($id = 'carousel', $data = array(), $thisRow = null) { $rendered = ''; if (!FArrayHelper::emptyIsh($data)) { $render = $this->loadElement($data[0]); $params = $this->getParams(); $rendered = $render->renderCarousel($id, $data, $this, $params, $thisRow); } return $rendered; } }
edortiz9/limmto
plugins/fabrik_element/fileupload/fileupload.php
PHP
gpl-2.0
80,252
#include "sndintrf.h" #include "streams.h" #include "flt_vol.h" struct filter_volume_info { sound_stream * stream; int gain; }; static void filter_volume_update(void *param, stream_sample_t **inputs, stream_sample_t **outputs, int samples) { stream_sample_t *src = inputs[0]; stream_sample_t *dst = outputs[0]; struct filter_volume_info *info = param; while (samples--) *dst++ = (*src++ * info->gain) >> 8; } static void *filter_volume_start(int sndindex, int clock, const void *config) { struct filter_volume_info *info; info = auto_malloc(sizeof(*info)); memset(info, 0, sizeof(*info)); info->gain = 0x100; info->stream = stream_create(1, 1, Machine->sample_rate, info, filter_volume_update); return info; } void flt_volume_set_volume(int num, float volume) { struct filter_volume_info *info = sndti_token(SOUND_FILTER_VOLUME, num); info->gain = (int)(volume * 256); } /************************************************************************** * Generic get_info **************************************************************************/ static void filter_volume_set_info(void *token, UINT32 state, sndinfo *info) { switch (state) { /* no parameters to set */ } } void filter_volume_get_info(void *token, UINT32 state, sndinfo *info) { switch (state) { /* --- the following bits of info are returned as 64-bit signed integers --- */ /* --- the following bits of info are returned as pointers to data or functions --- */ case SNDINFO_PTR_SET_INFO: info->set_info = filter_volume_set_info;break; case SNDINFO_PTR_START: info->start = filter_volume_start; break; case SNDINFO_PTR_STOP: /* Nothing */ break; case SNDINFO_PTR_RESET: /* Nothing */ break; /* --- the following bits of info are returned as NULL-terminated strings --- */ case SNDINFO_STR_NAME: info->s = "Volume Filter"; break; case SNDINFO_STR_CORE_FAMILY: info->s = "Filters"; break; case SNDINFO_STR_CORE_VERSION: info->s = "1.0"; break; case SNDINFO_STR_CORE_FILE: info->s = __FILE__; break; case SNDINFO_STR_CORE_CREDITS: info->s = "Copyright (c) 2004, The MAME Team"; break; } }
scs/uclinux
user/games/xmame/xmame-0.106/src/sound/flt_vol.c
C
gpl-2.0
2,200
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package org.oscarehr.common.dao; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.oscarehr.common.dao.utils.EntityDataGenerator; import org.oscarehr.common.dao.utils.SchemaUtils; import org.oscarehr.common.model.EyeformMacro; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; public class EyeformMacroDaoTest extends DaoTestFixtures { protected EyeformMacroDao dao = SpringUtils.getBean(EyeformMacroDao.class); @Before public void before() throws Exception { SchemaUtils.restoreTable("eyeform_macro_def", "eyeform_macro_billing"); } @Test public void testCreate() throws Exception { EyeformMacro entity = new EyeformMacro(); EntityDataGenerator.generateTestDataForModelClass(entity); dao.persist(entity); assertNotNull(entity.getId()); } @Test public void testGetMacros() throws Exception { String macroName1 = "bravo"; String macroName2 = "charlie"; String macroName3 = "alpha"; EyeformMacro eyeformMacro1 = new EyeformMacro(); EntityDataGenerator.generateTestDataForModelClass(eyeformMacro1); eyeformMacro1.setMacroName(macroName1); dao.persist(eyeformMacro1); EyeformMacro eyeformMacro2 = new EyeformMacro(); EntityDataGenerator.generateTestDataForModelClass(eyeformMacro2); eyeformMacro2.setMacroName(macroName2); dao.persist(eyeformMacro2); EyeformMacro eyeformMacro3 = new EyeformMacro(); EntityDataGenerator.generateTestDataForModelClass(eyeformMacro3); eyeformMacro3.setMacroName(macroName3); dao.persist(eyeformMacro3); List<EyeformMacro> expectedResult = new ArrayList<EyeformMacro>(Arrays.asList(eyeformMacro3, eyeformMacro1, eyeformMacro2)); List<EyeformMacro> result = dao.getMacros(); Logger logger = MiscUtils.getLogger(); if (result.size() != expectedResult.size()) { logger.warn("Array sizes do not match."); fail("Array sizes do not match."); } for (int i = 0; i < expectedResult.size(); i++) { if (!expectedResult.get(i).equals(result.get(i))){ logger.warn("Items do not match."); fail("Items do not match."); } } assertTrue(true); } }
hexbinary/landing
src/test/java/org/oscarehr/common/dao/EyeformMacroDaoTest.java
Java
gpl-2.0
3,437
/* * Copyright (c) 2014, The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ /*register and associated bit definition*/ #ifndef __MPU6880_H__ #define __MPU6880_H__ #define REG_SAMPLE_RATE_DIV 0x19 #define REG_CONFIG 0x1A #define REG_GYRO_CONFIG 0x1B #define BITS_SELF_TEST_EN 0xE0 #define GYRO_CONFIG_FSR_SHIFT 3 #define REG_ACCEL_CONFIG 0x1C #define REG_ACCEL_MOT_THR 0x1F #define REG_ACCEL_MOT_DUR 0x20 #define ACCL_CONFIG_FSR_SHIFT 3 #define REG_FIFO_EN 0x23 #define BIT_ACCEL_OUT 0x08 #define BITS_GYRO_OUT 0x70 #define REG_INT_ENABLE 0x38 #define BIT_DATA_RDY_EN 0x01 #define BIT_DMP_INT_EN 0x02 #define BIT_ZMOT_EN 0x20 #define BIT_MOT_EN 0x40 #define BIT_6500_WOM_EN 0x40 #define REG_DMP_INT_STATUS 0x39 #define REG_INT_STATUS 0x3A #define BIT_MOT_INT 0x40 #define BIT_ZMOT_INT 0x20 #define REG_RAW_ACCEL 0x3B #define REG_TEMPERATURE 0x41 #define REG_RAW_GYRO 0x43 #define REG_EXT_SENS_DATA_00 0x49 #define BIT_FIFO_RST 0x04 #define BIT_DMP_RST 0x08 #define BIT_I2C_MST_EN 0x20 #define BIT_FIFO_EN 0x40 #define BIT_DMP_EN 0x80 #define BIT_ACCEL_FIFO 0x08 #define BIT_GYRO_FIFO 0x70 #define REG_PWR_MGMT_1 0x6B #define BIT_H_RESET 0x80 #define BIT_SLEEP 0x40 #define BIT_CYCLE 0x20 #define BIT_CLK_MASK 0x7 #define BIT_RESET_ALL 0xCF #define REG_PWR_MGMT_2 0x6C #define BIT_PWR_ACCEL_STBY_MASK 0x38 #define BIT_PWR_GYRO_STBY_MASK 0x07 #define BIT_LPA_FREQ_MASK 0xC0 #define REG_FIFO_COUNT_H 0x72 #define REG_FIFO_R_W 0x74 #define REG_WHOAMI 0x75 #define ODR_DLPF_DIS 8000 #define ODR_DLPF_ENA 1000 /* device bootup time in millisecond */ #define POWER_UP_TIME_MS 100 /* delay to wait gyro engine stable in millisecond*/ #define SENSOR_UP_TIME_MS 30 /* delay between power operation in millisecond */ #define POWER_EN_DELAY_US 10 /* chip reset wait */ #define MPU6880_RESET_RETRY_CNT 10 #define MPU6880_RESET_WAIT_MS 20 #define MPU6880_LPA_5HZ 0x40 /* initial configure*/ //LINE<JIRA_ID><DATE20141201><modify to 200HZ>zenghaihui #define INIT_FIFO_RATE 200 enum mpu_device_id { MPU6880_ID = 0x68, MPU6500_ID = 0x70, }; enum mpu_fsr { MPU_FSR_250DPS = 0, MPU_FSR_500DPS, MPU_FSR_1000DPS, MPU_FSR_2000DPS, NUM_FSR }; enum mpu_filter { MPU_DLPF_256HZ_NOLPF2 = 0, MPU_DLPF_188HZ, MPU_DLPF_98HZ, MPU_DLPF_42HZ, MPU_DLPF_20HZ, MPU_DLPF_10HZ, MPU_DLPF_5HZ, MPU_DLPF_RESERVED, NUM_FILTER }; enum mpu_clock_source { MPU_CLK_INTERNAL = 0, MPU_CLK_PLL_X, NUM_CLK }; enum mpu_accl_fs { ACCEL_FS_02G = 0, ACCEL_FS_04G, ACCEL_FS_08G, ACCEL_FS_16G, NUM_ACCL_FSR }; /*device enum */ enum inv_devices { INV_MPU6880, INV_MPU6500, INV_MPU6XXX, INV_NUM_PARTS }; /** * struct mpu_reg_map_s - Notable slave registers. * @sample_rate_div: Divider applied to gyro output rate. * @lpf: Configures internal LPF. * @fifo_en: Determines which data will appear in FIFO. * @gyro_config: gyro config register. * @accel_config: accel config register * @fifo_count_h: Upper byte of FIFO count. * @fifo_r_w: FIFO register. * @raw_gyro Address of first gyro register. * @raw_accl Address of first accel register. * @temperature temperature register * @int_enable: Interrupt enable register. * @int_status: Interrupt flags. * @pwr_mgmt_1: Controls chip's power state and clock source. * @pwr_mgmt_2: Controls power state of individual sensors. */ struct mpu_reg_map { u8 sample_rate_div; u8 lpf; u8 user_ctrl; u8 fifo_en; u8 gyro_config; u8 accel_config; u8 fifo_count_h; u8 fifo_r_w; u8 raw_gyro; u8 raw_accel; u8 temperature; u8 int_enable; u8 int_status; u8 pwr_mgmt_1; u8 pwr_mgmt_2; }; /** * struct mpu_chip_config - Cached chip configuration data. * @fsr: Full scale range. * @lpf: Digital low pass filter frequency. * @accl_fs: accel full scale range. * @enable: master enable to enable output * @accel_enable: enable accel functionality * @accel_fifo_enable: enable accel data output * @gyro_enable: enable gyro functionality * @gyro_fifo_enable: enable gyro data output * @is_asleep: 1 if chip is powered down. * @lpa_mod: low power mode. * @tap_on: tap on/off. * @flick_int_on: flick interrupt on/off. * @lpa_freq: low power frequency * @fifo_rate: FIFO update rate. */ struct mpu_chip_config { u32 fsr:2; u32 lpf:3; u32 accel_fs:2; u32 enable:1; u32 accel_enable:1; u32 accel_fifo_enable:1; u32 gyro_enable:1; u32 gyro_fifo_enable:1; u32 is_asleep:1; u32 lpa_mode:1; u32 tap_on:1; u32 flick_int_on:1; u16 lpa_freq; u16 fifo_rate; }; /** * struct mpu6880_platform_data - device platform dependent data. * @gpio_en: enable GPIO. * @gpio_int: interrupt GPIO. * @int_flags: interrupt pin control flags. * @use_int: use interrupt mode instead of polling data. * @place: sensor place number. */ struct mpu6880_platform_data { int gpio_en; int gpio_int; u32 int_flags; bool use_int; u8 place; u32 gyro_poll_ms; u32 accel_poll_ms; }; #endif /* __MPU6880_H__ */
ASAZING/android_kernel_lanix_l900
include/linux/input/mpu6880.h
C
gpl-2.0
5,411
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'templates', 'gu', { button: 'ટેમ્પ્લેટ', emptyListMsg: '(કોઈ ટેમ્પ્લેટ ડિફાઇન નથી)', insertOption: 'મૂળ શબ્દને બદલો', options: 'ટેમ્પ્લેટના વિકલ્પો', selectPromptMsg: 'એડિટરમાં ઓપન કરવા ટેમ્પ્લેટ પસંદ કરો (વર્તમાન કન્ટેન્ટ સેવ નહીં થાય):', title: 'કન્ટેન્ટ ટેમ્પ્લેટ' } );
tapclicks/tapanalytics
sites/all/modules/ckeditor/plugins/templates/lang/gu.js
JavaScript
gpl-2.0
732
/* virt-df * Copyright (C) 2010-2012 Red Hat Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <inttypes.h> #include <unistd.h> #include <errno.h> #include "guestfs.h" #include "options.h" #include "domains.h" #include "virt-df.h" /* Since we want this function to be robust against very bad failure * cases (hello, https://bugzilla.kernel.org/show_bug.cgi?id=18792) it * won't exit on guestfs failures. */ int df_on_handle (guestfs_h *g, const char *name, const char *uuid, FILE *fp) { size_t i; CLEANUP_FREE_STRING_LIST char **devices = NULL; CLEANUP_FREE_STRING_LIST char **fses = NULL; if (verbose) fprintf (stderr, "df_on_handle: %s\n", name); devices = guestfs_list_devices (g); if (devices == NULL) return -1; fses = guestfs_list_filesystems (g); if (fses == NULL) return -1; for (i = 0; fses[i] != NULL; i += 2) { if (STRNEQ (fses[i+1], "") && STRNEQ (fses[i+1], "swap") && STRNEQ (fses[i+1], "unknown")) { const char *dev = fses[i]; CLEANUP_FREE_STATVFS struct guestfs_statvfs *stat = NULL; if (verbose) fprintf (stderr, "df_on_handle: %s dev %s\n", name, dev); /* Try mounting and stating the device. This might reasonably * fail, so don't show errors. */ guestfs_push_error_handler (g, NULL, NULL); if (guestfs_mount_ro (g, dev, "/") == 0) { stat = guestfs_statvfs (g, "/"); guestfs_umount_all (g); } guestfs_pop_error_handler (g); if (stat) print_stat (fp, name, uuid, dev, stat); } } return 0; } #if defined(HAVE_LIBVIRT) #include <libvirt/libvirt.h> /* The multi-threaded version. This callback is called from the code * in "parallel.c". */ int df_work (guestfs_h *g, size_t i, FILE *fp) { struct guestfs_add_libvirt_dom_argv optargs; optargs.bitmask = GUESTFS_ADD_LIBVIRT_DOM_READONLY_BITMASK | GUESTFS_ADD_LIBVIRT_DOM_READONLYDISK_BITMASK; optargs.readonly = 1; optargs.readonlydisk = "read"; /* Traditionally we have ignored errors from adding disks in virt-df. */ if (guestfs_add_libvirt_dom_argv (g, domains[i].dom, &optargs) == -1) return 0; if (guestfs_launch (g) == -1) return -1; return df_on_handle (g, domains[i].name, domains[i].uuid, fp); } #endif /* HAVE_LIBVIRT */
pombredanne/libguestfs
df/df.c
C
gpl-2.0
3,102
#include <linux/module.h> #include <asm/generic/log.h> static int __init l4x_module_init(void) { printk("Hi from the sample module\n"); l4x_printf("sample module: Also a warm welcome to the console\n"); return 0; } static void __exit l4x_module_exit(void) { l4x_printf("Bye from sample module\n"); } module_init(l4x_module_init); module_exit(l4x_module_exit); MODULE_AUTHOR("Adam Lackorzynski <[email protected]>"); MODULE_DESCRIPTION("L4Linux sample module"); MODULE_LICENSE("GPL");
Ksys-labs/l4linux
arch/l4/kernel/l4x_module.c
C
gpl-2.0
500
#ifndef NAND_H_INCLUDED #define NAND_H_INCLUDED #include <linux/dma-mapping.h> #include <linux/clk.h> #include <linux/cdev.h> #include "am_regs.h" #include <linux/earlysuspend.h> /** Register defination **/ #define NAND_SYS_CLK_NAME "clk81" #define NAND_CYCLE_DELAY 90 #define NAND_BOOT_NAME "bootloader" #define NAND_NORMAL_NAME "nandnormal" #define NAND_MULTI_NAME "nandmulti" #define NAND_CONVERST_ADDR 0xa0000000 #define M3_BOOT_WRITE_SIZE 0x600 #define M3_BOOT_COPY_NUM 4 #define M3_BOOT_PAGES_PER_COPY 256 #define NFC_BASE CBUS_REG_ADDR(NAND_CMD) #define NFC_OFF_CMD ((NAND_CMD -NAND_CMD)<<2) #define NFC_OFF_CFG ((NAND_CFG -NAND_CMD)<<2) #define NFC_OFF_DADR ((NAND_DADR-NAND_CMD)<<2) #define NFC_OFF_IADR ((NAND_IADR-NAND_CMD)<<2) #define NFC_OFF_BUF ((NAND_BUF -NAND_CMD)<<2) #define NFC_OFF_INFO ((NAND_INFO-NAND_CMD)<<2) #define NFC_OFF_DC ((NAND_DC -NAND_CMD)<<2) #define NFC_OFF_ADR ((NAND_ADR -NAND_CMD)<<2) #define NFC_OFF_DL ((NAND_DL -NAND_CMD)<<2) #define NFC_OFF_DH ((NAND_DH -NAND_CMD)<<2) /* Common Nand Read Flow */ #define CE0 (0xe<<10) #define CE1 (0xd<<10) #define CE2 (0xb<<10) #define CE3 (0x7<<10) #define CE_NOT_SEL (0xf<<10) #define IO4 ((0xe<<10)|(1<<18)) #define IO5 ((0xd<<10)|(1<<18)) #define IO6 ((0xb<<10)|(1<<18)) #define CLE (0x5<<14) #define ALE (0x6<<14) #define DWR (0x4<<14) #define DRD (0x8<<14) #define IDLE (0xc<<14) #define RB (1<<20) //#define STANDBY (0xf<<10) #define MAX_CYCLE_NUM 20 #define PER_INFO_BYTE 8 #define SIZE_INT (sizeof(unsigned int)) #define M2N ((0<<17) | (2<<20) | (1<<19)) #define N2M ((1<<17) | (2<<20) | (1<<19)) #define M2N_NORAN 0x00200000 #define N2M_NORAN 0x00220000 #define STS ((3<<17) | (2<<20)) #define ADL ((0<<16) | (3<<20)) #define ADH ((1<<16) | (3<<20)) #define AIL ((2<<16) | (3<<20)) #define AIH ((3<<16) | (3<<20)) #define ASL ((4<<16) | (3<<20)) #define ASH ((5<<16) | (3<<20)) #define SEED ((8<<16) | (3<<20)) /** Nand Flash Controller (M1) Global Macros */ /** Config Group */ #define NFC_SET_TIMING(mode,cycles,adjust) WRITE_CBUS_REG_BITS(NAND_CFG,((cycles)|((adjust&0xf)<<10)|((mode&7)<<5)),0,14) #define NFC_SET_CMD_START() SET_CBUS_REG_MASK(NAND_CFG,1<<12) #define NFC_SET_CMD_AUTO() SET_CBUS_REG_MASK(NAND_CFG,1<<13) #define NFC_SET_STS_IRQ(en) WRITE_CBUS_REG_BITS(NAND_CFG,en,20,1) #define NFC_SET_CMD_IRQ(en) WRITE_CBUS_REG_BITS(NAND_CFG,en,21,1) #define NFC_SET_TIMING_ASYC(bus_tim,bus_cyc) WRITE_CBUS_REG_BITS(NAND_CFG,((bus_cyc&31)|((bus_tim&31)<<5)|(0<<10)),0,12) #define NFC_SET_TIMING_SYNC(bus_tim,bus_cyc,sync_mode) WRITE_CBUS_REG_BITS(NAND_CFG,(bus_cyc&31)|((bus_tim&31)<<5)|((sync_mode&2)<<10),0,12) #define NFC_SET_TIMING_SYNC_ADJUST() #define NFC_SET_DMA_MODE(is_apb,spare_only) WRITE_CBUS_REG_BITS(NAND_CFG,((spare_only<<1)|(is_apb)),14,2) /** CMD relative Macros Shortage word . NFCC */ #define NFC_CMD_IDLE(ce,time) ((ce)|IDLE|(time&0x3ff)) #define NFC_CMD_CLE(ce,cmd ) ((ce)|CLE |(cmd &0x0ff)) #define NFC_CMD_ALE(ce,addr ) ((ce)|ALE |(addr&0x0ff)) #define NFC_CMD_STANDBY(time) (STANDBY |(time&0x3ff)) #define NFC_CMD_ADL(addr) (ADL |(addr&0xffff)) #define NFC_CMD_ADH(addr) (ADH|((addr>>16)&0xffff)) #define NFC_CMD_AIL(addr) (AIL |(addr&0xffff)) #define NFC_CMD_AIH(addr) (AIH|((addr>>16)&0xffff)) #define NFC_CMD_DWR(data) (DWR |(data&0xff )) #define NFC_CMD_DRD(ce,size) (ce|DRD|size) #define NFC_CMD_RB(ce,time ) ((ce)|RB |(time&0x1f)) #define NFC_CMD_RB_INT(ce,time) ((ce)|RB|(((ce>>10)^0xf)<<14)|(time&0x1f)) #define NFC_CMD_RBIO(time,io) (RB|io|(time&0x1f)) #define NFC_CMD_RBIO_INT(io,time) (RB|(((io>>10)^0x7)<<14)|(time&0x1f)) #define NFC_CMD_SEED(seed) (SEED|seed&0x7fff) #define NFC_CMD_STS(tim) (STS|(tim&3)) #define NFC_CMD_M2N(ran,ecc,sho,pgsz,pag) ((ran?M2N:M2N_NORAN)|(ecc<<14)|(sho<<13)|((pgsz&0x7f)<<6)|(pag&0x3f)) #define NFC_CMD_N2M(ran,ecc,sho,pgsz,pag) ((ran?N2M:N2M_NORAN)|(ecc<<14)|(sho<<13)|((pgsz&0x7f)<<6)|(pag&0x3f)) /** Alias for CMD */ #define NFC_CMD_D_ADR(addr) NFC_CMD_ADL(addr),NFC_CMD_ADH(addr) #define NFC_CMD_I_ADR(addr) NFC_CMD_ADI(addr),NFC_CMD_ADI(addr) /** Register Operation and Controller Status */ #define NFC_SEND_CMD(cmd) (WRITE_CBUS_REG(NAND_CMD,cmd)) #define NFC_READ_INFO() (READ_CBUS_REG(NAND_CMD)) /** ECC defination(M1) */ #define NAND_ECC_NONE (0x0<<14) #define NAND_ECC_REV0 (0x1<<14) #define NAND_ECC_REV1 (0x2<<14) #define NAND_ECC_REV2 (0x3<<14) #define NAND_ECC_BCH9 (0x4<<14) #define NAND_ECC_BCH12 (0x6<<14) #define NAND_ECC_BCH16 (0x7<<14) #define NAND_ECC_BCH8 (0x1) #define NAND_ECC_BCH8_1K (0x2) #define NAND_ECC_BCH16_1K (0x3) #define NAND_ECC_BCH24_1K (0x4) #define NAND_ECC_BCH30_1K (0x5) #define NAND_ECC_BCH40_1K (0x6) #define NAND_ECC_BCH60_1K (0x7) #define NAND_ECC_BCH_SHORT (0x8) /** Cmd FIFO control */ #define NFC_CMD_FIFO_GO() (WRITE_CBUS_REG(NAND_CMD,(1<<30))) #define NFC_CMD_FIFO_RESET() (WRITE_CBUS_REG(NAND_CMD,(1<<31))) /** ADDR operations */ #define NFC_SET_DADDR(a) (WRITE_CBUS_REG(NAND_DADR,(unsigned)a)) #define NFC_SET_IADDR(a) (WRITE_CBUS_REG(NAND_IADR,(unsigned)a)) #define NFC_SET_SADDR(a) (WRITE_CBUS_REG(NAND_SADR,(unsigned)a)) /** Send command directly */ /*#define NFC_SEND_CMD_IDLE(ce,time) NFC_SEND_CMD((ce)|IDLE|(time&0x3ff)) #define NFC_SEND_CMD_CLE(ce,cmd ) NFC_SEND_CMD((ce)|CLE |(cmd &0x0ff)) #define NFC_SEND_CMD_ALE(ce,addr ) NFC_SEND_CMD((ce)|ALE |(addr&0x0ff)) #define NFC_SEND_CMD_RB(ce,time ) NFC_SEND_CMD((ce)|RB |(time&0x3ff)) #define NFC_SEND_CMD_STANDBY(time) NFC_SEND_CMD(STANDBY |(time&0x3ff)) #define NFC_SEND_CMD_ADL(addr) NFC_SEND_CMD(ADL |(addr&0xffff)) #define NFC_SEND_CMD_ADH(addr) NFC_SEND_CMD(ADH|((addr>>16)&0xffff)) #define NFC_SEND_CMD_AIL(addr) NFC_SEND_CMD(AIL |(addr&0xffff)) #define NFC_SEND_CMD_AIH(addr) NFC_SEND_CMD(AIH|((addr>>16)&0xffff)) #define NFC_SEND_CMD_M2N(size,ecc) NFC_SEND_CMD(M2N |ecc|(size&0x3fff)) #define NFC_SEND_CMD_N2M(size,ecc) NFC_SEND_CMD(N2M |ecc|(size&0x3fff)) #define NFC_SEND_CMD_DWR(data) NFC_SEND_CMD(DWR |(data&0xff )) #define NFC_SEND_CMD_DRD( ) NFC_SEND_CMD(DRD ) */ #define NFC_SEND_CMD_IDLE(ce,time) NFC_SEND_CMD(NFC_CMD_IDLE(ce,time)) #define NFC_SEND_CMD_CLE(ce,cmd ) NFC_SEND_CMD(NFC_CMD_CLE(ce,cmd)) #define NFC_SEND_CMD_ALE(ce,addr ) NFC_SEND_CMD(NFC_CMD_ALE(ce,addr)) #define NFC_SEND_CMD_STANDBY(time) NFC_SEND_CMD(NFC_CMD_STANDBY(time)) #define NFC_SEND_CMD_ADL(addr) NFC_SEND_CMD(NFC_CMD_ADL(addr)) #define NFC_SEND_CMD_ADH(addr) NFC_SEND_CMD(NFC_CMD_ADH(addr)) #define NFC_SEND_CMD_AIL(addr) NFC_SEND_CMD(NFC_CMD_AIL(addr)) #define NFC_SEND_CMD_AIH(addr) NFC_SEND_CMD(NFC_CMD_AIH(addr)) #define NFC_SEND_CMD_DWR(data) NFC_SEND_CMD(NFC_CMD_DWR(data)) #define NFC_SEND_CMD_DRD(ce,size) NFC_SEND_CMD(NFC_CMD_DRD(ce,size)) #define NFC_SEND_CMD_RB(ce,time) NFC_SEND_CMD(NFC_CMD_RB(ce,time)) #define NFC_SEND_CMD_SEED(seed) NFC_SEND_CMD(NFC_CMD_SEED(seed)) #define NFC_SEND_CMD_M2N(ran,ecc,sho,pgsz,pag) NFC_SEND_CMD(NFC_CMD_M2N(ran,ecc,sho,pgsz,pag)) #define NFC_SEND_CMD_N2M(ran,ecc,sho,pgsz,pag) NFC_SEND_CMD(NFC_CMD_N2M(ran,ecc,sho,pgsz,pag)) #define NFC_SEND_CMD_M2N_RAW(ran,len) NFC_SEND_CMD((ran?M2N:M2N_NORAN)|(len&0x3fff)) #define NFC_SEND_CMD_N2M_RAW(ran,len) NFC_SEND_CMD((ran?N2M:N2M_NORAN)|(len&0x3fff)) /** Cmd Info Macros */ #define NFC_INFO_GET() (READ_CBUS_REG(NAND_CMD)) #define NFC_CMDFIFO_SIZE() ((NFC_INFO_GET()>>22)&0x1f) #define NFC_CHECEK_RB_TIMEOUT() ((NFC_INFO_GET()>>27)&0x1) #define NFC_GET_RB_STATUS(ce) (((NFC_INFO_GET()>>28)&(~(ce>>10)))&0xf) #define NFC_GET_BUF() READ_CBUS_REG(NAND_BUF) #define NFC_SET_CFG(val) (WRITE_CBUS_REG(NAND_CFG,(unsigned)val)) #define NFC_FIFO_CUR_CMD() ((NFC_INFO_GET()>>22)&0x3FFFFF) #define NAND_INFO_DONE(a) (((a)>>31)&1) #define NAND_ECC_ENABLE(a) (((a)>>30)&1) #define NAND_ECC_CNT(a) (((a)>>24)&0x3f) #define NAND_ZERO_CNT(a) (((a)>>16)&0x3f) #define NAND_INFO_DATA_2INFO(a) ((a)&0xffff) #define NAND_INFO_DATA_1INFO(a) ((a)&0xff) #define NAND_DEFAULT_OPTIONS (NAND_TIMING_MODE5 | NAND_ECC_BCH8_MODE) #define AML_NORMAL 0 #define AML_MULTI_CHIP 1 #define AML_MULTI_CHIP_SHARE_RB 2 #define AML_CHIP_NONE_RB 4 #define AML_INTERLEAVING_MODE 8 #define AML_NAND_CE0 0xe #define AML_NAND_CE1 0xd #define AML_NAND_CE2 0xb #define AML_NAND_CE3 0x7 #define AML_BADBLK_POS 0 #define NAND_ECC_UNIT_SIZE 512 #define NAND_ECC_UNIT_1KSIZE 1024 #define NAND_ECC_UNIT_SHORT 384 #define NAND_BCH9_ECC_SIZE 15 #define NAND_BCH8_ECC_SIZE 14 #define NAND_BCH12_ECC_SIZE 20 #define NAND_BCH16_ECC_SIZE 26 #define NAND_BCH8_1K_ECC_SIZE 14 #define NAND_BCH16_1K_ECC_SIZE 28 #define NAND_BCH24_1K_ECC_SIZE 42 #define NAND_BCH30_1K_ECC_SIZE 54 #define NAND_BCH40_1K_ECC_SIZE 70 #define NAND_BCH60_1K_ECC_SIZE 106 #define NAND_ECC_OPTIONS_MASK 0x0000000f #define NAND_PLANE_OPTIONS_MASK 0x000000f0 #define NAND_TIMING_OPTIONS_MASK 0x00000f00 #define NAND_BUSW_OPTIONS_MASK 0x0000f000 #define NAND_INTERLEAVING_OPTIONS_MASK 0x000f0000 #define NAND_ECC_SOFT_MODE 0x00000000 #define NAND_ECC_SHORT_MODE 0x00000001 #define NAND_ECC_BCH9_MODE 0x00000002 #define NAND_ECC_BCH8_MODE 0x00000003 #define NAND_ECC_BCH12_MODE 0x00000004 #define NAND_ECC_BCH16_MODE 0x00000005 #define NAND_ECC_BCH8_1K_MODE 0x00000006 #define NAND_ECC_BCH16_1K_MODE 0x00000007 #define NAND_ECC_BCH24_1K_MODE 0x00000008 #define NAND_ECC_BCH30_1K_MODE 0x00000009 #define NAND_ECC_BCH40_1K_MODE 0x0000000a #define NAND_ECC_BCH60_1K_MODE 0x0000000b #define NAND_TWO_PLANE_MODE 0x00000010 #define NAND_TIMING_MODE0 0x00000000 #define NAND_TIMING_MODE1 0x00000100 #define NAND_TIMING_MODE2 0x00000200 #define NAND_TIMING_MODE3 0x00000300 #define NAND_TIMING_MODE4 0x00000400 #define NAND_TIMING_MODE5 0x00000500 #define NAND_INTERLEAVING_MODE 0x00010000 #define DEFAULT_T_REA 40 #define DEFAULT_T_RHOH 0 #define AML_NAND_BUSY_TIMEOUT 0x40000 #define AML_DMA_BUSY_TIMEOUT 0x100000 #define MAX_ID_LEN 8 #define NAND_CMD_PLANE2_READ_START 0x06 #define NAND_CMD_TWOPLANE_PREVIOS_READ 0x60 #define NAND_CMD_TWOPLANE_READ1 0x5a #define NAND_CMD_TWOPLANE_READ2 0xa5 #define NAND_CMD_TWOPLANE_WRITE2_MICRO 0x80 #define NAND_CMD_TWOPLANE_WRITE2 0x81 #define NAND_CMD_DUMMY_PROGRAM 0x11 #define NAND_CMD_ERASE1_END 0xd1 #define NAND_CMD_MULTI_CHIP_STATUS 0x78 #define NAND_CMD_SET_FEATURES 0xEF #define NAND_CMD_GET_FEATURES 0xEE #define ONFI_TIMING_ADDR 0x01 #define MAX_CHIP_NUM 4 #define USER_BYTE_NUM 4 #define NAND_STATUS_READY_MULTI 0x20 #define NAND_BLOCK_GOOD 0 #define NAND_BLOCK_BAD 1 #define NAND_MINI_PART_SIZE 0x800000 #define NAND_MINI_PART_NUM 4 #define MAX_BAD_BLK_NUM 2000 #define MAX_MTD_PART_NUM 16 #define MAX_MTD_PART_NAME_LEN 24 #define ENV_NAND_MAGIC "envx" #define BBT_HEAD_MAGIC "bbts" #define BBT_TAIL_MAGIC "bbte" #define MTD_PART_MAGIC "anpt" #define CONFIG_ENV_SIZE 0x2000 #define ENV_SIZE (CONFIG_ENV_SIZE - (sizeof(uint32_t))) #define NAND_SYS_PART_SIZE 0x10000000 struct aml_nand_flash_dev { char *name; u8 id[MAX_ID_LEN]; unsigned pagesize; unsigned chipsize; unsigned erasesize; unsigned oobsize; unsigned internal_chipnr; unsigned T_REA; unsigned T_RHOH; u8 onfi_mode; unsigned options; }; struct aml_nand_part_info { char mtd_part_magic[4]; char mtd_part_name[MAX_MTD_PART_NAME_LEN]; uint64_t size; uint64_t offset; u_int32_t mask_flags; }; struct aml_nand_bbt_info { char bbt_head_magic[4]; int16_t nand_bbt[MAX_BAD_BLK_NUM]; struct aml_nand_part_info aml_nand_part[MAX_MTD_PART_NUM]; char bbt_tail_magic[4]; }; struct env_valid_node_t { int16_t ec; int16_t phy_blk_addr; int16_t phy_page_addr; int timestamp; }; struct env_free_node_t { int16_t ec; int16_t phy_blk_addr; int dirty_flag; struct env_free_node_t *next; }; struct env_oobinfo_t { char name[4]; int16_t ec; unsigned timestamp: 15; unsigned status_page: 1; }; struct aml_nandenv_info_t { struct mtd_info *mtd; struct env_valid_node_t *env_valid_node; struct env_free_node_t *env_free_node; u_char env_valid; u_char env_init; u_char part_num_before_sys; struct aml_nand_bbt_info nand_bbt_info; }; typedef struct environment_s { uint32_t crc; /* CRC32 over data bytes */ unsigned char data[ENV_SIZE]; /* Environment data */ } env_t; struct aml_nand_bch_desc{ char * name; unsigned bch_mode; unsigned bch_unit_size; unsigned bch_bytes; unsigned user_byte_mode; }; struct aml_nand_chip { u8 mfr_type; unsigned onfi_mode; unsigned T_REA; unsigned T_RHOH; unsigned options; unsigned page_size; unsigned block_size; unsigned oob_size; unsigned virtual_page_size; unsigned virtual_block_size; u8 plane_num; u8 chip_num; u8 internal_chipnr; unsigned internal_page_nums; unsigned internal_chip_shift; unsigned bch_mode; u8 user_byte_mode; u8 ops_mode; u8 cached_prog_status; u8 max_bch_mode; unsigned chip_enable[MAX_CHIP_NUM]; unsigned rb_enable[MAX_CHIP_NUM]; unsigned chip_selected; unsigned rb_received; unsigned valid_chip[MAX_CHIP_NUM]; unsigned page_addr; unsigned char *aml_nand_data_buf; dma_addr_t data_dma_addr; unsigned int *user_info_buf; dma_addr_t nand_info_dma_addr; int8_t *block_status; struct mtd_info mtd; struct nand_chip chip; struct aml_nandenv_info_t *aml_nandenv_info; struct aml_nand_bch_desc *bch_desc; /* platform info */ struct aml_nand_platform *platform; /* device info */ struct device *device; /* nand env device */ struct cdev nand_env_cdev; struct early_suspend nand_early_suspend; struct class cls; //plateform operation function void (*aml_nand_hw_init)(struct aml_nand_chip *aml_chip); void (*aml_nand_adjust_timing)(struct aml_nand_chip *aml_chip); int (*aml_nand_options_confirm)(struct aml_nand_chip *aml_chip); void (*aml_nand_cmd_ctrl)(struct aml_nand_chip *aml_chip, int cmd, unsigned int ctrl); void (*aml_nand_select_chip)(struct aml_nand_chip *aml_chip, int chipnr); void (*aml_nand_write_byte)(struct aml_nand_chip *aml_chip, uint8_t data); void (*aml_nand_get_user_byte)(struct aml_nand_chip *aml_chip, unsigned char *oob_buf, int byte_num); void (*aml_nand_set_user_byte)(struct aml_nand_chip *aml_chip, unsigned char *oob_buf, int byte_num); void (*aml_nand_command)(struct aml_nand_chip *aml_chip, unsigned command, int column, int page_addr, int chipnr); int (*aml_nand_wait_devready)(struct aml_nand_chip *aml_chip, int chipnr); int (*aml_nand_dma_read)(struct aml_nand_chip *aml_chip, unsigned char *buf, int len, unsigned bch_mode); int (*aml_nand_dma_write)(struct aml_nand_chip *aml_chip, unsigned char *buf, int len, unsigned bch_mode); int (*aml_nand_hwecc_correct)(struct aml_nand_chip *aml_chip, unsigned char *buf, unsigned size, unsigned char *oob_buf); }; struct aml_nand_platform { struct aml_nand_flash_dev *nand_flash_dev; char *name; unsigned chip_enable_pad; unsigned ready_busy_pad; unsigned T_REA; unsigned T_RHOH; struct aml_nand_chip *aml_chip; struct platform_nand_data platform_nand_data; }; struct aml_nand_device { struct aml_nand_platform *aml_nand_platform; u8 dev_num; }; static void inline nand_get_chip(void ) { SET_CBUS_REG_MASK(PREG_PAD_GPIO3_EN_N, 0x3ffff); SET_CBUS_REG_MASK(PAD_PULL_UP_REG3, (0xff | (1<<16))); SET_CBUS_REG_MASK(PERIPHS_PIN_MUX_5, ((1<<7) | (1 << 8) | (1 << 9))); SET_CBUS_REG_MASK(PERIPHS_PIN_MUX_2, ((0xf<<18) | (1 << 17) | (0x3 << 25))); } static void inline nand_release_chip(void) { CLEAR_CBUS_REG_MASK(PERIPHS_PIN_MUX_5, ((1<<7) | (1 << 8) | (1 << 9))); CLEAR_CBUS_REG_MASK(PERIPHS_PIN_MUX_2, ((0x3fF<<18) | (0X3 << 16))); } static inline struct aml_nand_chip *to_nand_chip(struct platform_device *pdev) { return platform_get_drvdata(pdev); } static inline struct aml_nand_chip *mtd_to_nand_chip(struct mtd_info *mtd) { return container_of(mtd, struct aml_nand_chip, mtd); } extern int aml_nand_init(struct aml_nand_chip *aml_chip); extern uint8_t aml_nand_get_onfi_features(struct aml_nand_chip *aml_chip, uint8_t *buf, int addr); extern void aml_nand_set_onfi_features(struct aml_nand_chip *aml_chip, uint8_t *buf, int addr); #endif // NAND_H_INCLUDED
madmaze/Meson-3-Kernel
arch/arm/mach-meson3/include/mach/nand.h
C
gpl-2.0
17,351
/* IPsec DOI and Oakley resolution routines * Copyright (C) 1998-2002 D. Hugh Redelmeier. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>. * * 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. * * RCSID $Id: ipsec_doi.h,v 1.41 2005/03/20 02:27:50 mcr Exp $ */ extern void echo_hdr(struct msg_digest *md, bool enc, u_int8_t np); extern void ipsecdoi_initiate(int whack_sock, struct connection *c , lset_t policy, unsigned long try , so_serial_t replacing , enum crypto_importance importance); extern void ipsecdoi_replace(struct state *st , lset_t policy_add, lset_t policy_del , unsigned long try); extern void init_phase2_iv(struct state *st, const msgid_t *msgid); #include "ikev1_quick.h" extern state_transition_fn main_inI1_outR1, main_inR1_outI2, main_inI2_outR2, main_inR2_outI3, main_inI3_outR3, main_inR3, aggr_inI1_outR1_psk, aggr_inI1_outR1_rsasig, aggr_inR1_outI2, aggr_inI2; extern void send_delete(struct state *st); extern void accept_delete(struct state *st, struct msg_digest *md , struct payload_digest *p); extern void send_notification_from_state(struct state *st, enum state_kind state, u_int16_t type); extern void send_notification_from_md(struct msg_digest *md, u_int16_t type); extern notification_t accept_nonce(struct msg_digest *md, chunk_t *dest , const char *name , enum next_payload_types paynum); extern notification_t accept_KE(chunk_t *dest, const char *val_name , const struct oakley_group_desc *gr , pb_stream *pbs); /* * some additional functions are exported for xauth.c */ extern void close_message(pb_stream *pbs); /* forward declaration */ extern bool encrypt_message(pb_stream *pbs, struct state *st); /* forward declaration */ extern stf_status dpd_inI_outR(struct state *st , struct isakmp_notification *const n, pb_stream *n_pbs); extern stf_status dpd_inR(struct state *st , struct isakmp_notification *const n, pb_stream *n_pbs); extern void dpd_timeout(struct state *st); /* START_HASH_PAYLOAD * * Emit a to-be-filled-in hash payload, noting the field start (r_hashval) * and the start of the part of the message to be hashed (r_hash_start). * This macro is magic. * - it can cause the caller to return * - it references variables local to the caller (r_hashval, r_hash_start, st) */ #define START_HASH_PAYLOAD(rbody, np) { \ pb_stream hash_pbs; \ if (!out_generic(np, &isakmp_hash_desc, &(rbody), &hash_pbs)) \ return STF_INTERNAL_ERROR; \ r_hashval = hash_pbs.cur; /* remember where to plant value */ \ if (!out_zero(st->st_oakley.prf_hasher->hash_digest_len, &hash_pbs, "HASH")) \ return STF_INTERNAL_ERROR; \ close_output_pbs(&hash_pbs); \ r_hash_start = (rbody).cur; /* hash from after HASH payload */ \ } /* CHECK_QUICK_HASH * * This macro is magic -- it cannot be expressed as a function. * - it causes the caller to return! * - it declares local variables and expects the "do_hash" argument * expression to reference them (hash_val, hash_pbs) */ #define CHECK_QUICK_HASH(md, do_hash, hash_name, msg_name) { \ pb_stream *const hash_pbs = &md->chain[ISAKMP_NEXT_HASH]->pbs; \ u_char hash_val[MAX_DIGEST_LEN]; \ size_t hash_len = do_hash; \ if (pbs_left(hash_pbs) != hash_len \ || memcmp(hash_pbs->cur, hash_val, hash_len) != 0) \ { \ DBG_cond_dump(DBG_CRYPT, "received " hash_name ":", hash_pbs->cur, pbs_left(hash_pbs)); \ loglog(RC_LOG_SERIOUS, "received " hash_name " does not match computed value in " msg_name); \ /* XXX Could send notification back */ \ return STF_FAIL + INVALID_HASH_INFORMATION; \ } \ } extern stf_status send_isakmp_notification(struct state *st , u_int16_t type, const void *data, size_t len); extern bool has_preloaded_public_key(struct state *st); extern bool extract_peer_id(struct id *peer, const pb_stream *id_pbs); /* * tools for sending Pluto Vendor ID. */ #ifdef PLUTO_SENDS_VENDORID #define SEND_PLUTO_VID 1 #else /* !PLUTO_SENDS_VENDORID */ #define SEND_PLUTO_VID 0 #endif /* !PLUTO_SENDS_VENDORID */ extern char pluto_vendorid[];
rhuitl/uClinux
openswan/programs/pluto/ipsec_doi.h
C
gpl-2.0
4,612
/* * linux/drivers/video/omap2/dss/dispc.c * * Copyright (C) 2009 Nokia Corporation * Author: Tomi Valkeinen <[email protected]> * * Some code and ideas taken from drivers/video/omap/ driver * by Imre Deak. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. * * 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/>. */ #define DSS_SUBSYS_NAME "DISPC" #include <linux/kernel.h> #include <linux/dma-mapping.h> #include <linux/vmalloc.h> #include <linux/export.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/jiffies.h> #include <linux/seq_file.h> #include <linux/delay.h> #include <linux/workqueue.h> #include <linux/hardirq.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <plat/clock.h> #include <video/omapdss.h> #include "dss.h" #include "dss_features.h" #include "dispc.h" /* DISPC */ #define DISPC_SZ_REGS SZ_4K #define DISPC_IRQ_MASK_ERROR (DISPC_IRQ_GFX_FIFO_UNDERFLOW | \ DISPC_IRQ_OCP_ERR | \ DISPC_IRQ_VID1_FIFO_UNDERFLOW | \ DISPC_IRQ_VID2_FIFO_UNDERFLOW | \ DISPC_IRQ_SYNC_LOST | \ DISPC_IRQ_SYNC_LOST_DIGIT) #define DISPC_MAX_NR_ISRS 8 struct omap_dispc_isr_data { omap_dispc_isr_t isr; void *arg; u32 mask; }; enum omap_burst_size { BURST_SIZE_X2 = 0, BURST_SIZE_X4 = 1, BURST_SIZE_X8 = 2, }; #define REG_GET(idx, start, end) \ FLD_GET(dispc_read_reg(idx), start, end) #define REG_FLD_MOD(idx, val, start, end) \ dispc_write_reg(idx, FLD_MOD(dispc_read_reg(idx), val, start, end)) struct dispc_irq_stats { unsigned long last_reset; unsigned irq_count; unsigned irqs[32]; }; static struct { struct platform_device *pdev; void __iomem *base; int ctx_loss_cnt; int irq; struct clk *dss_clk; u32 fifo_size[MAX_DSS_OVERLAYS]; spinlock_t irq_lock; u32 irq_error_mask; struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS]; u32 error_irqs; struct work_struct error_work; bool ctx_valid; u32 ctx[DISPC_SZ_REGS / sizeof(u32)]; #ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS spinlock_t irq_stats_lock; struct dispc_irq_stats irq_stats; #endif } dispc; enum omap_color_component { /* used for all color formats for OMAP3 and earlier * and for RGB and Y color component on OMAP4 */ DISPC_COLOR_COMPONENT_RGB_Y = 1 << 0, /* used for UV component for * OMAP_DSS_COLOR_YUV2, OMAP_DSS_COLOR_UYVY, OMAP_DSS_COLOR_NV12 * color formats on OMAP4 */ DISPC_COLOR_COMPONENT_UV = 1 << 1, }; static void _omap_dispc_set_irqs(void); static inline void dispc_write_reg(const u16 idx, u32 val) { __raw_writel(val, dispc.base + idx); } static inline u32 dispc_read_reg(const u16 idx) { return __raw_readl(dispc.base + idx); } static int dispc_get_ctx_loss_count(void) { struct device *dev = &dispc.pdev->dev; struct omap_display_platform_data *pdata = dev->platform_data; struct omap_dss_board_info *board_data = pdata->board_data; int cnt; if (!board_data->get_context_loss_count) return -ENOENT; cnt = board_data->get_context_loss_count(dev); WARN_ONCE(cnt < 0, "get_context_loss_count failed: %d\n", cnt); return cnt; } #define SR(reg) \ dispc.ctx[DISPC_##reg / sizeof(u32)] = dispc_read_reg(DISPC_##reg) #define RR(reg) \ dispc_write_reg(DISPC_##reg, dispc.ctx[DISPC_##reg / sizeof(u32)]) static void dispc_save_context(void) { int i, j; DSSDBG("dispc_save_context\n"); SR(IRQENABLE); SR(CONTROL); SR(CONFIG); SR(LINE_NUMBER); if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) || dss_has_feature(FEAT_ALPHA_FREE_ZORDER)) SR(GLOBAL_ALPHA); if (dss_has_feature(FEAT_MGR_LCD2)) { SR(CONTROL2); SR(CONFIG2); } for (i = 0; i < dss_feat_get_num_mgrs(); i++) { SR(DEFAULT_COLOR(i)); SR(TRANS_COLOR(i)); SR(SIZE_MGR(i)); if (i == OMAP_DSS_CHANNEL_DIGIT) continue; SR(TIMING_H(i)); SR(TIMING_V(i)); SR(POL_FREQ(i)); SR(DIVISORo(i)); SR(DATA_CYCLE1(i)); SR(DATA_CYCLE2(i)); SR(DATA_CYCLE3(i)); if (dss_has_feature(FEAT_CPR)) { SR(CPR_COEF_R(i)); SR(CPR_COEF_G(i)); SR(CPR_COEF_B(i)); } } for (i = 0; i < dss_feat_get_num_ovls(); i++) { SR(OVL_BA0(i)); SR(OVL_BA1(i)); SR(OVL_POSITION(i)); SR(OVL_SIZE(i)); SR(OVL_ATTRIBUTES(i)); SR(OVL_FIFO_THRESHOLD(i)); SR(OVL_ROW_INC(i)); SR(OVL_PIXEL_INC(i)); if (dss_has_feature(FEAT_PRELOAD)) SR(OVL_PRELOAD(i)); if (i == OMAP_DSS_GFX) { SR(OVL_WINDOW_SKIP(i)); SR(OVL_TABLE_BA(i)); continue; } SR(OVL_FIR(i)); SR(OVL_PICTURE_SIZE(i)); SR(OVL_ACCU0(i)); SR(OVL_ACCU1(i)); for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_H(i, j)); for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_HV(i, j)); for (j = 0; j < 5; j++) SR(OVL_CONV_COEF(i, j)); if (dss_has_feature(FEAT_FIR_COEF_V)) { for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_V(i, j)); } if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) { SR(OVL_BA0_UV(i)); SR(OVL_BA1_UV(i)); SR(OVL_FIR2(i)); SR(OVL_ACCU2_0(i)); SR(OVL_ACCU2_1(i)); for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_H2(i, j)); for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_HV2(i, j)); for (j = 0; j < 8; j++) SR(OVL_FIR_COEF_V2(i, j)); } if (dss_has_feature(FEAT_ATTR2)) SR(OVL_ATTRIBUTES2(i)); } if (dss_has_feature(FEAT_CORE_CLK_DIV)) SR(DIVISOR); dispc.ctx_loss_cnt = dispc_get_ctx_loss_count(); dispc.ctx_valid = true; DSSDBG("context saved, ctx_loss_count %d\n", dispc.ctx_loss_cnt); } static void dispc_restore_context(void) { int i, j, ctx; DSSDBG("dispc_restore_context\n"); if (!dispc.ctx_valid) return; ctx = dispc_get_ctx_loss_count(); if (ctx >= 0 && ctx == dispc.ctx_loss_cnt) return; DSSDBG("ctx_loss_count: saved %d, current %d\n", dispc.ctx_loss_cnt, ctx); /*RR(IRQENABLE);*/ /*RR(CONTROL);*/ RR(CONFIG); RR(LINE_NUMBER); if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) || dss_has_feature(FEAT_ALPHA_FREE_ZORDER)) RR(GLOBAL_ALPHA); if (dss_has_feature(FEAT_MGR_LCD2)) RR(CONFIG2); for (i = 0; i < dss_feat_get_num_mgrs(); i++) { RR(DEFAULT_COLOR(i)); RR(TRANS_COLOR(i)); RR(SIZE_MGR(i)); if (i == OMAP_DSS_CHANNEL_DIGIT) continue; RR(TIMING_H(i)); RR(TIMING_V(i)); RR(POL_FREQ(i)); RR(DIVISORo(i)); RR(DATA_CYCLE1(i)); RR(DATA_CYCLE2(i)); RR(DATA_CYCLE3(i)); if (dss_has_feature(FEAT_CPR)) { RR(CPR_COEF_R(i)); RR(CPR_COEF_G(i)); RR(CPR_COEF_B(i)); } } for (i = 0; i < dss_feat_get_num_ovls(); i++) { RR(OVL_BA0(i)); RR(OVL_BA1(i)); RR(OVL_POSITION(i)); RR(OVL_SIZE(i)); RR(OVL_ATTRIBUTES(i)); RR(OVL_FIFO_THRESHOLD(i)); RR(OVL_ROW_INC(i)); RR(OVL_PIXEL_INC(i)); if (dss_has_feature(FEAT_PRELOAD)) RR(OVL_PRELOAD(i)); if (i == OMAP_DSS_GFX) { RR(OVL_WINDOW_SKIP(i)); RR(OVL_TABLE_BA(i)); continue; } RR(OVL_FIR(i)); RR(OVL_PICTURE_SIZE(i)); RR(OVL_ACCU0(i)); RR(OVL_ACCU1(i)); for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_H(i, j)); for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_HV(i, j)); for (j = 0; j < 5; j++) RR(OVL_CONV_COEF(i, j)); if (dss_has_feature(FEAT_FIR_COEF_V)) { for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_V(i, j)); } if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) { RR(OVL_BA0_UV(i)); RR(OVL_BA1_UV(i)); RR(OVL_FIR2(i)); RR(OVL_ACCU2_0(i)); RR(OVL_ACCU2_1(i)); for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_H2(i, j)); for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_HV2(i, j)); for (j = 0; j < 8; j++) RR(OVL_FIR_COEF_V2(i, j)); } if (dss_has_feature(FEAT_ATTR2)) RR(OVL_ATTRIBUTES2(i)); } if (dss_has_feature(FEAT_CORE_CLK_DIV)) RR(DIVISOR); /* enable last, because LCD & DIGIT enable are here */ RR(CONTROL); if (dss_has_feature(FEAT_MGR_LCD2)) RR(CONTROL2); /* clear spurious SYNC_LOST_DIGIT interrupts */ dispc_write_reg(DISPC_IRQSTATUS, DISPC_IRQ_SYNC_LOST_DIGIT); /* * enable last so IRQs won't trigger before * the context is fully restored */ RR(IRQENABLE); DSSDBG("context restored\n"); } #undef SR #undef RR int dispc_runtime_get(void) { int r; DSSDBG("dispc_runtime_get\n"); r = pm_runtime_get_sync(&dispc.pdev->dev); WARN_ON(r < 0); return r < 0 ? r : 0; } void dispc_runtime_put(void) { int r; DSSDBG("dispc_runtime_put\n"); r = pm_runtime_put_sync(&dispc.pdev->dev); WARN_ON(r < 0); } static inline bool dispc_mgr_is_lcd(enum omap_channel channel) { if (channel == OMAP_DSS_CHANNEL_LCD || channel == OMAP_DSS_CHANNEL_LCD2) return true; else return false; } static struct omap_dss_device *dispc_mgr_get_device(enum omap_channel channel) { struct omap_overlay_manager *mgr = omap_dss_get_overlay_manager(channel); return mgr ? mgr->device : NULL; } u32 dispc_mgr_get_vsync_irq(enum omap_channel channel) { switch (channel) { case OMAP_DSS_CHANNEL_LCD: return DISPC_IRQ_VSYNC; case OMAP_DSS_CHANNEL_LCD2: return DISPC_IRQ_VSYNC2; case OMAP_DSS_CHANNEL_DIGIT: return DISPC_IRQ_EVSYNC_ODD | DISPC_IRQ_EVSYNC_EVEN; default: BUG(); } } u32 dispc_mgr_get_framedone_irq(enum omap_channel channel) { switch (channel) { case OMAP_DSS_CHANNEL_LCD: return DISPC_IRQ_FRAMEDONE; case OMAP_DSS_CHANNEL_LCD2: return DISPC_IRQ_FRAMEDONE2; case OMAP_DSS_CHANNEL_DIGIT: return 0; default: BUG(); } } bool dispc_mgr_go_busy(enum omap_channel channel) { int bit; if (dispc_mgr_is_lcd(channel)) bit = 5; /* GOLCD */ else bit = 6; /* GODIGIT */ if (channel == OMAP_DSS_CHANNEL_LCD2) return REG_GET(DISPC_CONTROL2, bit, bit) == 1; else return REG_GET(DISPC_CONTROL, bit, bit) == 1; } void dispc_mgr_go(enum omap_channel channel) { int bit; bool enable_bit, go_bit; if (dispc_mgr_is_lcd(channel)) bit = 0; /* LCDENABLE */ else bit = 1; /* DIGITALENABLE */ /* if the channel is not enabled, we don't need GO */ if (channel == OMAP_DSS_CHANNEL_LCD2) enable_bit = REG_GET(DISPC_CONTROL2, bit, bit) == 1; else enable_bit = REG_GET(DISPC_CONTROL, bit, bit) == 1; if (!enable_bit) return; if (dispc_mgr_is_lcd(channel)) bit = 5; /* GOLCD */ else bit = 6; /* GODIGIT */ if (channel == OMAP_DSS_CHANNEL_LCD2) go_bit = REG_GET(DISPC_CONTROL2, bit, bit) == 1; else go_bit = REG_GET(DISPC_CONTROL, bit, bit) == 1; if (go_bit) { DSSERR("GO bit not down for channel %d\n", channel); return; } DSSDBG("GO %s\n", channel == OMAP_DSS_CHANNEL_LCD ? "LCD" : (channel == OMAP_DSS_CHANNEL_LCD2 ? "LCD2" : "DIGIT")); if (channel == OMAP_DSS_CHANNEL_LCD2) REG_FLD_MOD(DISPC_CONTROL2, 1, bit, bit); else REG_FLD_MOD(DISPC_CONTROL, 1, bit, bit); } static void dispc_ovl_write_firh_reg(enum omap_plane plane, int reg, u32 value) { dispc_write_reg(DISPC_OVL_FIR_COEF_H(plane, reg), value); } static void dispc_ovl_write_firhv_reg(enum omap_plane plane, int reg, u32 value) { dispc_write_reg(DISPC_OVL_FIR_COEF_HV(plane, reg), value); } static void dispc_ovl_write_firv_reg(enum omap_plane plane, int reg, u32 value) { dispc_write_reg(DISPC_OVL_FIR_COEF_V(plane, reg), value); } static void dispc_ovl_write_firh2_reg(enum omap_plane plane, int reg, u32 value) { BUG_ON(plane == OMAP_DSS_GFX); dispc_write_reg(DISPC_OVL_FIR_COEF_H2(plane, reg), value); } static void dispc_ovl_write_firhv2_reg(enum omap_plane plane, int reg, u32 value) { BUG_ON(plane == OMAP_DSS_GFX); dispc_write_reg(DISPC_OVL_FIR_COEF_HV2(plane, reg), value); } static void dispc_ovl_write_firv2_reg(enum omap_plane plane, int reg, u32 value) { BUG_ON(plane == OMAP_DSS_GFX); dispc_write_reg(DISPC_OVL_FIR_COEF_V2(plane, reg), value); } static void dispc_ovl_set_scale_coef(enum omap_plane plane, int fir_hinc, int fir_vinc, int five_taps, enum omap_color_component color_comp) { const struct dispc_coef *h_coef, *v_coef; int i; h_coef = dispc_ovl_get_scale_coef(fir_hinc, true); v_coef = dispc_ovl_get_scale_coef(fir_vinc, five_taps); for (i = 0; i < 8; i++) { u32 h, hv; h = FLD_VAL(h_coef[i].hc0_vc00, 7, 0) | FLD_VAL(h_coef[i].hc1_vc0, 15, 8) | FLD_VAL(h_coef[i].hc2_vc1, 23, 16) | FLD_VAL(h_coef[i].hc3_vc2, 31, 24); hv = FLD_VAL(h_coef[i].hc4_vc22, 7, 0) | FLD_VAL(v_coef[i].hc1_vc0, 15, 8) | FLD_VAL(v_coef[i].hc2_vc1, 23, 16) | FLD_VAL(v_coef[i].hc3_vc2, 31, 24); if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y) { dispc_ovl_write_firh_reg(plane, i, h); dispc_ovl_write_firhv_reg(plane, i, hv); } else { dispc_ovl_write_firh2_reg(plane, i, h); dispc_ovl_write_firhv2_reg(plane, i, hv); } } if (five_taps) { for (i = 0; i < 8; i++) { u32 v; v = FLD_VAL(v_coef[i].hc0_vc00, 7, 0) | FLD_VAL(v_coef[i].hc4_vc22, 15, 8); if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y) dispc_ovl_write_firv_reg(plane, i, v); else dispc_ovl_write_firv2_reg(plane, i, v); } } } static void _dispc_setup_color_conv_coef(void) { int i; const struct color_conv_coef { int ry, rcr, rcb, gy, gcr, gcb, by, bcr, bcb; int full_range; } ctbl_bt601_5 = { 298, 409, 0, 298, -208, -100, 298, 0, 517, 0, }; const struct color_conv_coef *ct; #define CVAL(x, y) (FLD_VAL(x, 26, 16) | FLD_VAL(y, 10, 0)) ct = &ctbl_bt601_5; for (i = 1; i < dss_feat_get_num_ovls(); i++) { dispc_write_reg(DISPC_OVL_CONV_COEF(i, 0), CVAL(ct->rcr, ct->ry)); dispc_write_reg(DISPC_OVL_CONV_COEF(i, 1), CVAL(ct->gy, ct->rcb)); dispc_write_reg(DISPC_OVL_CONV_COEF(i, 2), CVAL(ct->gcb, ct->gcr)); dispc_write_reg(DISPC_OVL_CONV_COEF(i, 3), CVAL(ct->bcr, ct->by)); dispc_write_reg(DISPC_OVL_CONV_COEF(i, 4), CVAL(0, ct->bcb)); REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(i), ct->full_range, 11, 11); } #undef CVAL } static void dispc_ovl_set_ba0(enum omap_plane plane, u32 paddr) { dispc_write_reg(DISPC_OVL_BA0(plane), paddr); } static void dispc_ovl_set_ba1(enum omap_plane plane, u32 paddr) { dispc_write_reg(DISPC_OVL_BA1(plane), paddr); } static void dispc_ovl_set_ba0_uv(enum omap_plane plane, u32 paddr) { dispc_write_reg(DISPC_OVL_BA0_UV(plane), paddr); } static void dispc_ovl_set_ba1_uv(enum omap_plane plane, u32 paddr) { dispc_write_reg(DISPC_OVL_BA1_UV(plane), paddr); } static void dispc_ovl_set_pos(enum omap_plane plane, int x, int y) { u32 val = FLD_VAL(y, 26, 16) | FLD_VAL(x, 10, 0); dispc_write_reg(DISPC_OVL_POSITION(plane), val); } static void dispc_ovl_set_pic_size(enum omap_plane plane, int width, int height) { u32 val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0); if (plane == OMAP_DSS_GFX) dispc_write_reg(DISPC_OVL_SIZE(plane), val); else dispc_write_reg(DISPC_OVL_PICTURE_SIZE(plane), val); } static void dispc_ovl_set_vid_size(enum omap_plane plane, int width, int height) { u32 val; BUG_ON(plane == OMAP_DSS_GFX); val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0); dispc_write_reg(DISPC_OVL_SIZE(plane), val); } static void dispc_ovl_set_zorder(enum omap_plane plane, u8 zorder) { struct omap_overlay *ovl = omap_dss_get_overlay(plane); if ((ovl->caps & OMAP_DSS_OVL_CAP_ZORDER) == 0) return; REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), zorder, 27, 26); } static void dispc_ovl_enable_zorder_planes(void) { int i; if (!dss_has_feature(FEAT_ALPHA_FREE_ZORDER)) return; for (i = 0; i < dss_feat_get_num_ovls(); i++) REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(i), 1, 25, 25); } static void dispc_ovl_set_pre_mult_alpha(enum omap_plane plane, bool enable) { struct omap_overlay *ovl = omap_dss_get_overlay(plane); if ((ovl->caps & OMAP_DSS_OVL_CAP_PRE_MULT_ALPHA) == 0) return; REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable ? 1 : 0, 28, 28); } static void dispc_ovl_setup_global_alpha(enum omap_plane plane, u8 global_alpha) { static const unsigned shifts[] = { 0, 8, 16, 24, }; int shift; struct omap_overlay *ovl = omap_dss_get_overlay(plane); if ((ovl->caps & OMAP_DSS_OVL_CAP_GLOBAL_ALPHA) == 0) return; shift = shifts[plane]; REG_FLD_MOD(DISPC_GLOBAL_ALPHA, global_alpha, shift + 7, shift); } static void dispc_ovl_set_pix_inc(enum omap_plane plane, s32 inc) { dispc_write_reg(DISPC_OVL_PIXEL_INC(plane), inc); } static void dispc_ovl_set_row_inc(enum omap_plane plane, s32 inc) { dispc_write_reg(DISPC_OVL_ROW_INC(plane), inc); } static void dispc_ovl_set_color_mode(enum omap_plane plane, enum omap_color_mode color_mode) { u32 m = 0; if (plane != OMAP_DSS_GFX) { switch (color_mode) { case OMAP_DSS_COLOR_NV12: m = 0x0; break; case OMAP_DSS_COLOR_RGBX16: m = 0x1; break; case OMAP_DSS_COLOR_RGBA16: m = 0x2; break; case OMAP_DSS_COLOR_RGB12U: m = 0x4; break; case OMAP_DSS_COLOR_ARGB16: m = 0x5; break; case OMAP_DSS_COLOR_RGB16: m = 0x6; break; case OMAP_DSS_COLOR_ARGB16_1555: m = 0x7; break; case OMAP_DSS_COLOR_RGB24U: m = 0x8; break; case OMAP_DSS_COLOR_RGB24P: m = 0x9; break; case OMAP_DSS_COLOR_YUV2: m = 0xa; break; case OMAP_DSS_COLOR_UYVY: m = 0xb; break; case OMAP_DSS_COLOR_ARGB32: m = 0xc; break; case OMAP_DSS_COLOR_RGBA32: m = 0xd; break; case OMAP_DSS_COLOR_RGBX32: m = 0xe; break; case OMAP_DSS_COLOR_XRGB16_1555: m = 0xf; break; default: BUG(); break; } } else { switch (color_mode) { case OMAP_DSS_COLOR_CLUT1: m = 0x0; break; case OMAP_DSS_COLOR_CLUT2: m = 0x1; break; case OMAP_DSS_COLOR_CLUT4: m = 0x2; break; case OMAP_DSS_COLOR_CLUT8: m = 0x3; break; case OMAP_DSS_COLOR_RGB12U: m = 0x4; break; case OMAP_DSS_COLOR_ARGB16: m = 0x5; break; case OMAP_DSS_COLOR_RGB16: m = 0x6; break; case OMAP_DSS_COLOR_ARGB16_1555: m = 0x7; break; case OMAP_DSS_COLOR_RGB24U: m = 0x8; break; case OMAP_DSS_COLOR_RGB24P: m = 0x9; break; case OMAP_DSS_COLOR_RGBX16: m = 0xa; break; case OMAP_DSS_COLOR_RGBA16: m = 0xb; break; case OMAP_DSS_COLOR_ARGB32: m = 0xc; break; case OMAP_DSS_COLOR_RGBA32: m = 0xd; break; case OMAP_DSS_COLOR_RGBX32: m = 0xe; break; case OMAP_DSS_COLOR_XRGB16_1555: m = 0xf; break; default: BUG(); break; } } REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), m, 4, 1); } void dispc_ovl_set_channel_out(enum omap_plane plane, enum omap_channel channel) { int shift; u32 val; int chan = 0, chan2 = 0; switch (plane) { case OMAP_DSS_GFX: shift = 8; break; case OMAP_DSS_VIDEO1: case OMAP_DSS_VIDEO2: case OMAP_DSS_VIDEO3: shift = 16; break; default: BUG(); return; } val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane)); if (dss_has_feature(FEAT_MGR_LCD2)) { switch (channel) { case OMAP_DSS_CHANNEL_LCD: chan = 0; chan2 = 0; break; case OMAP_DSS_CHANNEL_DIGIT: chan = 1; chan2 = 0; break; case OMAP_DSS_CHANNEL_LCD2: chan = 0; chan2 = 1; break; default: BUG(); } val = FLD_MOD(val, chan, shift, shift); val = FLD_MOD(val, chan2, 31, 30); } else { val = FLD_MOD(val, channel, shift, shift); } dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), val); } static enum omap_channel dispc_ovl_get_channel_out(enum omap_plane plane) { int shift; u32 val; enum omap_channel channel; switch (plane) { case OMAP_DSS_GFX: shift = 8; break; case OMAP_DSS_VIDEO1: case OMAP_DSS_VIDEO2: case OMAP_DSS_VIDEO3: shift = 16; break; default: BUG(); } val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane)); if (dss_has_feature(FEAT_MGR_LCD2)) { if (FLD_GET(val, 31, 30) == 0) channel = FLD_GET(val, shift, shift); else channel = OMAP_DSS_CHANNEL_LCD2; } else { channel = FLD_GET(val, shift, shift); } return channel; } static void dispc_ovl_set_burst_size(enum omap_plane plane, enum omap_burst_size burst_size) { static const unsigned shifts[] = { 6, 14, 14, 14, }; int shift; shift = shifts[plane]; REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), burst_size, shift + 1, shift); } static void dispc_configure_burst_sizes(void) { int i; const int burst_size = BURST_SIZE_X8; /* Configure burst size always to maximum size */ for (i = 0; i < omap_dss_get_num_overlays(); ++i) dispc_ovl_set_burst_size(i, burst_size); } static u32 dispc_ovl_get_burst_size(enum omap_plane plane) { unsigned unit = dss_feat_get_burst_size_unit(); /* burst multiplier is always x8 (see dispc_configure_burst_sizes()) */ return unit * 8; } void dispc_enable_gamma_table(bool enable) { /* * This is partially implemented to support only disabling of * the gamma table. */ if (enable) { DSSWARN("Gamma table enabling for TV not yet supported"); return; } REG_FLD_MOD(DISPC_CONFIG, enable, 9, 9); } static void dispc_mgr_enable_cpr(enum omap_channel channel, bool enable) { u16 reg; if (channel == OMAP_DSS_CHANNEL_LCD) reg = DISPC_CONFIG; else if (channel == OMAP_DSS_CHANNEL_LCD2) reg = DISPC_CONFIG2; else return; REG_FLD_MOD(reg, enable, 15, 15); } static void dispc_mgr_set_cpr_coef(enum omap_channel channel, struct omap_dss_cpr_coefs *coefs) { u32 coef_r, coef_g, coef_b; if (!dispc_mgr_is_lcd(channel)) return; coef_r = FLD_VAL(coefs->rr, 31, 22) | FLD_VAL(coefs->rg, 20, 11) | FLD_VAL(coefs->rb, 9, 0); coef_g = FLD_VAL(coefs->gr, 31, 22) | FLD_VAL(coefs->gg, 20, 11) | FLD_VAL(coefs->gb, 9, 0); coef_b = FLD_VAL(coefs->br, 31, 22) | FLD_VAL(coefs->bg, 20, 11) | FLD_VAL(coefs->bb, 9, 0); dispc_write_reg(DISPC_CPR_COEF_R(channel), coef_r); dispc_write_reg(DISPC_CPR_COEF_G(channel), coef_g); dispc_write_reg(DISPC_CPR_COEF_B(channel), coef_b); } static void dispc_ovl_set_vid_color_conv(enum omap_plane plane, bool enable) { u32 val; BUG_ON(plane == OMAP_DSS_GFX); val = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane)); val = FLD_MOD(val, enable, 9, 9); dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), val); } static void dispc_ovl_enable_replication(enum omap_plane plane, bool enable) { static const unsigned shifts[] = { 5, 10, 10, 10 }; int shift; shift = shifts[plane]; REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable, shift, shift); } void dispc_mgr_set_lcd_size(enum omap_channel channel, u16 width, u16 height) { u32 val; BUG_ON((width > (1 << 11)) || (height > (1 << 11))); val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0); dispc_write_reg(DISPC_SIZE_MGR(channel), val); } void dispc_set_digit_size(u16 width, u16 height) { u32 val; BUG_ON((width > (1 << 11)) || (height > (1 << 11))); val = FLD_VAL(height - 1, 26, 16) | FLD_VAL(width - 1, 10, 0); dispc_write_reg(DISPC_SIZE_MGR(OMAP_DSS_CHANNEL_DIGIT), val); } static void dispc_read_plane_fifo_sizes(void) { u32 size; int plane; u8 start, end; u32 unit; unit = dss_feat_get_buffer_size_unit(); dss_feat_get_reg_field(FEAT_REG_FIFOSIZE, &start, &end); for (plane = 0; plane < dss_feat_get_num_ovls(); ++plane) { size = REG_GET(DISPC_OVL_FIFO_SIZE_STATUS(plane), start, end); size *= unit; dispc.fifo_size[plane] = size; } } static u32 dispc_ovl_get_fifo_size(enum omap_plane plane) { return dispc.fifo_size[plane]; } void dispc_ovl_set_fifo_threshold(enum omap_plane plane, u32 low, u32 high) { u8 hi_start, hi_end, lo_start, lo_end; u32 unit; unit = dss_feat_get_buffer_size_unit(); WARN_ON(low % unit != 0); WARN_ON(high % unit != 0); low /= unit; high /= unit; dss_feat_get_reg_field(FEAT_REG_FIFOHIGHTHRESHOLD, &hi_start, &hi_end); dss_feat_get_reg_field(FEAT_REG_FIFOLOWTHRESHOLD, &lo_start, &lo_end); DSSDBG("fifo(%d) threshold (bytes), old %u/%u, new %u/%u\n", plane, REG_GET(DISPC_OVL_FIFO_THRESHOLD(plane), lo_start, lo_end) * unit, REG_GET(DISPC_OVL_FIFO_THRESHOLD(plane), hi_start, hi_end) * unit, low * unit, high * unit); dispc_write_reg(DISPC_OVL_FIFO_THRESHOLD(plane), FLD_VAL(high, hi_start, hi_end) | FLD_VAL(low, lo_start, lo_end)); } void dispc_enable_fifomerge(bool enable) { if (!dss_has_feature(FEAT_FIFO_MERGE)) { WARN_ON(enable); return; } DSSDBG("FIFO merge %s\n", enable ? "enabled" : "disabled"); REG_FLD_MOD(DISPC_CONFIG, enable ? 1 : 0, 14, 14); } void dispc_ovl_compute_fifo_thresholds(enum omap_plane plane, u32 *fifo_low, u32 *fifo_high, bool use_fifomerge) { /* * All sizes are in bytes. Both the buffer and burst are made of * buffer_units, and the fifo thresholds must be buffer_unit aligned. */ unsigned buf_unit = dss_feat_get_buffer_size_unit(); unsigned ovl_fifo_size, total_fifo_size, burst_size; int i; burst_size = dispc_ovl_get_burst_size(plane); ovl_fifo_size = dispc_ovl_get_fifo_size(plane); if (use_fifomerge) { total_fifo_size = 0; for (i = 0; i < omap_dss_get_num_overlays(); ++i) total_fifo_size += dispc_ovl_get_fifo_size(i); } else { total_fifo_size = ovl_fifo_size; } /* * We use the same low threshold for both fifomerge and non-fifomerge * cases, but for fifomerge we calculate the high threshold using the * combined fifo size */ if (dss_has_feature(FEAT_OMAP3_DSI_FIFO_BUG)) { *fifo_low = ovl_fifo_size - burst_size * 2; *fifo_high = total_fifo_size - burst_size; } else { *fifo_low = ovl_fifo_size - burst_size; *fifo_high = total_fifo_size - buf_unit; } } static void dispc_ovl_set_fir(enum omap_plane plane, int hinc, int vinc, enum omap_color_component color_comp) { u32 val; if (color_comp == DISPC_COLOR_COMPONENT_RGB_Y) { u8 hinc_start, hinc_end, vinc_start, vinc_end; dss_feat_get_reg_field(FEAT_REG_FIRHINC, &hinc_start, &hinc_end); dss_feat_get_reg_field(FEAT_REG_FIRVINC, &vinc_start, &vinc_end); val = FLD_VAL(vinc, vinc_start, vinc_end) | FLD_VAL(hinc, hinc_start, hinc_end); dispc_write_reg(DISPC_OVL_FIR(plane), val); } else { val = FLD_VAL(vinc, 28, 16) | FLD_VAL(hinc, 12, 0); dispc_write_reg(DISPC_OVL_FIR2(plane), val); } } static void dispc_ovl_set_vid_accu0(enum omap_plane plane, int haccu, int vaccu) { u32 val; u8 hor_start, hor_end, vert_start, vert_end; dss_feat_get_reg_field(FEAT_REG_HORIZONTALACCU, &hor_start, &hor_end); dss_feat_get_reg_field(FEAT_REG_VERTICALACCU, &vert_start, &vert_end); val = FLD_VAL(vaccu, vert_start, vert_end) | FLD_VAL(haccu, hor_start, hor_end); dispc_write_reg(DISPC_OVL_ACCU0(plane), val); } static void dispc_ovl_set_vid_accu1(enum omap_plane plane, int haccu, int vaccu) { u32 val; u8 hor_start, hor_end, vert_start, vert_end; dss_feat_get_reg_field(FEAT_REG_HORIZONTALACCU, &hor_start, &hor_end); dss_feat_get_reg_field(FEAT_REG_VERTICALACCU, &vert_start, &vert_end); val = FLD_VAL(vaccu, vert_start, vert_end) | FLD_VAL(haccu, hor_start, hor_end); dispc_write_reg(DISPC_OVL_ACCU1(plane), val); } static void dispc_ovl_set_vid_accu2_0(enum omap_plane plane, int haccu, int vaccu) { u32 val; val = FLD_VAL(vaccu, 26, 16) | FLD_VAL(haccu, 10, 0); dispc_write_reg(DISPC_OVL_ACCU2_0(plane), val); } static void dispc_ovl_set_vid_accu2_1(enum omap_plane plane, int haccu, int vaccu) { u32 val; val = FLD_VAL(vaccu, 26, 16) | FLD_VAL(haccu, 10, 0); dispc_write_reg(DISPC_OVL_ACCU2_1(plane), val); } static void dispc_ovl_set_scale_param(enum omap_plane plane, u16 orig_width, u16 orig_height, u16 out_width, u16 out_height, bool five_taps, u8 rotation, enum omap_color_component color_comp) { int fir_hinc, fir_vinc; fir_hinc = 1024 * orig_width / out_width; fir_vinc = 1024 * orig_height / out_height; dispc_ovl_set_scale_coef(plane, fir_hinc, fir_vinc, five_taps, color_comp); dispc_ovl_set_fir(plane, fir_hinc, fir_vinc, color_comp); } static void dispc_ovl_set_scaling_common(enum omap_plane plane, u16 orig_width, u16 orig_height, u16 out_width, u16 out_height, bool ilace, bool five_taps, bool fieldmode, enum omap_color_mode color_mode, u8 rotation) { int accu0 = 0; int accu1 = 0; u32 l; dispc_ovl_set_scale_param(plane, orig_width, orig_height, out_width, out_height, five_taps, rotation, DISPC_COLOR_COMPONENT_RGB_Y); l = dispc_read_reg(DISPC_OVL_ATTRIBUTES(plane)); /* RESIZEENABLE and VERTICALTAPS */ l &= ~((0x3 << 5) | (0x1 << 21)); l |= (orig_width != out_width) ? (1 << 5) : 0; l |= (orig_height != out_height) ? (1 << 6) : 0; l |= five_taps ? (1 << 21) : 0; /* VRESIZECONF and HRESIZECONF */ if (dss_has_feature(FEAT_RESIZECONF)) { l &= ~(0x3 << 7); l |= (orig_width <= out_width) ? 0 : (1 << 7); l |= (orig_height <= out_height) ? 0 : (1 << 8); } /* LINEBUFFERSPLIT */ if (dss_has_feature(FEAT_LINEBUFFERSPLIT)) { l &= ~(0x1 << 22); l |= five_taps ? (1 << 22) : 0; } dispc_write_reg(DISPC_OVL_ATTRIBUTES(plane), l); /* * field 0 = even field = bottom field * field 1 = odd field = top field */ if (ilace && !fieldmode) { accu1 = 0; accu0 = ((1024 * orig_height / out_height) / 2) & 0x3ff; if (accu0 >= 1024/2) { accu1 = 1024/2; accu0 -= accu1; } } dispc_ovl_set_vid_accu0(plane, 0, accu0); dispc_ovl_set_vid_accu1(plane, 0, accu1); } static void dispc_ovl_set_scaling_uv(enum omap_plane plane, u16 orig_width, u16 orig_height, u16 out_width, u16 out_height, bool ilace, bool five_taps, bool fieldmode, enum omap_color_mode color_mode, u8 rotation) { int scale_x = out_width != orig_width; int scale_y = out_height != orig_height; if (!dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) return; if ((color_mode != OMAP_DSS_COLOR_YUV2 && color_mode != OMAP_DSS_COLOR_UYVY && color_mode != OMAP_DSS_COLOR_NV12)) { /* reset chroma resampling for RGB formats */ REG_FLD_MOD(DISPC_OVL_ATTRIBUTES2(plane), 0, 8, 8); return; } switch (color_mode) { case OMAP_DSS_COLOR_NV12: /* UV is subsampled by 2 vertically*/ orig_height >>= 1; /* UV is subsampled by 2 horz.*/ orig_width >>= 1; break; case OMAP_DSS_COLOR_YUV2: case OMAP_DSS_COLOR_UYVY: /*For YUV422 with 90/270 rotation, *we don't upsample chroma */ if (rotation == OMAP_DSS_ROT_0 || rotation == OMAP_DSS_ROT_180) /* UV is subsampled by 2 hrz*/ orig_width >>= 1; /* must use FIR for YUV422 if rotated */ if (rotation != OMAP_DSS_ROT_0) scale_x = scale_y = true; break; default: BUG(); } if (out_width != orig_width) scale_x = true; if (out_height != orig_height) scale_y = true; dispc_ovl_set_scale_param(plane, orig_width, orig_height, out_width, out_height, five_taps, rotation, DISPC_COLOR_COMPONENT_UV); REG_FLD_MOD(DISPC_OVL_ATTRIBUTES2(plane), (scale_x || scale_y) ? 1 : 0, 8, 8); /* set H scaling */ REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), scale_x ? 1 : 0, 5, 5); /* set V scaling */ REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), scale_y ? 1 : 0, 6, 6); dispc_ovl_set_vid_accu2_0(plane, 0x80, 0); dispc_ovl_set_vid_accu2_1(plane, 0x80, 0); } static void dispc_ovl_set_scaling(enum omap_plane plane, u16 orig_width, u16 orig_height, u16 out_width, u16 out_height, bool ilace, bool five_taps, bool fieldmode, enum omap_color_mode color_mode, u8 rotation) { BUG_ON(plane == OMAP_DSS_GFX); dispc_ovl_set_scaling_common(plane, orig_width, orig_height, out_width, out_height, ilace, five_taps, fieldmode, color_mode, rotation); dispc_ovl_set_scaling_uv(plane, orig_width, orig_height, out_width, out_height, ilace, five_taps, fieldmode, color_mode, rotation); } static void dispc_ovl_set_rotation_attrs(enum omap_plane plane, u8 rotation, bool mirroring, enum omap_color_mode color_mode) { bool row_repeat = false; int vidrot = 0; if (color_mode == OMAP_DSS_COLOR_YUV2 || color_mode == OMAP_DSS_COLOR_UYVY) { if (mirroring) { switch (rotation) { case OMAP_DSS_ROT_0: vidrot = 2; break; case OMAP_DSS_ROT_90: vidrot = 1; break; case OMAP_DSS_ROT_180: vidrot = 0; break; case OMAP_DSS_ROT_270: vidrot = 3; break; } } else { switch (rotation) { case OMAP_DSS_ROT_0: vidrot = 0; break; case OMAP_DSS_ROT_90: vidrot = 1; break; case OMAP_DSS_ROT_180: vidrot = 2; break; case OMAP_DSS_ROT_270: vidrot = 3; break; } } if (rotation == OMAP_DSS_ROT_90 || rotation == OMAP_DSS_ROT_270) row_repeat = true; else row_repeat = false; } REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), vidrot, 13, 12); if (dss_has_feature(FEAT_ROWREPEATENABLE)) REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), row_repeat ? 1 : 0, 18, 18); } static int color_mode_to_bpp(enum omap_color_mode color_mode) { switch (color_mode) { case OMAP_DSS_COLOR_CLUT1: return 1; case OMAP_DSS_COLOR_CLUT2: return 2; case OMAP_DSS_COLOR_CLUT4: return 4; case OMAP_DSS_COLOR_CLUT8: case OMAP_DSS_COLOR_NV12: return 8; case OMAP_DSS_COLOR_RGB12U: case OMAP_DSS_COLOR_RGB16: case OMAP_DSS_COLOR_ARGB16: case OMAP_DSS_COLOR_YUV2: case OMAP_DSS_COLOR_UYVY: case OMAP_DSS_COLOR_RGBA16: case OMAP_DSS_COLOR_RGBX16: case OMAP_DSS_COLOR_ARGB16_1555: case OMAP_DSS_COLOR_XRGB16_1555: return 16; case OMAP_DSS_COLOR_RGB24P: return 24; case OMAP_DSS_COLOR_RGB24U: case OMAP_DSS_COLOR_ARGB32: case OMAP_DSS_COLOR_RGBA32: case OMAP_DSS_COLOR_RGBX32: return 32; default: BUG(); } } static s32 pixinc(int pixels, u8 ps) { if (pixels == 1) return 1; else if (pixels > 1) return 1 + (pixels - 1) * ps; else if (pixels < 0) return 1 - (-pixels + 1) * ps; else BUG(); } static void calc_vrfb_rotation_offset(u8 rotation, bool mirror, u16 screen_width, u16 width, u16 height, enum omap_color_mode color_mode, bool fieldmode, unsigned int field_offset, unsigned *offset0, unsigned *offset1, s32 *row_inc, s32 *pix_inc) { u8 ps; /* FIXME CLUT formats */ switch (color_mode) { case OMAP_DSS_COLOR_CLUT1: case OMAP_DSS_COLOR_CLUT2: case OMAP_DSS_COLOR_CLUT4: case OMAP_DSS_COLOR_CLUT8: BUG(); return; case OMAP_DSS_COLOR_YUV2: case OMAP_DSS_COLOR_UYVY: ps = 4; break; default: ps = color_mode_to_bpp(color_mode) / 8; break; } DSSDBG("calc_rot(%d): scrw %d, %dx%d\n", rotation, screen_width, width, height); /* * field 0 = even field = bottom field * field 1 = odd field = top field */ switch (rotation + mirror * 4) { case OMAP_DSS_ROT_0: case OMAP_DSS_ROT_180: /* * If the pixel format is YUV or UYVY divide the width * of the image by 2 for 0 and 180 degree rotation. */ if (color_mode == OMAP_DSS_COLOR_YUV2 || color_mode == OMAP_DSS_COLOR_UYVY) width = width >> 1; case OMAP_DSS_ROT_90: case OMAP_DSS_ROT_270: *offset1 = 0; if (field_offset) *offset0 = field_offset * screen_width * ps; else *offset0 = 0; *row_inc = pixinc(1 + (screen_width - width) + (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(1, ps); break; case OMAP_DSS_ROT_0 + 4: case OMAP_DSS_ROT_180 + 4: /* If the pixel format is YUV or UYVY divide the width * of the image by 2 for 0 degree and 180 degree */ if (color_mode == OMAP_DSS_COLOR_YUV2 || color_mode == OMAP_DSS_COLOR_UYVY) width = width >> 1; case OMAP_DSS_ROT_90 + 4: case OMAP_DSS_ROT_270 + 4: *offset1 = 0; if (field_offset) *offset0 = field_offset * screen_width * ps; else *offset0 = 0; *row_inc = pixinc(1 - (screen_width + width) - (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(1, ps); break; default: BUG(); } } static void calc_dma_rotation_offset(u8 rotation, bool mirror, u16 screen_width, u16 width, u16 height, enum omap_color_mode color_mode, bool fieldmode, unsigned int field_offset, unsigned *offset0, unsigned *offset1, s32 *row_inc, s32 *pix_inc) { u8 ps; u16 fbw, fbh; /* FIXME CLUT formats */ switch (color_mode) { case OMAP_DSS_COLOR_CLUT1: case OMAP_DSS_COLOR_CLUT2: case OMAP_DSS_COLOR_CLUT4: case OMAP_DSS_COLOR_CLUT8: BUG(); return; default: ps = color_mode_to_bpp(color_mode) / 8; break; } DSSDBG("calc_rot(%d): scrw %d, %dx%d\n", rotation, screen_width, width, height); /* width & height are overlay sizes, convert to fb sizes */ if (rotation == OMAP_DSS_ROT_0 || rotation == OMAP_DSS_ROT_180) { fbw = width; fbh = height; } else { fbw = height; fbh = width; } /* * field 0 = even field = bottom field * field 1 = odd field = top field */ switch (rotation + mirror * 4) { case OMAP_DSS_ROT_0: *offset1 = 0; if (field_offset) *offset0 = *offset1 + field_offset * screen_width * ps; else *offset0 = *offset1; *row_inc = pixinc(1 + (screen_width - fbw) + (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(1, ps); break; case OMAP_DSS_ROT_90: *offset1 = screen_width * (fbh - 1) * ps; if (field_offset) *offset0 = *offset1 + field_offset * ps; else *offset0 = *offset1; *row_inc = pixinc(screen_width * (fbh - 1) + 1 + (fieldmode ? 1 : 0), ps); *pix_inc = pixinc(-screen_width, ps); break; case OMAP_DSS_ROT_180: *offset1 = (screen_width * (fbh - 1) + fbw - 1) * ps; if (field_offset) *offset0 = *offset1 - field_offset * screen_width * ps; else *offset0 = *offset1; *row_inc = pixinc(-1 - (screen_width - fbw) - (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(-1, ps); break; case OMAP_DSS_ROT_270: *offset1 = (fbw - 1) * ps; if (field_offset) *offset0 = *offset1 - field_offset * ps; else *offset0 = *offset1; *row_inc = pixinc(-screen_width * (fbh - 1) - 1 - (fieldmode ? 1 : 0), ps); *pix_inc = pixinc(screen_width, ps); break; /* mirroring */ case OMAP_DSS_ROT_0 + 4: *offset1 = (fbw - 1) * ps; if (field_offset) *offset0 = *offset1 + field_offset * screen_width * ps; else *offset0 = *offset1; *row_inc = pixinc(screen_width * 2 - 1 + (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(-1, ps); break; case OMAP_DSS_ROT_90 + 4: *offset1 = 0; if (field_offset) *offset0 = *offset1 + field_offset * ps; else *offset0 = *offset1; *row_inc = pixinc(-screen_width * (fbh - 1) + 1 + (fieldmode ? 1 : 0), ps); *pix_inc = pixinc(screen_width, ps); break; case OMAP_DSS_ROT_180 + 4: *offset1 = screen_width * (fbh - 1) * ps; if (field_offset) *offset0 = *offset1 - field_offset * screen_width * ps; else *offset0 = *offset1; *row_inc = pixinc(1 - screen_width * 2 - (fieldmode ? screen_width : 0), ps); *pix_inc = pixinc(1, ps); break; case OMAP_DSS_ROT_270 + 4: *offset1 = (screen_width * (fbh - 1) + fbw - 1) * ps; if (field_offset) *offset0 = *offset1 - field_offset * ps; else *offset0 = *offset1; *row_inc = pixinc(screen_width * (fbh - 1) - 1 - (fieldmode ? 1 : 0), ps); *pix_inc = pixinc(-screen_width, ps); break; default: BUG(); } } static unsigned long calc_fclk_five_taps(enum omap_channel channel, u16 width, u16 height, u16 out_width, u16 out_height, enum omap_color_mode color_mode) { u32 fclk = 0; u64 tmp, pclk = dispc_mgr_pclk_rate(channel); if (height <= out_height && width <= out_width) return (unsigned long) pclk; if (height > out_height) { struct omap_dss_device *dssdev = dispc_mgr_get_device(channel); unsigned int ppl = dssdev->panel.timings.x_res; tmp = pclk * height * out_width; do_div(tmp, 2 * out_height * ppl); fclk = tmp; if (height > 2 * out_height) { if (ppl == out_width) return 0; tmp = pclk * (height - 2 * out_height) * out_width; do_div(tmp, 2 * out_height * (ppl - out_width)); fclk = max(fclk, (u32) tmp); } } if (width > out_width) { tmp = pclk * width; do_div(tmp, out_width); fclk = max(fclk, (u32) tmp); if (color_mode == OMAP_DSS_COLOR_RGB24U) fclk <<= 1; } return fclk; } static unsigned long calc_fclk(enum omap_channel channel, u16 width, u16 height, u16 out_width, u16 out_height) { unsigned int hf, vf; unsigned long pclk = dispc_mgr_pclk_rate(channel); /* * FIXME how to determine the 'A' factor * for the no downscaling case ? */ if (width > 3 * out_width) hf = 4; else if (width > 2 * out_width) hf = 3; else if (width > out_width) hf = 2; else hf = 1; if (height > out_height) vf = 2; else vf = 1; if (cpu_is_omap24xx()) { if (vf > 1 && hf > 1) return pclk * 4; else return pclk * 2; } else if (cpu_is_omap34xx()) { return pclk * vf * hf; } else { if (hf > 1) return DIV_ROUND_UP(pclk, out_width) * width; else return pclk; } } static int dispc_ovl_calc_scaling(enum omap_plane plane, enum omap_channel channel, u16 width, u16 height, u16 out_width, u16 out_height, enum omap_color_mode color_mode, bool *five_taps) { struct omap_overlay *ovl = omap_dss_get_overlay(plane); const int maxdownscale = dss_feat_get_param_max(FEAT_PARAM_DOWNSCALE); const int maxsinglelinewidth = dss_feat_get_param_max(FEAT_PARAM_LINEWIDTH); unsigned long fclk = 0; if (width == out_width && height == out_height) return 0; if ((ovl->caps & OMAP_DSS_OVL_CAP_SCALE) == 0) return -EINVAL; if (out_width < width / maxdownscale || out_width > width * 8) return -EINVAL; if (out_height < height / maxdownscale || out_height > height * 8) return -EINVAL; if (cpu_is_omap24xx()) { if (width > maxsinglelinewidth) DSSERR("Cannot scale max input width exceeded"); *five_taps = false; fclk = calc_fclk(channel, width, height, out_width, out_height); } else if (cpu_is_omap34xx()) { if (width > (maxsinglelinewidth * 2)) { DSSERR("Cannot setup scaling"); DSSERR("width exceeds maximum width possible"); return -EINVAL; } fclk = calc_fclk_five_taps(channel, width, height, out_width, out_height, color_mode); if (width > maxsinglelinewidth) { if (height > out_height && height < out_height * 2) *five_taps = false; else { DSSERR("cannot setup scaling with five taps"); return -EINVAL; } } if (!*five_taps) fclk = calc_fclk(channel, width, height, out_width, out_height); } else { if (width > maxsinglelinewidth) { DSSERR("Cannot scale width exceeds max line width"); return -EINVAL; } fclk = calc_fclk(channel, width, height, out_width, out_height); } DSSDBG("required fclk rate = %lu Hz\n", fclk); DSSDBG("current fclk rate = %lu Hz\n", dispc_fclk_rate()); if (!fclk || fclk > dispc_fclk_rate()) { DSSERR("failed to set up scaling, " "required fclk rate = %lu Hz, " "current fclk rate = %lu Hz\n", fclk, dispc_fclk_rate()); return -EINVAL; } return 0; } int dispc_ovl_setup(enum omap_plane plane, struct omap_overlay_info *oi, bool ilace, bool replication) { struct omap_overlay *ovl = omap_dss_get_overlay(plane); bool five_taps = true; bool fieldmode = 0; int r, cconv = 0; unsigned offset0, offset1; s32 row_inc; s32 pix_inc; u16 frame_height = oi->height; unsigned int field_offset = 0; u16 outw, outh; enum omap_channel channel; channel = dispc_ovl_get_channel_out(plane); DSSDBG("dispc_ovl_setup %d, pa %x, pa_uv %x, sw %d, %d,%d, %dx%d -> " "%dx%d, cmode %x, rot %d, mir %d, ilace %d chan %d repl %d\n", plane, oi->paddr, oi->p_uv_addr, oi->screen_width, oi->pos_x, oi->pos_y, oi->width, oi->height, oi->out_width, oi->out_height, oi->color_mode, oi->rotation, oi->mirror, ilace, channel, replication); if (oi->paddr == 0) return -EINVAL; outw = oi->out_width == 0 ? oi->width : oi->out_width; outh = oi->out_height == 0 ? oi->height : oi->out_height; if (ilace && oi->height == outh) fieldmode = 1; if (ilace) { if (fieldmode) oi->height /= 2; oi->pos_y /= 2; outh /= 2; DSSDBG("adjusting for ilace: height %d, pos_y %d, " "out_height %d\n", oi->height, oi->pos_y, outh); } if (!dss_feat_color_mode_supported(plane, oi->color_mode)) return -EINVAL; r = dispc_ovl_calc_scaling(plane, channel, oi->width, oi->height, outw, outh, oi->color_mode, &five_taps); if (r) return r; if (oi->color_mode == OMAP_DSS_COLOR_YUV2 || oi->color_mode == OMAP_DSS_COLOR_UYVY || oi->color_mode == OMAP_DSS_COLOR_NV12) cconv = 1; if (ilace && !fieldmode) { /* * when downscaling the bottom field may have to start several * source lines below the top field. Unfortunately ACCUI * registers will only hold the fractional part of the offset * so the integer part must be added to the base address of the * bottom field. */ if (!oi->height || oi->height == outh) field_offset = 0; else field_offset = oi->height / outh / 2; } /* Fields are independent but interleaved in memory. */ if (fieldmode) field_offset = 1; if (oi->rotation_type == OMAP_DSS_ROT_DMA) calc_dma_rotation_offset(oi->rotation, oi->mirror, oi->screen_width, oi->width, frame_height, oi->color_mode, fieldmode, field_offset, &offset0, &offset1, &row_inc, &pix_inc); else calc_vrfb_rotation_offset(oi->rotation, oi->mirror, oi->screen_width, oi->width, frame_height, oi->color_mode, fieldmode, field_offset, &offset0, &offset1, &row_inc, &pix_inc); DSSDBG("offset0 %u, offset1 %u, row_inc %d, pix_inc %d\n", offset0, offset1, row_inc, pix_inc); dispc_ovl_set_color_mode(plane, oi->color_mode); dispc_ovl_set_ba0(plane, oi->paddr + offset0); dispc_ovl_set_ba1(plane, oi->paddr + offset1); if (OMAP_DSS_COLOR_NV12 == oi->color_mode) { dispc_ovl_set_ba0_uv(plane, oi->p_uv_addr + offset0); dispc_ovl_set_ba1_uv(plane, oi->p_uv_addr + offset1); } dispc_ovl_set_row_inc(plane, row_inc); dispc_ovl_set_pix_inc(plane, pix_inc); DSSDBG("%d,%d %dx%d -> %dx%d\n", oi->pos_x, oi->pos_y, oi->width, oi->height, outw, outh); dispc_ovl_set_pos(plane, oi->pos_x, oi->pos_y); dispc_ovl_set_pic_size(plane, oi->width, oi->height); if (ovl->caps & OMAP_DSS_OVL_CAP_SCALE) { dispc_ovl_set_scaling(plane, oi->width, oi->height, outw, outh, ilace, five_taps, fieldmode, oi->color_mode, oi->rotation); dispc_ovl_set_vid_size(plane, outw, outh); dispc_ovl_set_vid_color_conv(plane, cconv); } dispc_ovl_set_rotation_attrs(plane, oi->rotation, oi->mirror, oi->color_mode); dispc_ovl_set_zorder(plane, oi->zorder); dispc_ovl_set_pre_mult_alpha(plane, oi->pre_mult_alpha); dispc_ovl_setup_global_alpha(plane, oi->global_alpha); dispc_ovl_enable_replication(plane, replication); return 0; } int dispc_ovl_enable(enum omap_plane plane, bool enable) { DSSDBG("dispc_enable_plane %d, %d\n", plane, enable); REG_FLD_MOD(DISPC_OVL_ATTRIBUTES(plane), enable ? 1 : 0, 0, 0); return 0; } static void dispc_disable_isr(void *data, u32 mask) { struct completion *compl = data; complete(compl); } static void _enable_lcd_out(enum omap_channel channel, bool enable) { if (channel == OMAP_DSS_CHANNEL_LCD2) { REG_FLD_MOD(DISPC_CONTROL2, enable ? 1 : 0, 0, 0); /* flush posted write */ dispc_read_reg(DISPC_CONTROL2); } else { REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 0, 0); dispc_read_reg(DISPC_CONTROL); } } static void dispc_mgr_enable_lcd_out(enum omap_channel channel, bool enable) { struct completion frame_done_completion; bool is_on; int r; u32 irq; /* When we disable LCD output, we need to wait until frame is done. * Otherwise the DSS is still working, and turning off the clocks * prevents DSS from going to OFF mode */ is_on = channel == OMAP_DSS_CHANNEL_LCD2 ? REG_GET(DISPC_CONTROL2, 0, 0) : REG_GET(DISPC_CONTROL, 0, 0); irq = channel == OMAP_DSS_CHANNEL_LCD2 ? DISPC_IRQ_FRAMEDONE2 : DISPC_IRQ_FRAMEDONE; if (!enable && is_on) { init_completion(&frame_done_completion); r = omap_dispc_register_isr(dispc_disable_isr, &frame_done_completion, irq); if (r) DSSERR("failed to register FRAMEDONE isr\n"); } _enable_lcd_out(channel, enable); if (!enable && is_on) { if (!wait_for_completion_timeout(&frame_done_completion, msecs_to_jiffies(100))) DSSERR("timeout waiting for FRAME DONE\n"); r = omap_dispc_unregister_isr(dispc_disable_isr, &frame_done_completion, irq); if (r) DSSERR("failed to unregister FRAMEDONE isr\n"); } } static void _enable_digit_out(bool enable) { REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 1, 1); /* flush posted write */ dispc_read_reg(DISPC_CONTROL); } static void dispc_mgr_enable_digit_out(bool enable) { struct completion frame_done_completion; enum dss_hdmi_venc_clk_source_select src; int r, i; u32 irq_mask; int num_irqs; if (REG_GET(DISPC_CONTROL, 1, 1) == enable) return; src = dss_get_hdmi_venc_clk_source(); if (enable) { unsigned long flags; /* When we enable digit output, we'll get an extra digit * sync lost interrupt, that we need to ignore */ spin_lock_irqsave(&dispc.irq_lock, flags); dispc.irq_error_mask &= ~DISPC_IRQ_SYNC_LOST_DIGIT; _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); } /* When we disable digit output, we need to wait until fields are done. * Otherwise the DSS is still working, and turning off the clocks * prevents DSS from going to OFF mode. And when enabling, we need to * wait for the extra sync losts */ init_completion(&frame_done_completion); if (src == DSS_HDMI_M_PCLK && enable == false) { irq_mask = DISPC_IRQ_FRAMEDONETV; num_irqs = 1; } else { irq_mask = DISPC_IRQ_EVSYNC_EVEN | DISPC_IRQ_EVSYNC_ODD; /* XXX I understand from TRM that we should only wait for the * current field to complete. But it seems we have to wait for * both fields */ num_irqs = 2; } r = omap_dispc_register_isr(dispc_disable_isr, &frame_done_completion, irq_mask); if (r) DSSERR("failed to register %x isr\n", irq_mask); _enable_digit_out(enable); for (i = 0; i < num_irqs; ++i) { if (!wait_for_completion_timeout(&frame_done_completion, msecs_to_jiffies(100))) DSSERR("timeout waiting for digit out to %s\n", enable ? "start" : "stop"); } r = omap_dispc_unregister_isr(dispc_disable_isr, &frame_done_completion, irq_mask); if (r) DSSERR("failed to unregister %x isr\n", irq_mask); if (enable) { unsigned long flags; spin_lock_irqsave(&dispc.irq_lock, flags); dispc.irq_error_mask |= DISPC_IRQ_SYNC_LOST_DIGIT; dispc_write_reg(DISPC_IRQSTATUS, DISPC_IRQ_SYNC_LOST_DIGIT); _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); } } bool dispc_mgr_is_enabled(enum omap_channel channel) { if (channel == OMAP_DSS_CHANNEL_LCD) return !!REG_GET(DISPC_CONTROL, 0, 0); else if (channel == OMAP_DSS_CHANNEL_DIGIT) return !!REG_GET(DISPC_CONTROL, 1, 1); else if (channel == OMAP_DSS_CHANNEL_LCD2) return !!REG_GET(DISPC_CONTROL2, 0, 0); else BUG(); } void dispc_mgr_enable(enum omap_channel channel, bool enable) { if (dispc_mgr_is_lcd(channel)) dispc_mgr_enable_lcd_out(channel, enable); else if (channel == OMAP_DSS_CHANNEL_DIGIT) dispc_mgr_enable_digit_out(enable); else BUG(); } void dispc_lcd_enable_signal_polarity(bool act_high) { if (!dss_has_feature(FEAT_LCDENABLEPOL)) return; REG_FLD_MOD(DISPC_CONTROL, act_high ? 1 : 0, 29, 29); } void dispc_lcd_enable_signal(bool enable) { if (!dss_has_feature(FEAT_LCDENABLESIGNAL)) return; REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 28, 28); } void dispc_pck_free_enable(bool enable) { if (!dss_has_feature(FEAT_PCKFREEENABLE)) return; REG_FLD_MOD(DISPC_CONTROL, enable ? 1 : 0, 27, 27); } void dispc_mgr_enable_fifohandcheck(enum omap_channel channel, bool enable) { if (channel == OMAP_DSS_CHANNEL_LCD2) REG_FLD_MOD(DISPC_CONFIG2, enable ? 1 : 0, 16, 16); else REG_FLD_MOD(DISPC_CONFIG, enable ? 1 : 0, 16, 16); } void dispc_mgr_set_lcd_display_type(enum omap_channel channel, enum omap_lcd_display_type type) { int mode; switch (type) { case OMAP_DSS_LCD_DISPLAY_STN: mode = 0; break; case OMAP_DSS_LCD_DISPLAY_TFT: mode = 1; break; default: BUG(); return; } if (channel == OMAP_DSS_CHANNEL_LCD2) REG_FLD_MOD(DISPC_CONTROL2, mode, 3, 3); else REG_FLD_MOD(DISPC_CONTROL, mode, 3, 3); } void dispc_set_loadmode(enum omap_dss_load_mode mode) { REG_FLD_MOD(DISPC_CONFIG, mode, 2, 1); } static void dispc_mgr_set_default_color(enum omap_channel channel, u32 color) { dispc_write_reg(DISPC_DEFAULT_COLOR(channel), color); } static void dispc_mgr_set_trans_key(enum omap_channel ch, enum omap_dss_trans_key_type type, u32 trans_key) { if (ch == OMAP_DSS_CHANNEL_LCD) REG_FLD_MOD(DISPC_CONFIG, type, 11, 11); else if (ch == OMAP_DSS_CHANNEL_DIGIT) REG_FLD_MOD(DISPC_CONFIG, type, 13, 13); else /* OMAP_DSS_CHANNEL_LCD2 */ REG_FLD_MOD(DISPC_CONFIG2, type, 11, 11); dispc_write_reg(DISPC_TRANS_COLOR(ch), trans_key); } static void dispc_mgr_enable_trans_key(enum omap_channel ch, bool enable) { if (ch == OMAP_DSS_CHANNEL_LCD) REG_FLD_MOD(DISPC_CONFIG, enable, 10, 10); else if (ch == OMAP_DSS_CHANNEL_DIGIT) REG_FLD_MOD(DISPC_CONFIG, enable, 12, 12); else /* OMAP_DSS_CHANNEL_LCD2 */ REG_FLD_MOD(DISPC_CONFIG2, enable, 10, 10); } static void dispc_mgr_enable_alpha_fixed_zorder(enum omap_channel ch, bool enable) { if (!dss_has_feature(FEAT_ALPHA_FIXED_ZORDER)) return; if (ch == OMAP_DSS_CHANNEL_LCD) REG_FLD_MOD(DISPC_CONFIG, enable, 18, 18); else if (ch == OMAP_DSS_CHANNEL_DIGIT) REG_FLD_MOD(DISPC_CONFIG, enable, 19, 19); } void dispc_mgr_setup(enum omap_channel channel, struct omap_overlay_manager_info *info) { dispc_mgr_set_default_color(channel, info->default_color); dispc_mgr_set_trans_key(channel, info->trans_key_type, info->trans_key); dispc_mgr_enable_trans_key(channel, info->trans_enabled); dispc_mgr_enable_alpha_fixed_zorder(channel, info->partial_alpha_enabled); if (dss_has_feature(FEAT_CPR)) { dispc_mgr_enable_cpr(channel, info->cpr_enable); dispc_mgr_set_cpr_coef(channel, &info->cpr_coefs); } } void dispc_mgr_set_tft_data_lines(enum omap_channel channel, u8 data_lines) { int code; switch (data_lines) { case 12: code = 0; break; case 16: code = 1; break; case 18: code = 2; break; case 24: code = 3; break; default: BUG(); return; } if (channel == OMAP_DSS_CHANNEL_LCD2) REG_FLD_MOD(DISPC_CONTROL2, code, 9, 8); else REG_FLD_MOD(DISPC_CONTROL, code, 9, 8); } void dispc_mgr_set_io_pad_mode(enum dss_io_pad_mode mode) { u32 l; int gpout0, gpout1; switch (mode) { case DSS_IO_PAD_MODE_RESET: gpout0 = 0; gpout1 = 0; break; case DSS_IO_PAD_MODE_RFBI: gpout0 = 1; gpout1 = 0; break; case DSS_IO_PAD_MODE_BYPASS: gpout0 = 1; gpout1 = 1; break; default: BUG(); return; } l = dispc_read_reg(DISPC_CONTROL); l = FLD_MOD(l, gpout0, 15, 15); l = FLD_MOD(l, gpout1, 16, 16); dispc_write_reg(DISPC_CONTROL, l); } void dispc_mgr_enable_stallmode(enum omap_channel channel, bool enable) { if (channel == OMAP_DSS_CHANNEL_LCD2) REG_FLD_MOD(DISPC_CONTROL2, enable, 11, 11); else REG_FLD_MOD(DISPC_CONTROL, enable, 11, 11); } static bool _dispc_lcd_timings_ok(int hsw, int hfp, int hbp, int vsw, int vfp, int vbp) { if (cpu_is_omap24xx() || omap_rev() < OMAP3430_REV_ES3_0) { if (hsw < 1 || hsw > 64 || hfp < 1 || hfp > 256 || hbp < 1 || hbp > 256 || vsw < 1 || vsw > 64 || vfp < 0 || vfp > 255 || vbp < 0 || vbp > 255) return false; } else { if (hsw < 1 || hsw > 256 || hfp < 1 || hfp > 4096 || hbp < 1 || hbp > 4096 || vsw < 1 || vsw > 256 || vfp < 0 || vfp > 4095 || vbp < 0 || vbp > 4095) return false; } return true; } bool dispc_lcd_timings_ok(struct omap_video_timings *timings) { return _dispc_lcd_timings_ok(timings->hsw, timings->hfp, timings->hbp, timings->vsw, timings->vfp, timings->vbp); } static void _dispc_mgr_set_lcd_timings(enum omap_channel channel, int hsw, int hfp, int hbp, int vsw, int vfp, int vbp) { u32 timing_h, timing_v; if (cpu_is_omap24xx() || omap_rev() < OMAP3430_REV_ES3_0) { timing_h = FLD_VAL(hsw-1, 5, 0) | FLD_VAL(hfp-1, 15, 8) | FLD_VAL(hbp-1, 27, 20); timing_v = FLD_VAL(vsw-1, 5, 0) | FLD_VAL(vfp, 15, 8) | FLD_VAL(vbp, 27, 20); } else { timing_h = FLD_VAL(hsw-1, 7, 0) | FLD_VAL(hfp-1, 19, 8) | FLD_VAL(hbp-1, 31, 20); timing_v = FLD_VAL(vsw-1, 7, 0) | FLD_VAL(vfp, 19, 8) | FLD_VAL(vbp, 31, 20); } dispc_write_reg(DISPC_TIMING_H(channel), timing_h); dispc_write_reg(DISPC_TIMING_V(channel), timing_v); } /* change name to mode? */ void dispc_mgr_set_lcd_timings(enum omap_channel channel, struct omap_video_timings *timings) { unsigned xtot, ytot; unsigned long ht, vt; if (!_dispc_lcd_timings_ok(timings->hsw, timings->hfp, timings->hbp, timings->vsw, timings->vfp, timings->vbp)) BUG(); _dispc_mgr_set_lcd_timings(channel, timings->hsw, timings->hfp, timings->hbp, timings->vsw, timings->vfp, timings->vbp); dispc_mgr_set_lcd_size(channel, timings->x_res, timings->y_res); xtot = timings->x_res + timings->hfp + timings->hsw + timings->hbp; ytot = timings->y_res + timings->vfp + timings->vsw + timings->vbp; ht = (timings->pixel_clock * 1000) / xtot; vt = (timings->pixel_clock * 1000) / xtot / ytot; DSSDBG("channel %d xres %u yres %u\n", channel, timings->x_res, timings->y_res); DSSDBG("pck %u\n", timings->pixel_clock); DSSDBG("hsw %d hfp %d hbp %d vsw %d vfp %d vbp %d\n", timings->hsw, timings->hfp, timings->hbp, timings->vsw, timings->vfp, timings->vbp); DSSDBG("hsync %luHz, vsync %luHz\n", ht, vt); } static void dispc_mgr_set_lcd_divisor(enum omap_channel channel, u16 lck_div, u16 pck_div) { BUG_ON(lck_div < 1); BUG_ON(pck_div < 1); dispc_write_reg(DISPC_DIVISORo(channel), FLD_VAL(lck_div, 23, 16) | FLD_VAL(pck_div, 7, 0)); } static void dispc_mgr_get_lcd_divisor(enum omap_channel channel, int *lck_div, int *pck_div) { u32 l; l = dispc_read_reg(DISPC_DIVISORo(channel)); *lck_div = FLD_GET(l, 23, 16); *pck_div = FLD_GET(l, 7, 0); } unsigned long dispc_fclk_rate(void) { struct platform_device *dsidev; unsigned long r = 0; switch (dss_get_dispc_clk_source()) { case OMAP_DSS_CLK_SRC_FCK: r = clk_get_rate(dispc.dss_clk); break; case OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DISPC: dsidev = dsi_get_dsidev_from_id(0); r = dsi_get_pll_hsdiv_dispc_rate(dsidev); break; case OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DISPC: dsidev = dsi_get_dsidev_from_id(1); r = dsi_get_pll_hsdiv_dispc_rate(dsidev); break; default: BUG(); } return r; } unsigned long dispc_mgr_lclk_rate(enum omap_channel channel) { struct platform_device *dsidev; int lcd; unsigned long r; u32 l; l = dispc_read_reg(DISPC_DIVISORo(channel)); lcd = FLD_GET(l, 23, 16); switch (dss_get_lcd_clk_source(channel)) { case OMAP_DSS_CLK_SRC_FCK: r = clk_get_rate(dispc.dss_clk); break; case OMAP_DSS_CLK_SRC_DSI_PLL_HSDIV_DISPC: dsidev = dsi_get_dsidev_from_id(0); r = dsi_get_pll_hsdiv_dispc_rate(dsidev); break; case OMAP_DSS_CLK_SRC_DSI2_PLL_HSDIV_DISPC: dsidev = dsi_get_dsidev_from_id(1); r = dsi_get_pll_hsdiv_dispc_rate(dsidev); break; default: BUG(); } return r / lcd; } unsigned long dispc_mgr_pclk_rate(enum omap_channel channel) { unsigned long r; if (dispc_mgr_is_lcd(channel)) { int pcd; u32 l; l = dispc_read_reg(DISPC_DIVISORo(channel)); pcd = FLD_GET(l, 7, 0); r = dispc_mgr_lclk_rate(channel); return r / pcd; } else { struct omap_dss_device *dssdev = dispc_mgr_get_device(channel); switch (dssdev->type) { case OMAP_DISPLAY_TYPE_VENC: return venc_get_pixel_clock(); case OMAP_DISPLAY_TYPE_HDMI: return hdmi_get_pixel_clock(); default: BUG(); } } } void dispc_dump_clocks(struct seq_file *s) { int lcd, pcd; u32 l; enum omap_dss_clk_source dispc_clk_src = dss_get_dispc_clk_source(); enum omap_dss_clk_source lcd_clk_src; if (dispc_runtime_get()) return; seq_printf(s, "- DISPC -\n"); seq_printf(s, "dispc fclk source = %s (%s)\n", dss_get_generic_clk_source_name(dispc_clk_src), dss_feat_get_clk_source_name(dispc_clk_src)); seq_printf(s, "fck\t\t%-16lu\n", dispc_fclk_rate()); if (dss_has_feature(FEAT_CORE_CLK_DIV)) { seq_printf(s, "- DISPC-CORE-CLK -\n"); l = dispc_read_reg(DISPC_DIVISOR); lcd = FLD_GET(l, 23, 16); seq_printf(s, "lck\t\t%-16lulck div\t%u\n", (dispc_fclk_rate()/lcd), lcd); } seq_printf(s, "- LCD1 -\n"); lcd_clk_src = dss_get_lcd_clk_source(OMAP_DSS_CHANNEL_LCD); seq_printf(s, "lcd1_clk source = %s (%s)\n", dss_get_generic_clk_source_name(lcd_clk_src), dss_feat_get_clk_source_name(lcd_clk_src)); dispc_mgr_get_lcd_divisor(OMAP_DSS_CHANNEL_LCD, &lcd, &pcd); seq_printf(s, "lck\t\t%-16lulck div\t%u\n", dispc_mgr_lclk_rate(OMAP_DSS_CHANNEL_LCD), lcd); seq_printf(s, "pck\t\t%-16lupck div\t%u\n", dispc_mgr_pclk_rate(OMAP_DSS_CHANNEL_LCD), pcd); if (dss_has_feature(FEAT_MGR_LCD2)) { seq_printf(s, "- LCD2 -\n"); lcd_clk_src = dss_get_lcd_clk_source(OMAP_DSS_CHANNEL_LCD2); seq_printf(s, "lcd2_clk source = %s (%s)\n", dss_get_generic_clk_source_name(lcd_clk_src), dss_feat_get_clk_source_name(lcd_clk_src)); dispc_mgr_get_lcd_divisor(OMAP_DSS_CHANNEL_LCD2, &lcd, &pcd); seq_printf(s, "lck\t\t%-16lulck div\t%u\n", dispc_mgr_lclk_rate(OMAP_DSS_CHANNEL_LCD2), lcd); seq_printf(s, "pck\t\t%-16lupck div\t%u\n", dispc_mgr_pclk_rate(OMAP_DSS_CHANNEL_LCD2), pcd); } dispc_runtime_put(); } #ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS void dispc_dump_irqs(struct seq_file *s) { unsigned long flags; struct dispc_irq_stats stats; spin_lock_irqsave(&dispc.irq_stats_lock, flags); stats = dispc.irq_stats; memset(&dispc.irq_stats, 0, sizeof(dispc.irq_stats)); dispc.irq_stats.last_reset = jiffies; spin_unlock_irqrestore(&dispc.irq_stats_lock, flags); seq_printf(s, "period %u ms\n", jiffies_to_msecs(jiffies - stats.last_reset)); seq_printf(s, "irqs %d\n", stats.irq_count); #define PIS(x) \ seq_printf(s, "%-20s %10d\n", #x, stats.irqs[ffs(DISPC_IRQ_##x)-1]); PIS(FRAMEDONE); PIS(VSYNC); PIS(EVSYNC_EVEN); PIS(EVSYNC_ODD); PIS(ACBIAS_COUNT_STAT); PIS(PROG_LINE_NUM); PIS(GFX_FIFO_UNDERFLOW); PIS(GFX_END_WIN); PIS(PAL_GAMMA_MASK); PIS(OCP_ERR); PIS(VID1_FIFO_UNDERFLOW); PIS(VID1_END_WIN); PIS(VID2_FIFO_UNDERFLOW); PIS(VID2_END_WIN); if (dss_feat_get_num_ovls() > 3) { PIS(VID3_FIFO_UNDERFLOW); PIS(VID3_END_WIN); } PIS(SYNC_LOST); PIS(SYNC_LOST_DIGIT); PIS(WAKEUP); if (dss_has_feature(FEAT_MGR_LCD2)) { PIS(FRAMEDONE2); PIS(VSYNC2); PIS(ACBIAS_COUNT_STAT2); PIS(SYNC_LOST2); } #undef PIS } #endif void dispc_dump_regs(struct seq_file *s) { int i, j; const char *mgr_names[] = { [OMAP_DSS_CHANNEL_LCD] = "LCD", [OMAP_DSS_CHANNEL_DIGIT] = "TV", [OMAP_DSS_CHANNEL_LCD2] = "LCD2", }; const char *ovl_names[] = { [OMAP_DSS_GFX] = "GFX", [OMAP_DSS_VIDEO1] = "VID1", [OMAP_DSS_VIDEO2] = "VID2", [OMAP_DSS_VIDEO3] = "VID3", }; const char **p_names; #define DUMPREG(r) seq_printf(s, "%-50s %08x\n", #r, dispc_read_reg(r)) if (dispc_runtime_get()) return; /* DISPC common registers */ DUMPREG(DISPC_REVISION); DUMPREG(DISPC_SYSCONFIG); DUMPREG(DISPC_SYSSTATUS); DUMPREG(DISPC_IRQSTATUS); DUMPREG(DISPC_IRQENABLE); DUMPREG(DISPC_CONTROL); DUMPREG(DISPC_CONFIG); DUMPREG(DISPC_CAPABLE); DUMPREG(DISPC_LINE_STATUS); DUMPREG(DISPC_LINE_NUMBER); if (dss_has_feature(FEAT_ALPHA_FIXED_ZORDER) || dss_has_feature(FEAT_ALPHA_FREE_ZORDER)) DUMPREG(DISPC_GLOBAL_ALPHA); if (dss_has_feature(FEAT_MGR_LCD2)) { DUMPREG(DISPC_CONTROL2); DUMPREG(DISPC_CONFIG2); } #undef DUMPREG #define DISPC_REG(i, name) name(i) #define DUMPREG(i, r) seq_printf(s, "%s(%s)%*s %08x\n", #r, p_names[i], \ 48 - strlen(#r) - strlen(p_names[i]), " ", \ dispc_read_reg(DISPC_REG(i, r))) p_names = mgr_names; /* DISPC channel specific registers */ for (i = 0; i < dss_feat_get_num_mgrs(); i++) { DUMPREG(i, DISPC_DEFAULT_COLOR); DUMPREG(i, DISPC_TRANS_COLOR); DUMPREG(i, DISPC_SIZE_MGR); if (i == OMAP_DSS_CHANNEL_DIGIT) continue; DUMPREG(i, DISPC_DEFAULT_COLOR); DUMPREG(i, DISPC_TRANS_COLOR); DUMPREG(i, DISPC_TIMING_H); DUMPREG(i, DISPC_TIMING_V); DUMPREG(i, DISPC_POL_FREQ); DUMPREG(i, DISPC_DIVISORo); DUMPREG(i, DISPC_SIZE_MGR); DUMPREG(i, DISPC_DATA_CYCLE1); DUMPREG(i, DISPC_DATA_CYCLE2); DUMPREG(i, DISPC_DATA_CYCLE3); if (dss_has_feature(FEAT_CPR)) { DUMPREG(i, DISPC_CPR_COEF_R); DUMPREG(i, DISPC_CPR_COEF_G); DUMPREG(i, DISPC_CPR_COEF_B); } } p_names = ovl_names; for (i = 0; i < dss_feat_get_num_ovls(); i++) { DUMPREG(i, DISPC_OVL_BA0); DUMPREG(i, DISPC_OVL_BA1); DUMPREG(i, DISPC_OVL_POSITION); DUMPREG(i, DISPC_OVL_SIZE); DUMPREG(i, DISPC_OVL_ATTRIBUTES); DUMPREG(i, DISPC_OVL_FIFO_THRESHOLD); DUMPREG(i, DISPC_OVL_FIFO_SIZE_STATUS); DUMPREG(i, DISPC_OVL_ROW_INC); DUMPREG(i, DISPC_OVL_PIXEL_INC); if (dss_has_feature(FEAT_PRELOAD)) DUMPREG(i, DISPC_OVL_PRELOAD); if (i == OMAP_DSS_GFX) { DUMPREG(i, DISPC_OVL_WINDOW_SKIP); DUMPREG(i, DISPC_OVL_TABLE_BA); continue; } DUMPREG(i, DISPC_OVL_FIR); DUMPREG(i, DISPC_OVL_PICTURE_SIZE); DUMPREG(i, DISPC_OVL_ACCU0); DUMPREG(i, DISPC_OVL_ACCU1); if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) { DUMPREG(i, DISPC_OVL_BA0_UV); DUMPREG(i, DISPC_OVL_BA1_UV); DUMPREG(i, DISPC_OVL_FIR2); DUMPREG(i, DISPC_OVL_ACCU2_0); DUMPREG(i, DISPC_OVL_ACCU2_1); } if (dss_has_feature(FEAT_ATTR2)) DUMPREG(i, DISPC_OVL_ATTRIBUTES2); if (dss_has_feature(FEAT_PRELOAD)) DUMPREG(i, DISPC_OVL_PRELOAD); } #undef DISPC_REG #undef DUMPREG #define DISPC_REG(plane, name, i) name(plane, i) #define DUMPREG(plane, name, i) \ seq_printf(s, "%s_%d(%s)%*s %08x\n", #name, i, p_names[plane], \ 46 - strlen(#name) - strlen(p_names[plane]), " ", \ dispc_read_reg(DISPC_REG(plane, name, i))) /* Video pipeline coefficient registers */ /* start from OMAP_DSS_VIDEO1 */ for (i = 1; i < dss_feat_get_num_ovls(); i++) { for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_H, j); for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_HV, j); for (j = 0; j < 5; j++) DUMPREG(i, DISPC_OVL_CONV_COEF, j); if (dss_has_feature(FEAT_FIR_COEF_V)) { for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_V, j); } if (dss_has_feature(FEAT_HANDLE_UV_SEPARATE)) { for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_H2, j); for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_HV2, j); for (j = 0; j < 8; j++) DUMPREG(i, DISPC_OVL_FIR_COEF_V2, j); } } dispc_runtime_put(); #undef DISPC_REG #undef DUMPREG } static void _dispc_mgr_set_pol_freq(enum omap_channel channel, bool onoff, bool rf, bool ieo, bool ipc, bool ihs, bool ivs, u8 acbi, u8 acb) { u32 l = 0; DSSDBG("onoff %d rf %d ieo %d ipc %d ihs %d ivs %d acbi %d acb %d\n", onoff, rf, ieo, ipc, ihs, ivs, acbi, acb); l |= FLD_VAL(onoff, 17, 17); l |= FLD_VAL(rf, 16, 16); l |= FLD_VAL(ieo, 15, 15); l |= FLD_VAL(ipc, 14, 14); l |= FLD_VAL(ihs, 13, 13); l |= FLD_VAL(ivs, 12, 12); l |= FLD_VAL(acbi, 11, 8); l |= FLD_VAL(acb, 7, 0); dispc_write_reg(DISPC_POL_FREQ(channel), l); } void dispc_mgr_set_pol_freq(enum omap_channel channel, enum omap_panel_config config, u8 acbi, u8 acb) { _dispc_mgr_set_pol_freq(channel, (config & OMAP_DSS_LCD_ONOFF) != 0, (config & OMAP_DSS_LCD_RF) != 0, (config & OMAP_DSS_LCD_IEO) != 0, (config & OMAP_DSS_LCD_IPC) != 0, (config & OMAP_DSS_LCD_IHS) != 0, (config & OMAP_DSS_LCD_IVS) != 0, acbi, acb); } /* with fck as input clock rate, find dispc dividers that produce req_pck */ void dispc_find_clk_divs(bool is_tft, unsigned long req_pck, unsigned long fck, struct dispc_clock_info *cinfo) { u16 pcd_min, pcd_max; unsigned long best_pck; u16 best_ld, cur_ld; u16 best_pd, cur_pd; pcd_min = dss_feat_get_param_min(FEAT_PARAM_DSS_PCD); pcd_max = dss_feat_get_param_max(FEAT_PARAM_DSS_PCD); if (!is_tft) pcd_min = 3; best_pck = 0; best_ld = 0; best_pd = 0; for (cur_ld = 1; cur_ld <= 255; ++cur_ld) { unsigned long lck = fck / cur_ld; for (cur_pd = pcd_min; cur_pd <= pcd_max; ++cur_pd) { unsigned long pck = lck / cur_pd; long old_delta = abs(best_pck - req_pck); long new_delta = abs(pck - req_pck); if (best_pck == 0 || new_delta < old_delta) { best_pck = pck; best_ld = cur_ld; best_pd = cur_pd; if (pck == req_pck) goto found; } if (pck < req_pck) break; } if (lck / pcd_min < req_pck) break; } found: cinfo->lck_div = best_ld; cinfo->pck_div = best_pd; cinfo->lck = fck / cinfo->lck_div; cinfo->pck = cinfo->lck / cinfo->pck_div; } /* calculate clock rates using dividers in cinfo */ int dispc_calc_clock_rates(unsigned long dispc_fclk_rate, struct dispc_clock_info *cinfo) { if (cinfo->lck_div > 255 || cinfo->lck_div == 0) return -EINVAL; if (cinfo->pck_div < 1 || cinfo->pck_div > 255) return -EINVAL; cinfo->lck = dispc_fclk_rate / cinfo->lck_div; cinfo->pck = cinfo->lck / cinfo->pck_div; return 0; } int dispc_mgr_set_clock_div(enum omap_channel channel, struct dispc_clock_info *cinfo) { DSSDBG("lck = %lu (%u)\n", cinfo->lck, cinfo->lck_div); DSSDBG("pck = %lu (%u)\n", cinfo->pck, cinfo->pck_div); dispc_mgr_set_lcd_divisor(channel, cinfo->lck_div, cinfo->pck_div); return 0; } int dispc_mgr_get_clock_div(enum omap_channel channel, struct dispc_clock_info *cinfo) { unsigned long fck; fck = dispc_fclk_rate(); cinfo->lck_div = REG_GET(DISPC_DIVISORo(channel), 23, 16); cinfo->pck_div = REG_GET(DISPC_DIVISORo(channel), 7, 0); cinfo->lck = fck / cinfo->lck_div; cinfo->pck = cinfo->lck / cinfo->pck_div; return 0; } /* dispc.irq_lock has to be locked by the caller */ static void _omap_dispc_set_irqs(void) { u32 mask; u32 old_mask; int i; struct omap_dispc_isr_data *isr_data; mask = dispc.irq_error_mask; for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { isr_data = &dispc.registered_isr[i]; if (isr_data->isr == NULL) continue; mask |= isr_data->mask; } old_mask = dispc_read_reg(DISPC_IRQENABLE); /* clear the irqstatus for newly enabled irqs */ dispc_write_reg(DISPC_IRQSTATUS, (mask ^ old_mask) & mask); dispc_write_reg(DISPC_IRQENABLE, mask); } int omap_dispc_register_isr(omap_dispc_isr_t isr, void *arg, u32 mask) { int i; int ret; unsigned long flags; struct omap_dispc_isr_data *isr_data; if (isr == NULL) return -EINVAL; spin_lock_irqsave(&dispc.irq_lock, flags); /* check for duplicate entry */ for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { isr_data = &dispc.registered_isr[i]; if (isr_data->isr == isr && isr_data->arg == arg && isr_data->mask == mask) { ret = -EINVAL; goto err; } } isr_data = NULL; ret = -EBUSY; for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { isr_data = &dispc.registered_isr[i]; if (isr_data->isr != NULL) continue; isr_data->isr = isr; isr_data->arg = arg; isr_data->mask = mask; ret = 0; break; } if (ret) goto err; _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); return 0; err: spin_unlock_irqrestore(&dispc.irq_lock, flags); return ret; } EXPORT_SYMBOL(omap_dispc_register_isr); int omap_dispc_unregister_isr(omap_dispc_isr_t isr, void *arg, u32 mask) { int i; unsigned long flags; int ret = -EINVAL; struct omap_dispc_isr_data *isr_data; spin_lock_irqsave(&dispc.irq_lock, flags); for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { isr_data = &dispc.registered_isr[i]; if (isr_data->isr != isr || isr_data->arg != arg || isr_data->mask != mask) continue; /* found the correct isr */ isr_data->isr = NULL; isr_data->arg = NULL; isr_data->mask = 0; ret = 0; break; } if (ret == 0) _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); return ret; } EXPORT_SYMBOL(omap_dispc_unregister_isr); #ifdef DEBUG static void print_irq_status(u32 status) { if ((status & dispc.irq_error_mask) == 0) return; printk(KERN_DEBUG "DISPC IRQ: 0x%x: ", status); #define PIS(x) \ if (status & DISPC_IRQ_##x) \ printk(#x " "); PIS(GFX_FIFO_UNDERFLOW); PIS(OCP_ERR); PIS(VID1_FIFO_UNDERFLOW); PIS(VID2_FIFO_UNDERFLOW); if (dss_feat_get_num_ovls() > 3) PIS(VID3_FIFO_UNDERFLOW); PIS(SYNC_LOST); PIS(SYNC_LOST_DIGIT); if (dss_has_feature(FEAT_MGR_LCD2)) PIS(SYNC_LOST2); #undef PIS printk("\n"); } #endif /* Called from dss.c. Note that we don't touch clocks here, * but we presume they are on because we got an IRQ. However, * an irq handler may turn the clocks off, so we may not have * clock later in the function. */ static irqreturn_t omap_dispc_irq_handler(int irq, void *arg) { int i; u32 irqstatus, irqenable; u32 handledirqs = 0; u32 unhandled_errors; struct omap_dispc_isr_data *isr_data; struct omap_dispc_isr_data registered_isr[DISPC_MAX_NR_ISRS]; spin_lock(&dispc.irq_lock); irqstatus = dispc_read_reg(DISPC_IRQSTATUS); irqenable = dispc_read_reg(DISPC_IRQENABLE); /* IRQ is not for us */ if (!(irqstatus & irqenable)) { spin_unlock(&dispc.irq_lock); return IRQ_NONE; } #ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS spin_lock(&dispc.irq_stats_lock); dispc.irq_stats.irq_count++; dss_collect_irq_stats(irqstatus, dispc.irq_stats.irqs); spin_unlock(&dispc.irq_stats_lock); #endif #ifdef DEBUG if (dss_debug) print_irq_status(irqstatus); #endif /* Ack the interrupt. Do it here before clocks are possibly turned * off */ dispc_write_reg(DISPC_IRQSTATUS, irqstatus); /* flush posted write */ dispc_read_reg(DISPC_IRQSTATUS); /* make a copy and unlock, so that isrs can unregister * themselves */ memcpy(registered_isr, dispc.registered_isr, sizeof(registered_isr)); spin_unlock(&dispc.irq_lock); for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { isr_data = &registered_isr[i]; if (!isr_data->isr) continue; if (isr_data->mask & irqstatus) { isr_data->isr(isr_data->arg, irqstatus); handledirqs |= isr_data->mask; } } spin_lock(&dispc.irq_lock); unhandled_errors = irqstatus & ~handledirqs & dispc.irq_error_mask; if (unhandled_errors) { dispc.error_irqs |= unhandled_errors; dispc.irq_error_mask &= ~unhandled_errors; _omap_dispc_set_irqs(); schedule_work(&dispc.error_work); } spin_unlock(&dispc.irq_lock); return IRQ_HANDLED; } static void dispc_error_worker(struct work_struct *work) { int i; u32 errors; unsigned long flags; static const unsigned fifo_underflow_bits[] = { DISPC_IRQ_GFX_FIFO_UNDERFLOW, DISPC_IRQ_VID1_FIFO_UNDERFLOW, DISPC_IRQ_VID2_FIFO_UNDERFLOW, DISPC_IRQ_VID3_FIFO_UNDERFLOW, }; static const unsigned sync_lost_bits[] = { DISPC_IRQ_SYNC_LOST, DISPC_IRQ_SYNC_LOST_DIGIT, DISPC_IRQ_SYNC_LOST2, }; spin_lock_irqsave(&dispc.irq_lock, flags); errors = dispc.error_irqs; dispc.error_irqs = 0; spin_unlock_irqrestore(&dispc.irq_lock, flags); dispc_runtime_get(); for (i = 0; i < omap_dss_get_num_overlays(); ++i) { struct omap_overlay *ovl; unsigned bit; ovl = omap_dss_get_overlay(i); bit = fifo_underflow_bits[i]; if (bit & errors) { DSSERR("FIFO UNDERFLOW on %s, disabling the overlay\n", ovl->name); dispc_ovl_enable(ovl->id, false); dispc_mgr_go(ovl->manager->id); mdelay(50); } } for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) { struct omap_overlay_manager *mgr; unsigned bit; mgr = omap_dss_get_overlay_manager(i); bit = sync_lost_bits[i]; if (bit & errors) { struct omap_dss_device *dssdev = mgr->device; bool enable; DSSERR("SYNC_LOST on channel %s, restarting the output " "with video overlays disabled\n", mgr->name); enable = dssdev->state == OMAP_DSS_DISPLAY_ACTIVE; dssdev->driver->disable(dssdev); for (i = 0; i < omap_dss_get_num_overlays(); ++i) { struct omap_overlay *ovl; ovl = omap_dss_get_overlay(i); if (ovl->id != OMAP_DSS_GFX && ovl->manager == mgr) dispc_ovl_enable(ovl->id, false); } dispc_mgr_go(mgr->id); mdelay(50); if (enable) dssdev->driver->enable(dssdev); } } if (errors & DISPC_IRQ_OCP_ERR) { DSSERR("OCP_ERR\n"); for (i = 0; i < omap_dss_get_num_overlay_managers(); ++i) { struct omap_overlay_manager *mgr; mgr = omap_dss_get_overlay_manager(i); if (mgr->device && mgr->device->driver) mgr->device->driver->disable(mgr->device); } } spin_lock_irqsave(&dispc.irq_lock, flags); dispc.irq_error_mask |= errors; _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); dispc_runtime_put(); } int omap_dispc_wait_for_irq_timeout(u32 irqmask, unsigned long timeout) { void dispc_irq_wait_handler(void *data, u32 mask) { complete((struct completion *)data); } int r; DECLARE_COMPLETION_ONSTACK(completion); r = omap_dispc_register_isr(dispc_irq_wait_handler, &completion, irqmask); if (r) return r; timeout = wait_for_completion_timeout(&completion, timeout); omap_dispc_unregister_isr(dispc_irq_wait_handler, &completion, irqmask); if (timeout == 0) return -ETIMEDOUT; if (timeout == -ERESTARTSYS) return -ERESTARTSYS; return 0; } int omap_dispc_wait_for_irq_interruptible_timeout(u32 irqmask, unsigned long timeout) { void dispc_irq_wait_handler(void *data, u32 mask) { complete((struct completion *)data); } int r; DECLARE_COMPLETION_ONSTACK(completion); r = omap_dispc_register_isr(dispc_irq_wait_handler, &completion, irqmask); if (r) return r; timeout = wait_for_completion_interruptible_timeout(&completion, timeout); omap_dispc_unregister_isr(dispc_irq_wait_handler, &completion, irqmask); if (timeout == 0) return -ETIMEDOUT; if (timeout == -ERESTARTSYS) return -ERESTARTSYS; return 0; } #ifdef CONFIG_OMAP2_DSS_FAKE_VSYNC void dispc_fake_vsync_irq(void) { u32 irqstatus = DISPC_IRQ_VSYNC; int i; WARN_ON(!in_interrupt()); for (i = 0; i < DISPC_MAX_NR_ISRS; i++) { struct omap_dispc_isr_data *isr_data; isr_data = &dispc.registered_isr[i]; if (!isr_data->isr) continue; if (isr_data->mask & irqstatus) isr_data->isr(isr_data->arg, irqstatus); } } #endif static void _omap_dispc_initialize_irq(void) { unsigned long flags; spin_lock_irqsave(&dispc.irq_lock, flags); memset(dispc.registered_isr, 0, sizeof(dispc.registered_isr)); dispc.irq_error_mask = DISPC_IRQ_MASK_ERROR; if (dss_has_feature(FEAT_MGR_LCD2)) dispc.irq_error_mask |= DISPC_IRQ_SYNC_LOST2; if (dss_feat_get_num_ovls() > 3) dispc.irq_error_mask |= DISPC_IRQ_VID3_FIFO_UNDERFLOW; /* there's SYNC_LOST_DIGIT waiting after enabling the DSS, * so clear it */ dispc_write_reg(DISPC_IRQSTATUS, dispc_read_reg(DISPC_IRQSTATUS)); _omap_dispc_set_irqs(); spin_unlock_irqrestore(&dispc.irq_lock, flags); } void dispc_enable_sidle(void) { REG_FLD_MOD(DISPC_SYSCONFIG, 2, 4, 3); /* SIDLEMODE: smart idle */ } void dispc_disable_sidle(void) { REG_FLD_MOD(DISPC_SYSCONFIG, 1, 4, 3); /* SIDLEMODE: no idle */ } static void _omap_dispc_initial_config(void) { u32 l; /* Exclusively enable DISPC_CORE_CLK and set divider to 1 */ if (dss_has_feature(FEAT_CORE_CLK_DIV)) { l = dispc_read_reg(DISPC_DIVISOR); /* Use DISPC_DIVISOR.LCD, instead of DISPC_DIVISOR1.LCD */ l = FLD_MOD(l, 1, 0, 0); l = FLD_MOD(l, 1, 23, 16); dispc_write_reg(DISPC_DIVISOR, l); } /* FUNCGATED */ if (dss_has_feature(FEAT_FUNCGATED)) REG_FLD_MOD(DISPC_CONFIG, 1, 9, 9); /* L3 firewall setting: enable access to OCM RAM */ /* XXX this should be somewhere in plat-omap */ if (cpu_is_omap24xx()) __raw_writel(0x402000b0, OMAP2_L3_IO_ADDRESS(0x680050a0)); _dispc_setup_color_conv_coef(); dispc_set_loadmode(OMAP_DSS_LOAD_FRAME_ONLY); dispc_read_plane_fifo_sizes(); dispc_configure_burst_sizes(); dispc_ovl_enable_zorder_planes(); } /* DISPC HW IP initialisation */ static int omap_dispchw_probe(struct platform_device *pdev) { u32 rev; int r = 0; struct resource *dispc_mem; struct clk *clk; dispc.pdev = pdev; spin_lock_init(&dispc.irq_lock); #ifdef CONFIG_OMAP2_DSS_COLLECT_IRQ_STATS spin_lock_init(&dispc.irq_stats_lock); dispc.irq_stats.last_reset = jiffies; #endif INIT_WORK(&dispc.error_work, dispc_error_worker); dispc_mem = platform_get_resource(dispc.pdev, IORESOURCE_MEM, 0); if (!dispc_mem) { DSSERR("can't get IORESOURCE_MEM DISPC\n"); return -EINVAL; } dispc.base = devm_ioremap(&pdev->dev, dispc_mem->start, resource_size(dispc_mem)); if (!dispc.base) { DSSERR("can't ioremap DISPC\n"); return -ENOMEM; } dispc.irq = platform_get_irq(dispc.pdev, 0); if (dispc.irq < 0) { DSSERR("platform_get_irq failed\n"); return -ENODEV; } r = devm_request_irq(&pdev->dev, dispc.irq, omap_dispc_irq_handler, IRQF_SHARED, "OMAP DISPC", dispc.pdev); if (r < 0) { DSSERR("request_irq failed\n"); return r; } clk = clk_get(&pdev->dev, "fck"); if (IS_ERR(clk)) { DSSERR("can't get fck\n"); r = PTR_ERR(clk); return r; } dispc.dss_clk = clk; pm_runtime_enable(&pdev->dev); r = dispc_runtime_get(); if (r) goto err_runtime_get; _omap_dispc_initial_config(); _omap_dispc_initialize_irq(); rev = dispc_read_reg(DISPC_REVISION); dev_dbg(&pdev->dev, "OMAP DISPC rev %d.%d\n", FLD_GET(rev, 7, 4), FLD_GET(rev, 3, 0)); dispc_runtime_put(); return 0; err_runtime_get: pm_runtime_disable(&pdev->dev); clk_put(dispc.dss_clk); return r; } static int omap_dispchw_remove(struct platform_device *pdev) { pm_runtime_disable(&pdev->dev); clk_put(dispc.dss_clk); return 0; } static int dispc_runtime_suspend(struct device *dev) { dispc_save_context(); dss_runtime_put(); return 0; } static int dispc_runtime_resume(struct device *dev) { int r; r = dss_runtime_get(); if (r < 0) return r; dispc_restore_context(); return 0; } static const struct dev_pm_ops dispc_pm_ops = { .runtime_suspend = dispc_runtime_suspend, .runtime_resume = dispc_runtime_resume, }; static struct platform_driver omap_dispchw_driver = { .probe = omap_dispchw_probe, .remove = omap_dispchw_remove, .driver = { .name = "omapdss_dispc", .owner = THIS_MODULE, .pm = &dispc_pm_ops, }, }; int dispc_init_platform_driver(void) { return platform_driver_register(&omap_dispchw_driver); } void dispc_uninit_platform_driver(void) { return platform_driver_unregister(&omap_dispchw_driver); }
mcmenaminadrian/Linux-devel
drivers/video/omap2/dss/dispc.c
C
gpl-2.0
81,884
#ifndef _LINUX_FS_H #define _LINUX_FS_H #include <linux/linkage.h> #include <linux/wait.h> #include <linux/kdev_t.h> #include <linux/dcache.h> #include <linux/path.h> #include <linux/stat.h> #include <linux/cache.h> #include <linux/list.h> #include <linux/list_lru.h> #include <linux/llist.h> #include <linux/radix-tree.h> #include <linux/rbtree.h> #include <linux/init.h> #include <linux/pid.h> #include <linux/bug.h> #include <linux/mutex.h> #include <linux/capability.h> #include <linux/semaphore.h> #include <linux/fiemap.h> #include <linux/rculist_bl.h> #include <linux/atomic.h> #include <linux/shrinker.h> #include <linux/migrate_mode.h> #include <linux/uidgid.h> #include <linux/lockdep.h> #include <linux/percpu-rwsem.h> #include <linux/blk_types.h> #include <asm/byteorder.h> #include <uapi/linux/fs.h> struct export_operations; struct hd_geometry; struct iovec; struct nameidata; struct kiocb; struct kobject; struct pipe_inode_info; struct poll_table_struct; struct kstatfs; struct vm_area_struct; struct vfsmount; struct cred; struct swap_info_struct; struct seq_file; struct workqueue_struct; struct iov_iter; extern void __init inode_init(void); extern void __init inode_init_early(void); extern void __init files_init(unsigned long); extern struct files_stat_struct files_stat; extern unsigned long get_max_files(void); extern int sysctl_nr_open; extern struct inodes_stat_t inodes_stat; extern int leases_enable, lease_break_time; extern int sysctl_protected_symlinks; extern int sysctl_protected_hardlinks; struct buffer_head; typedef int (get_block_t)(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create); typedef void (dio_iodone_t)(struct kiocb *iocb, loff_t offset, ssize_t bytes, void *private); #define MAY_EXEC 0x00000001 #define MAY_WRITE 0x00000002 #define MAY_READ 0x00000004 #define MAY_APPEND 0x00000008 #define MAY_ACCESS 0x00000010 #define MAY_OPEN 0x00000020 #define MAY_CHDIR 0x00000040 /* called from RCU mode, don't block */ #define MAY_NOT_BLOCK 0x00000080 /* * flags in file.f_mode. Note that FMODE_READ and FMODE_WRITE must correspond * to O_WRONLY and O_RDWR via the strange trick in __dentry_open() */ /* file is open for reading */ #define FMODE_READ ((__force fmode_t)0x1) /* file is open for writing */ #define FMODE_WRITE ((__force fmode_t)0x2) /* file is seekable */ #define FMODE_LSEEK ((__force fmode_t)0x4) /* file can be accessed using pread */ #define FMODE_PREAD ((__force fmode_t)0x8) /* file can be accessed using pwrite */ #define FMODE_PWRITE ((__force fmode_t)0x10) /* File is opened for execution with sys_execve / sys_uselib */ #define FMODE_EXEC ((__force fmode_t)0x20) /* File is opened with O_NDELAY (only set for block devices) */ #define FMODE_NDELAY ((__force fmode_t)0x40) /* File is opened with O_EXCL (only set for block devices) */ #define FMODE_EXCL ((__force fmode_t)0x80) /* File is opened using open(.., 3, ..) and is writeable only for ioctls (specialy hack for floppy.c) */ #define FMODE_WRITE_IOCTL ((__force fmode_t)0x100) /* 32bit hashes as llseek() offset (for directories) */ #define FMODE_32BITHASH ((__force fmode_t)0x200) /* 64bit hashes as llseek() offset (for directories) */ #define FMODE_64BITHASH ((__force fmode_t)0x400) /* * Don't update ctime and mtime. * * Currently a special hack for the XFS open_by_handle ioctl, but we'll * hopefully graduate it to a proper O_CMTIME flag supported by open(2) soon. */ #define FMODE_NOCMTIME ((__force fmode_t)0x800) /* Expect random access pattern */ #define FMODE_RANDOM ((__force fmode_t)0x1000) /* File is huge (eg. /dev/kmem): treat loff_t as unsigned */ #define FMODE_UNSIGNED_OFFSET ((__force fmode_t)0x2000) /* File is opened with O_PATH; almost nothing can be done with it */ #define FMODE_PATH ((__force fmode_t)0x4000) /* File needs atomic accesses to f_pos */ #define FMODE_ATOMIC_POS ((__force fmode_t)0x8000) /* Write access to underlying fs */ #define FMODE_WRITER ((__force fmode_t)0x10000) /* Has read method(s) */ #define FMODE_CAN_READ ((__force fmode_t)0x20000) /* Has write method(s) */ #define FMODE_CAN_WRITE ((__force fmode_t)0x40000) /* File was opened by fanotify and shouldn't generate fanotify events */ #define FMODE_NONOTIFY ((__force fmode_t)0x1000000) /* * Flag for rw_copy_check_uvector and compat_rw_copy_check_uvector * that indicates that they should check the contents of the iovec are * valid, but not check the memory that the iovec elements * points too. */ #define CHECK_IOVEC_ONLY -1 /* * The below are the various read and write types that we support. Some of * them include behavioral modifiers that send information down to the * block layer and IO scheduler. Terminology: * * The block layer uses device plugging to defer IO a little bit, in * the hope that we will see more IO very shortly. This increases * coalescing of adjacent IO and thus reduces the number of IOs we * have to send to the device. It also allows for better queuing, * if the IO isn't mergeable. If the caller is going to be waiting * for the IO, then he must ensure that the device is unplugged so * that the IO is dispatched to the driver. * * All IO is handled async in Linux. This is fine for background * writes, but for reads or writes that someone waits for completion * on, we want to notify the block layer and IO scheduler so that they * know about it. That allows them to make better scheduling * decisions. So when the below references 'sync' and 'async', it * is referencing this priority hint. * * With that in mind, the available types are: * * READ A normal read operation. Device will be plugged. * READ_SYNC A synchronous read. Device is not plugged, caller can * immediately wait on this read without caring about * unplugging. * READA Used for read-ahead operations. Lower priority, and the * block layer could (in theory) choose to ignore this * request if it runs into resource problems. * WRITE A normal async write. Device will be plugged. * WRITE_SYNC Synchronous write. Identical to WRITE, but passes down * the hint that someone will be waiting on this IO * shortly. The write equivalent of READ_SYNC. * WRITE_ODIRECT Special case write for O_DIRECT only. * WRITE_FLUSH Like WRITE_SYNC but with preceding cache flush. * WRITE_FUA Like WRITE_SYNC but data is guaranteed to be on * non-volatile media on completion. * WRITE_FLUSH_FUA Combination of WRITE_FLUSH and FUA. The IO is preceded * by a cache flush and data is guaranteed to be on * non-volatile media on completion. * */ #define RW_MASK REQ_WRITE #define RWA_MASK REQ_RAHEAD #define READ 0 #define WRITE RW_MASK #define READA RWA_MASK #define READ_SYNC (READ | REQ_SYNC) #define WRITE_SYNC (WRITE | REQ_SYNC | REQ_NOIDLE) #define WRITE_ODIRECT (WRITE | REQ_SYNC) #define WRITE_FLUSH (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FLUSH) #define WRITE_FUA (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FUA) #define WRITE_FLUSH_FUA (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FLUSH | REQ_FUA) /* * Attribute flags. These should be or-ed together to figure out what * has been changed! */ #define ATTR_MODE (1 << 0) #define ATTR_UID (1 << 1) #define ATTR_GID (1 << 2) #define ATTR_SIZE (1 << 3) #define ATTR_ATIME (1 << 4) #define ATTR_MTIME (1 << 5) #define ATTR_CTIME (1 << 6) #define ATTR_ATIME_SET (1 << 7) #define ATTR_MTIME_SET (1 << 8) #define ATTR_FORCE (1 << 9) /* Not a change, but a change it */ #define ATTR_ATTR_FLAG (1 << 10) #define ATTR_KILL_SUID (1 << 11) #define ATTR_KILL_SGID (1 << 12) #define ATTR_FILE (1 << 13) #define ATTR_KILL_PRIV (1 << 14) #define ATTR_OPEN (1 << 15) /* Truncating from open(O_TRUNC) */ #define ATTR_TIMES_SET (1 << 16) /* * Whiteout is represented by a char device. The following constants define the * mode and device number to use. */ #define WHITEOUT_MODE 0 #define WHITEOUT_DEV 0 /* * This is the Inode Attributes structure, used for notify_change(). It * uses the above definitions as flags, to know which values have changed. * Also, in this manner, a Filesystem can look at only the values it cares * about. Basically, these are the attributes that the VFS layer can * request to change from the FS layer. * * Derek Atkins <[email protected]> 94-10-20 */ struct iattr { unsigned int ia_valid; umode_t ia_mode; kuid_t ia_uid; kgid_t ia_gid; loff_t ia_size; struct timespec ia_atime; struct timespec ia_mtime; struct timespec ia_ctime; /* * Not an attribute, but an auxiliary info for filesystems wanting to * implement an ftruncate() like method. NOTE: filesystem should * check for (ia_valid & ATTR_FILE), and not for (ia_file != NULL). */ struct file *ia_file; }; /* * Includes for diskquotas. */ #include <linux/quota.h> /* * Maximum number of layers of fs stack. Needs to be limited to * prevent kernel stack overflow */ #define FILESYSTEM_MAX_STACK_DEPTH 2 /** * enum positive_aop_returns - aop return codes with specific semantics * * @AOP_WRITEPAGE_ACTIVATE: Informs the caller that page writeback has * completed, that the page is still locked, and * should be considered active. The VM uses this hint * to return the page to the active list -- it won't * be a candidate for writeback again in the near * future. Other callers must be careful to unlock * the page if they get this return. Returned by * writepage(); * * @AOP_TRUNCATED_PAGE: The AOP method that was handed a locked page has * unlocked it and the page might have been truncated. * The caller should back up to acquiring a new page and * trying again. The aop will be taking reasonable * precautions not to livelock. If the caller held a page * reference, it should drop it before retrying. Returned * by readpage(). * * address_space_operation functions return these large constants to indicate * special semantics to the caller. These are much larger than the bytes in a * page to allow for functions that return the number of bytes operated on in a * given page. */ enum positive_aop_returns { AOP_WRITEPAGE_ACTIVATE = 0x80000, AOP_TRUNCATED_PAGE = 0x80001, }; #define AOP_FLAG_UNINTERRUPTIBLE 0x0001 /* will not do a short write */ #define AOP_FLAG_CONT_EXPAND 0x0002 /* called from cont_expand */ #define AOP_FLAG_NOFS 0x0004 /* used by filesystem to direct * helper code (eg buffer layer) * to clear GFP_FS from alloc */ /* * oh the beauties of C type declarations. */ struct page; struct address_space; struct writeback_control; /* * "descriptor" for what we're up to with a read. * This allows us to use the same read code yet * have multiple different users of the data that * we read from a file. * * The simplest case just copies the data to user * mode. */ typedef struct { size_t written; size_t count; union { char __user *buf; void *data; } arg; int error; } read_descriptor_t; typedef int (*read_actor_t)(read_descriptor_t *, struct page *, unsigned long, unsigned long); struct address_space_operations { int (*writepage)(struct page *page, struct writeback_control *wbc); int (*readpage)(struct file *, struct page *); /* Write back some dirty pages from this mapping. */ int (*writepages)(struct address_space *, struct writeback_control *); /* Set a page dirty. Return true if this dirtied it */ int (*set_page_dirty)(struct page *page); int (*readpages)(struct file *filp, struct address_space *mapping, struct list_head *pages, unsigned nr_pages); int (*write_begin)(struct file *, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata); int (*write_end)(struct file *, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata); /* Unfortunately this kludge is needed for FIBMAP. Don't use it */ sector_t (*bmap)(struct address_space *, sector_t); void (*invalidatepage) (struct page *, unsigned int, unsigned int); int (*releasepage) (struct page *, gfp_t); void (*freepage)(struct page *); ssize_t (*direct_IO)(int, struct kiocb *, struct iov_iter *iter, loff_t offset); int (*get_xip_mem)(struct address_space *, pgoff_t, int, void **, unsigned long *); /* * migrate the contents of a page to the specified target. If * migrate_mode is MIGRATE_ASYNC, it must not block. */ int (*migratepage) (struct address_space *, struct page *, struct page *, enum migrate_mode); int (*launder_page) (struct page *); int (*is_partially_uptodate) (struct page *, unsigned long, unsigned long); void (*is_dirty_writeback) (struct page *, bool *, bool *); int (*error_remove_page)(struct address_space *, struct page *); /* swapfile support */ int (*swap_activate)(struct swap_info_struct *sis, struct file *file, sector_t *span); void (*swap_deactivate)(struct file *file); }; extern const struct address_space_operations empty_aops; /* * pagecache_write_begin/pagecache_write_end must be used by general code * to write into the pagecache. */ int pagecache_write_begin(struct file *, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata); int pagecache_write_end(struct file *, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata); struct backing_dev_info; struct address_space { struct inode *host; /* owner: inode, block_device */ struct radix_tree_root page_tree; /* radix tree of all pages */ spinlock_t tree_lock; /* and lock protecting it */ atomic_t i_mmap_writable;/* count VM_SHARED mappings */ struct rb_root i_mmap; /* tree of private and shared mappings */ struct list_head i_mmap_nonlinear;/*list VM_NONLINEAR mappings */ struct mutex i_mmap_mutex; /* protect tree, count, list */ /* Protected by tree_lock together with the radix tree */ unsigned long nrpages; /* number of total pages */ unsigned long nrshadows; /* number of shadow entries */ pgoff_t writeback_index;/* writeback starts here */ const struct address_space_operations *a_ops; /* methods */ unsigned long flags; /* error bits/gfp mask */ struct backing_dev_info *backing_dev_info; /* device readahead, etc */ spinlock_t private_lock; /* for use by the address_space */ struct list_head private_list; /* ditto */ void *private_data; /* ditto */ } __attribute__((aligned(sizeof(long)))); /* * On most architectures that alignment is already the case; but * must be enforced here for CRIS, to let the least significant bit * of struct page's "mapping" pointer be used for PAGE_MAPPING_ANON. */ struct request_queue; struct block_device { dev_t bd_dev; /* not a kdev_t - it's a search key */ int bd_openers; struct inode * bd_inode; /* will die */ struct super_block * bd_super; struct mutex bd_mutex; /* open/close mutex */ struct list_head bd_inodes; void * bd_claiming; void * bd_holder; int bd_holders; bool bd_write_holder; #ifdef CONFIG_SYSFS struct list_head bd_holder_disks; #endif struct block_device * bd_contains; unsigned bd_block_size; struct hd_struct * bd_part; /* number of times partitions within this device have been opened. */ unsigned bd_part_count; int bd_invalidated; struct gendisk * bd_disk; struct request_queue * bd_queue; struct list_head bd_list; /* * Private data. You must have bd_claim'ed the block_device * to use this. NOTE: bd_claim allows an owner to claim * the same device multiple times, the owner must take special * care to not mess up bd_private for that case. */ unsigned long bd_private; /* The counter of freeze processes */ int bd_fsfreeze_count; /* Mutex for freeze */ struct mutex bd_fsfreeze_mutex; }; /* * Radix-tree tags, for tagging dirty and writeback pages within the pagecache * radix trees */ #define PAGECACHE_TAG_DIRTY 0 #define PAGECACHE_TAG_WRITEBACK 1 #define PAGECACHE_TAG_TOWRITE 2 int mapping_tagged(struct address_space *mapping, int tag); /* * Might pages of this file be mapped into userspace? */ static inline int mapping_mapped(struct address_space *mapping) { return !RB_EMPTY_ROOT(&mapping->i_mmap) || !list_empty(&mapping->i_mmap_nonlinear); } /* * Might pages of this file have been modified in userspace? * Note that i_mmap_writable counts all VM_SHARED vmas: do_mmap_pgoff * marks vma as VM_SHARED if it is shared, and the file was opened for * writing i.e. vma may be mprotected writable even if now readonly. * * If i_mmap_writable is negative, no new writable mappings are allowed. You * can only deny writable mappings, if none exists right now. */ static inline int mapping_writably_mapped(struct address_space *mapping) { return atomic_read(&mapping->i_mmap_writable) > 0; } static inline int mapping_map_writable(struct address_space *mapping) { return atomic_inc_unless_negative(&mapping->i_mmap_writable) ? 0 : -EPERM; } static inline void mapping_unmap_writable(struct address_space *mapping) { atomic_dec(&mapping->i_mmap_writable); } static inline int mapping_deny_writable(struct address_space *mapping) { return atomic_dec_unless_positive(&mapping->i_mmap_writable) ? 0 : -EBUSY; } static inline void mapping_allow_writable(struct address_space *mapping) { atomic_inc(&mapping->i_mmap_writable); } /* * Use sequence counter to get consistent i_size on 32-bit processors. */ #if BITS_PER_LONG==32 && defined(CONFIG_SMP) #include <linux/seqlock.h> #define __NEED_I_SIZE_ORDERED #define i_size_ordered_init(inode) seqcount_init(&inode->i_size_seqcount) #else #define i_size_ordered_init(inode) do { } while (0) #endif struct posix_acl; #define ACL_NOT_CACHED ((void *)(-1)) #define IOP_FASTPERM 0x0001 #define IOP_LOOKUP 0x0002 #define IOP_NOFOLLOW 0x0004 /* * Keep mostly read-only and often accessed (especially for * the RCU path lookup and 'stat' data) fields at the beginning * of the 'struct inode' */ struct inode { umode_t i_mode; unsigned short i_opflags; kuid_t i_uid; kgid_t i_gid; unsigned int i_flags; #ifdef CONFIG_FS_POSIX_ACL struct posix_acl *i_acl; struct posix_acl *i_default_acl; #endif const struct inode_operations *i_op; struct super_block *i_sb; struct address_space *i_mapping; #ifdef CONFIG_SECURITY void *i_security; #endif /* Stat data, not accessed from path walking */ unsigned long i_ino; /* * Filesystems may only read i_nlink directly. They shall use the * following functions for modification: * * (set|clear|inc|drop)_nlink * inode_(inc|dec)_link_count */ union { const unsigned int i_nlink; unsigned int __i_nlink; }; dev_t i_rdev; loff_t i_size; struct timespec i_atime; struct timespec i_mtime; struct timespec i_ctime; spinlock_t i_lock; /* i_blocks, i_bytes, maybe i_size */ unsigned short i_bytes; unsigned int i_blkbits; blkcnt_t i_blocks; #ifdef __NEED_I_SIZE_ORDERED seqcount_t i_size_seqcount; #endif /* Misc */ unsigned long i_state; struct mutex i_mutex; unsigned long dirtied_when; /* jiffies of first dirtying */ struct hlist_node i_hash; struct list_head i_wb_list; /* backing dev IO list */ struct list_head i_lru; /* inode LRU list */ struct list_head i_sb_list; union { struct hlist_head i_dentry; struct rcu_head i_rcu; }; u64 i_version; atomic_t i_count; atomic_t i_dio_count; atomic_t i_writecount; #ifdef CONFIG_IMA atomic_t i_readcount; /* struct files open RO */ #endif const struct file_operations *i_fop; /* former ->i_op->default_file_ops */ struct file_lock *i_flock; struct address_space i_data; #ifdef CONFIG_QUOTA struct dquot *i_dquot[MAXQUOTAS]; #endif struct list_head i_devices; union { struct pipe_inode_info *i_pipe; struct block_device *i_bdev; struct cdev *i_cdev; }; __u32 i_generation; #ifdef CONFIG_FSNOTIFY __u32 i_fsnotify_mask; /* all events this inode cares about */ struct hlist_head i_fsnotify_marks; #endif void *i_private; /* fs or device private pointer */ }; static inline int inode_unhashed(struct inode *inode) { return hlist_unhashed(&inode->i_hash); } /* * inode->i_mutex nesting subclasses for the lock validator: * * 0: the object of the current VFS operation * 1: parent * 2: child/target * 3: xattr * 4: second non-directory * 5: second parent (when locking independent directories in rename) * * I_MUTEX_NONDIR2 is for certain operations (such as rename) which lock two * non-directories at once. * * The locking order between these classes is * parent[2] -> child -> grandchild -> normal -> xattr -> second non-directory */ enum inode_i_mutex_lock_class { I_MUTEX_NORMAL, I_MUTEX_PARENT, I_MUTEX_CHILD, I_MUTEX_XATTR, I_MUTEX_NONDIR2, I_MUTEX_PARENT2, }; void lock_two_nondirectories(struct inode *, struct inode*); void unlock_two_nondirectories(struct inode *, struct inode*); /* * NOTE: in a 32bit arch with a preemptable kernel and * an UP compile the i_size_read/write must be atomic * with respect to the local cpu (unlike with preempt disabled), * but they don't need to be atomic with respect to other cpus like in * true SMP (so they need either to either locally disable irq around * the read or for example on x86 they can be still implemented as a * cmpxchg8b without the need of the lock prefix). For SMP compiles * and 64bit archs it makes no difference if preempt is enabled or not. */ static inline loff_t i_size_read(const struct inode *inode) { #if BITS_PER_LONG==32 && defined(CONFIG_SMP) loff_t i_size; unsigned int seq; do { seq = read_seqcount_begin(&inode->i_size_seqcount); i_size = inode->i_size; } while (read_seqcount_retry(&inode->i_size_seqcount, seq)); return i_size; #elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPT) loff_t i_size; preempt_disable(); i_size = inode->i_size; preempt_enable(); return i_size; #else return inode->i_size; #endif } /* * NOTE: unlike i_size_read(), i_size_write() does need locking around it * (normally i_mutex), otherwise on 32bit/SMP an update of i_size_seqcount * can be lost, resulting in subsequent i_size_read() calls spinning forever. */ static inline void i_size_write(struct inode *inode, loff_t i_size) { #if BITS_PER_LONG==32 && defined(CONFIG_SMP) preempt_disable(); write_seqcount_begin(&inode->i_size_seqcount); inode->i_size = i_size; write_seqcount_end(&inode->i_size_seqcount); preempt_enable(); #elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPT) preempt_disable(); inode->i_size = i_size; preempt_enable(); #else inode->i_size = i_size; #endif } /* Helper functions so that in most cases filesystems will * not need to deal directly with kuid_t and kgid_t and can * instead deal with the raw numeric values that are stored * in the filesystem. */ static inline uid_t i_uid_read(const struct inode *inode) { return from_kuid(&init_user_ns, inode->i_uid); } static inline gid_t i_gid_read(const struct inode *inode) { return from_kgid(&init_user_ns, inode->i_gid); } static inline void i_uid_write(struct inode *inode, uid_t uid) { inode->i_uid = make_kuid(&init_user_ns, uid); } static inline void i_gid_write(struct inode *inode, gid_t gid) { inode->i_gid = make_kgid(&init_user_ns, gid); } static inline unsigned iminor(const struct inode *inode) { return MINOR(inode->i_rdev); } static inline unsigned imajor(const struct inode *inode) { return MAJOR(inode->i_rdev); } extern struct block_device *I_BDEV(struct inode *inode); struct fown_struct { rwlock_t lock; /* protects pid, uid, euid fields */ struct pid *pid; /* pid or -pgrp where SIGIO should be sent */ enum pid_type pid_type; /* Kind of process group SIGIO should be sent to */ kuid_t uid, euid; /* uid/euid of process setting the owner */ int signum; /* posix.1b rt signal to be delivered on IO */ }; /* * Track a single file's readahead state */ struct file_ra_state { pgoff_t start; /* where readahead started */ unsigned int size; /* # of readahead pages */ unsigned int async_size; /* do asynchronous readahead when there are only # of pages ahead */ unsigned int ra_pages; /* Maximum readahead window */ unsigned int mmap_miss; /* Cache miss stat for mmap accesses */ loff_t prev_pos; /* Cache last read() position */ }; /* * Check if @index falls in the readahead windows. */ static inline int ra_has_index(struct file_ra_state *ra, pgoff_t index) { return (index >= ra->start && index < ra->start + ra->size); } struct file { union { struct llist_node fu_llist; struct rcu_head fu_rcuhead; } f_u; struct path f_path; #define f_dentry f_path.dentry struct inode *f_inode; /* cached value */ const struct file_operations *f_op; /* * Protects f_ep_links, f_flags. * Must not be taken from IRQ context. */ spinlock_t f_lock; atomic_long_t f_count; unsigned int f_flags; fmode_t f_mode; struct mutex f_pos_lock; loff_t f_pos; struct fown_struct f_owner; const struct cred *f_cred; struct file_ra_state f_ra; u64 f_version; #ifdef CONFIG_SECURITY void *f_security; #endif /* needed for tty driver, and maybe others */ void *private_data; #ifdef CONFIG_EPOLL /* Used by fs/eventpoll.c to link all the hooks to this file */ struct list_head f_ep_links; struct list_head f_tfile_llink; #endif /* #ifdef CONFIG_EPOLL */ struct address_space *f_mapping; } __attribute__((aligned(4))); /* lest something weird decides that 2 is OK */ struct file_handle { __u32 handle_bytes; int handle_type; /* file identifier */ unsigned char f_handle[0]; }; static inline struct file *get_file(struct file *f) { atomic_long_inc(&f->f_count); return f; } #define fput_atomic(x) atomic_long_add_unless(&(x)->f_count, -1, 1) #define file_count(x) atomic_long_read(&(x)->f_count) #define MAX_NON_LFS ((1UL<<31) - 1) /* Page cache limit. The filesystems should put that into their s_maxbytes limits, otherwise bad things can happen in VM. */ #if BITS_PER_LONG==32 #define MAX_LFS_FILESIZE (((loff_t)PAGE_CACHE_SIZE << (BITS_PER_LONG-1))-1) #elif BITS_PER_LONG==64 #define MAX_LFS_FILESIZE ((loff_t)0x7fffffffffffffffLL) #endif #define FL_POSIX 1 #define FL_FLOCK 2 #define FL_DELEG 4 /* NFSv4 delegation */ #define FL_ACCESS 8 /* not trying to lock, just looking */ #define FL_EXISTS 16 /* when unlocking, test for existence */ #define FL_LEASE 32 /* lease held on this file */ #define FL_CLOSE 64 /* unlock on close */ #define FL_SLEEP 128 /* A blocking lock */ #define FL_DOWNGRADE_PENDING 256 /* Lease is being downgraded */ #define FL_UNLOCK_PENDING 512 /* Lease is being broken */ #define FL_OFDLCK 1024 /* lock is "owned" by struct file */ /* * Special return value from posix_lock_file() and vfs_lock_file() for * asynchronous locking. */ #define FILE_LOCK_DEFERRED 1 /* legacy typedef, should eventually be removed */ typedef void *fl_owner_t; struct file_lock_operations { void (*fl_copy_lock)(struct file_lock *, struct file_lock *); void (*fl_release_private)(struct file_lock *); }; struct lock_manager_operations { int (*lm_compare_owner)(struct file_lock *, struct file_lock *); unsigned long (*lm_owner_key)(struct file_lock *); void (*lm_get_owner)(struct file_lock *, struct file_lock *); void (*lm_put_owner)(struct file_lock *); void (*lm_notify)(struct file_lock *); /* unblock callback */ int (*lm_grant)(struct file_lock *, int); bool (*lm_break)(struct file_lock *); int (*lm_change)(struct file_lock **, int, struct list_head *); void (*lm_setup)(struct file_lock *, void **); }; struct lock_manager { struct list_head list; }; struct net; void locks_start_grace(struct net *, struct lock_manager *); void locks_end_grace(struct lock_manager *); int locks_in_grace(struct net *); /* that will die - we need it for nfs_lock_info */ #include <linux/nfs_fs_i.h> /* * struct file_lock represents a generic "file lock". It's used to represent * POSIX byte range locks, BSD (flock) locks, and leases. It's important to * note that the same struct is used to represent both a request for a lock and * the lock itself, but the same object is never used for both. * * FIXME: should we create a separate "struct lock_request" to help distinguish * these two uses? * * The i_flock list is ordered by: * * 1) lock type -- FL_LEASEs first, then FL_FLOCK, and finally FL_POSIX * 2) lock owner * 3) lock range start * 4) lock range end * * Obviously, the last two criteria only matter for POSIX locks. */ struct file_lock { struct file_lock *fl_next; /* singly linked list for this inode */ struct hlist_node fl_link; /* node in global lists */ struct list_head fl_block; /* circular list of blocked processes */ fl_owner_t fl_owner; unsigned int fl_flags; unsigned char fl_type; unsigned int fl_pid; int fl_link_cpu; /* what cpu's list is this on? */ struct pid *fl_nspid; wait_queue_head_t fl_wait; struct file *fl_file; loff_t fl_start; loff_t fl_end; struct fasync_struct * fl_fasync; /* for lease break notifications */ /* for lease breaks: */ unsigned long fl_break_time; unsigned long fl_downgrade_time; const struct file_lock_operations *fl_ops; /* Callbacks for filesystems */ const struct lock_manager_operations *fl_lmops; /* Callbacks for lockmanagers */ union { struct nfs_lock_info nfs_fl; struct nfs4_lock_info nfs4_fl; struct { struct list_head link; /* link in AFS vnode's pending_locks list */ int state; /* state of grant or error if -ve */ } afs; } fl_u; }; /* The following constant reflects the upper bound of the file/locking space */ #ifndef OFFSET_MAX #define INT_LIMIT(x) (~((x)1 << (sizeof(x)*8 - 1))) #define OFFSET_MAX INT_LIMIT(loff_t) #define OFFT_OFFSET_MAX INT_LIMIT(off_t) #endif #include <linux/fcntl.h> extern void send_sigio(struct fown_struct *fown, int fd, int band); #ifdef CONFIG_FILE_LOCKING extern int fcntl_getlk(struct file *, unsigned int, struct flock __user *); extern int fcntl_setlk(unsigned int, struct file *, unsigned int, struct flock __user *); #if BITS_PER_LONG == 32 extern int fcntl_getlk64(struct file *, unsigned int, struct flock64 __user *); extern int fcntl_setlk64(unsigned int, struct file *, unsigned int, struct flock64 __user *); #endif extern int fcntl_setlease(unsigned int fd, struct file *filp, long arg); extern int fcntl_getlease(struct file *filp); /* fs/locks.c */ void locks_free_lock(struct file_lock *fl); extern void locks_init_lock(struct file_lock *); extern struct file_lock * locks_alloc_lock(void); extern void locks_copy_lock(struct file_lock *, struct file_lock *); extern void locks_copy_conflock(struct file_lock *, struct file_lock *); extern void locks_remove_posix(struct file *, fl_owner_t); extern void locks_remove_file(struct file *); extern void locks_release_private(struct file_lock *); extern void posix_test_lock(struct file *, struct file_lock *); extern int posix_lock_file(struct file *, struct file_lock *, struct file_lock *); extern int posix_lock_file_wait(struct file *, struct file_lock *); extern int posix_unblock_lock(struct file_lock *); extern int vfs_test_lock(struct file *, struct file_lock *); extern int vfs_lock_file(struct file *, unsigned int, struct file_lock *, struct file_lock *); extern int vfs_cancel_lock(struct file *filp, struct file_lock *fl); extern int flock_lock_file_wait(struct file *filp, struct file_lock *fl); extern int __break_lease(struct inode *inode, unsigned int flags, unsigned int type); extern void lease_get_mtime(struct inode *, struct timespec *time); extern int generic_setlease(struct file *, long, struct file_lock **, void **priv); extern int vfs_setlease(struct file *, long, struct file_lock **, void **); extern int lease_modify(struct file_lock **, int, struct list_head *); #else /* !CONFIG_FILE_LOCKING */ static inline int fcntl_getlk(struct file *file, unsigned int cmd, struct flock __user *user) { return -EINVAL; } static inline int fcntl_setlk(unsigned int fd, struct file *file, unsigned int cmd, struct flock __user *user) { return -EACCES; } #if BITS_PER_LONG == 32 static inline int fcntl_getlk64(struct file *file, unsigned int cmd, struct flock64 __user *user) { return -EINVAL; } static inline int fcntl_setlk64(unsigned int fd, struct file *file, unsigned int cmd, struct flock64 __user *user) { return -EACCES; } #endif static inline int fcntl_setlease(unsigned int fd, struct file *filp, long arg) { return -EINVAL; } static inline int fcntl_getlease(struct file *filp) { return F_UNLCK; } static inline void locks_init_lock(struct file_lock *fl) { return; } static inline void locks_copy_conflock(struct file_lock *new, struct file_lock *fl) { return; } static inline void locks_copy_lock(struct file_lock *new, struct file_lock *fl) { return; } static inline void locks_remove_posix(struct file *filp, fl_owner_t owner) { return; } static inline void locks_remove_file(struct file *filp) { return; } static inline void posix_test_lock(struct file *filp, struct file_lock *fl) { return; } static inline int posix_lock_file(struct file *filp, struct file_lock *fl, struct file_lock *conflock) { return -ENOLCK; } static inline int posix_lock_file_wait(struct file *filp, struct file_lock *fl) { return -ENOLCK; } static inline int posix_unblock_lock(struct file_lock *waiter) { return -ENOENT; } static inline int vfs_test_lock(struct file *filp, struct file_lock *fl) { return 0; } static inline int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf) { return -ENOLCK; } static inline int vfs_cancel_lock(struct file *filp, struct file_lock *fl) { return 0; } static inline int flock_lock_file_wait(struct file *filp, struct file_lock *request) { return -ENOLCK; } static inline int __break_lease(struct inode *inode, unsigned int mode, unsigned int type) { return 0; } static inline void lease_get_mtime(struct inode *inode, struct timespec *time) { return; } static inline int generic_setlease(struct file *filp, long arg, struct file_lock **flp, void **priv) { return -EINVAL; } static inline int vfs_setlease(struct file *filp, long arg, struct file_lock **lease, void **priv) { return -EINVAL; } static inline int lease_modify(struct file_lock **before, int arg, struct list_head *dispose) { return -EINVAL; } #endif /* !CONFIG_FILE_LOCKING */ struct fasync_struct { spinlock_t fa_lock; int magic; int fa_fd; struct fasync_struct *fa_next; /* singly linked list */ struct file *fa_file; struct rcu_head fa_rcu; }; #define FASYNC_MAGIC 0x4601 /* SMP safe fasync helpers: */ extern int fasync_helper(int, struct file *, int, struct fasync_struct **); extern struct fasync_struct *fasync_insert_entry(int, struct file *, struct fasync_struct **, struct fasync_struct *); extern int fasync_remove_entry(struct file *, struct fasync_struct **); extern struct fasync_struct *fasync_alloc(void); extern void fasync_free(struct fasync_struct *); /* can be called from interrupts */ extern void kill_fasync(struct fasync_struct **, int, int); extern void __f_setown(struct file *filp, struct pid *, enum pid_type, int force); extern void f_setown(struct file *filp, unsigned long arg, int force); extern void f_delown(struct file *filp); extern pid_t f_getown(struct file *filp); extern int send_sigurg(struct fown_struct *fown); struct mm_struct; /* * Umount options */ #define MNT_FORCE 0x00000001 /* Attempt to forcibily umount */ #define MNT_DETACH 0x00000002 /* Just detach from the tree */ #define MNT_EXPIRE 0x00000004 /* Mark for expiry */ #define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */ #define UMOUNT_UNUSED 0x80000000 /* Flag guaranteed to be unused */ extern struct list_head super_blocks; extern spinlock_t sb_lock; /* Possible states of 'frozen' field */ enum { SB_UNFROZEN = 0, /* FS is unfrozen */ SB_FREEZE_WRITE = 1, /* Writes, dir ops, ioctls frozen */ SB_FREEZE_PAGEFAULT = 2, /* Page faults stopped as well */ SB_FREEZE_FS = 3, /* For internal FS use (e.g. to stop * internal threads if needed) */ SB_FREEZE_COMPLETE = 4, /* ->freeze_fs finished successfully */ }; #define SB_FREEZE_LEVELS (SB_FREEZE_COMPLETE - 1) struct sb_writers { /* Counters for counting writers at each level */ struct percpu_counter counter[SB_FREEZE_LEVELS]; wait_queue_head_t wait; /* queue for waiting for writers / faults to finish */ int frozen; /* Is sb frozen? */ wait_queue_head_t wait_unfrozen; /* queue for waiting for sb to be thawed */ #ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map lock_map[SB_FREEZE_LEVELS]; #endif }; struct super_block { struct list_head s_list; /* Keep this first */ dev_t s_dev; /* search index; _not_ kdev_t */ unsigned char s_blocksize_bits; unsigned long s_blocksize; loff_t s_maxbytes; /* Max file size */ struct file_system_type *s_type; const struct super_operations *s_op; const struct dquot_operations *dq_op; const struct quotactl_ops *s_qcop; const struct export_operations *s_export_op; unsigned long s_flags; unsigned long s_magic; struct dentry *s_root; struct rw_semaphore s_umount; int s_count; atomic_t s_active; #ifdef CONFIG_SECURITY void *s_security; #endif const struct xattr_handler **s_xattr; struct list_head s_inodes; /* all inodes */ struct hlist_bl_head s_anon; /* anonymous dentries for (nfs) exporting */ struct list_head s_mounts; /* list of mounts; _not_ for fs use */ struct block_device *s_bdev; struct backing_dev_info *s_bdi; struct mtd_info *s_mtd; struct hlist_node s_instances; struct quota_info s_dquot; /* Diskquota specific options */ struct sb_writers s_writers; char s_id[32]; /* Informational name */ u8 s_uuid[16]; /* UUID */ void *s_fs_info; /* Filesystem private info */ unsigned int s_max_links; fmode_t s_mode; /* Granularity of c/m/atime in ns. Cannot be worse than a second */ u32 s_time_gran; /* * The next field is for VFS *only*. No filesystems have any business * even looking at it. You had been warned. */ struct mutex s_vfs_rename_mutex; /* Kludge */ /* * Filesystem subtype. If non-empty the filesystem type field * in /proc/mounts will be "type.subtype" */ char *s_subtype; /* * Saved mount options for lazy filesystems using * generic_show_options() */ char __rcu *s_options; const struct dentry_operations *s_d_op; /* default d_op for dentries */ /* * Saved pool identifier for cleancache (-1 means none) */ int cleancache_poolid; struct shrinker s_shrink; /* per-sb shrinker handle */ /* Number of inodes with nlink == 0 but still referenced */ atomic_long_t s_remove_count; /* Being remounted read-only */ int s_readonly_remount; /* AIO completions deferred from interrupt context */ struct workqueue_struct *s_dio_done_wq; struct hlist_head s_pins; /* * Keep the lru lists last in the structure so they always sit on their * own individual cachelines. */ struct list_lru s_dentry_lru ____cacheline_aligned_in_smp; struct list_lru s_inode_lru ____cacheline_aligned_in_smp; struct rcu_head rcu; /* * Indicates how deep in a filesystem stack this SB is */ int s_stack_depth; }; extern struct timespec current_fs_time(struct super_block *sb); /* * Snapshotting support. */ void __sb_end_write(struct super_block *sb, int level); int __sb_start_write(struct super_block *sb, int level, bool wait); /** * sb_end_write - drop write access to a superblock * @sb: the super we wrote to * * Decrement number of writers to the filesystem. Wake up possible waiters * wanting to freeze the filesystem. */ static inline void sb_end_write(struct super_block *sb) { __sb_end_write(sb, SB_FREEZE_WRITE); } /** * sb_end_pagefault - drop write access to a superblock from a page fault * @sb: the super we wrote to * * Decrement number of processes handling write page fault to the filesystem. * Wake up possible waiters wanting to freeze the filesystem. */ static inline void sb_end_pagefault(struct super_block *sb) { __sb_end_write(sb, SB_FREEZE_PAGEFAULT); } /** * sb_end_intwrite - drop write access to a superblock for internal fs purposes * @sb: the super we wrote to * * Decrement fs-internal number of writers to the filesystem. Wake up possible * waiters wanting to freeze the filesystem. */ static inline void sb_end_intwrite(struct super_block *sb) { __sb_end_write(sb, SB_FREEZE_FS); } /** * sb_start_write - get write access to a superblock * @sb: the super we write to * * When a process wants to write data or metadata to a file system (i.e. dirty * a page or an inode), it should embed the operation in a sb_start_write() - * sb_end_write() pair to get exclusion against file system freezing. This * function increments number of writers preventing freezing. If the file * system is already frozen, the function waits until the file system is * thawed. * * Since freeze protection behaves as a lock, users have to preserve * ordering of freeze protection and other filesystem locks. Generally, * freeze protection should be the outermost lock. In particular, we have: * * sb_start_write * -> i_mutex (write path, truncate, directory ops, ...) * -> s_umount (freeze_super, thaw_super) */ static inline void sb_start_write(struct super_block *sb) { __sb_start_write(sb, SB_FREEZE_WRITE, true); } static inline int sb_start_write_trylock(struct super_block *sb) { return __sb_start_write(sb, SB_FREEZE_WRITE, false); } /** * sb_start_pagefault - get write access to a superblock from a page fault * @sb: the super we write to * * When a process starts handling write page fault, it should embed the * operation into sb_start_pagefault() - sb_end_pagefault() pair to get * exclusion against file system freezing. This is needed since the page fault * is going to dirty a page. This function increments number of running page * faults preventing freezing. If the file system is already frozen, the * function waits until the file system is thawed. * * Since page fault freeze protection behaves as a lock, users have to preserve * ordering of freeze protection and other filesystem locks. It is advised to * put sb_start_pagefault() close to mmap_sem in lock ordering. Page fault * handling code implies lock dependency: * * mmap_sem * -> sb_start_pagefault */ static inline void sb_start_pagefault(struct super_block *sb) { __sb_start_write(sb, SB_FREEZE_PAGEFAULT, true); } /* * sb_start_intwrite - get write access to a superblock for internal fs purposes * @sb: the super we write to * * This is the third level of protection against filesystem freezing. It is * free for use by a filesystem. The only requirement is that it must rank * below sb_start_pagefault. * * For example filesystem can call sb_start_intwrite() when starting a * transaction which somewhat eases handling of freezing for internal sources * of filesystem changes (internal fs threads, discarding preallocation on file * close, etc.). */ static inline void sb_start_intwrite(struct super_block *sb) { __sb_start_write(sb, SB_FREEZE_FS, true); } extern bool inode_owner_or_capable(const struct inode *inode); /* * VFS helper functions.. */ extern int vfs_create(struct inode *, struct dentry *, umode_t, bool); extern int vfs_mkdir(struct inode *, struct dentry *, umode_t); extern int vfs_mknod(struct inode *, struct dentry *, umode_t, dev_t); extern int vfs_symlink(struct inode *, struct dentry *, const char *); extern int vfs_link(struct dentry *, struct inode *, struct dentry *, struct inode **); extern int vfs_rmdir(struct inode *, struct dentry *); extern int vfs_unlink(struct inode *, struct dentry *, struct inode **); extern int vfs_rename(struct inode *, struct dentry *, struct inode *, struct dentry *, struct inode **, unsigned int); extern int vfs_whiteout(struct inode *, struct dentry *); /* * VFS dentry helper functions. */ extern void dentry_unhash(struct dentry *dentry); /* * VFS file helper functions. */ extern void inode_init_owner(struct inode *inode, const struct inode *dir, umode_t mode); /* * VFS FS_IOC_FIEMAP helper definitions. */ struct fiemap_extent_info { unsigned int fi_flags; /* Flags as passed from user */ unsigned int fi_extents_mapped; /* Number of mapped extents */ unsigned int fi_extents_max; /* Size of fiemap_extent array */ struct fiemap_extent __user *fi_extents_start; /* Start of fiemap_extent array */ }; int fiemap_fill_next_extent(struct fiemap_extent_info *info, u64 logical, u64 phys, u64 len, u32 flags); int fiemap_check_flags(struct fiemap_extent_info *fieinfo, u32 fs_flags); /* * File types * * NOTE! These match bits 12..15 of stat.st_mode * (ie "(i_mode >> 12) & 15"). */ #define DT_UNKNOWN 0 #define DT_FIFO 1 #define DT_CHR 2 #define DT_DIR 4 #define DT_BLK 6 #define DT_REG 8 #define DT_LNK 10 #define DT_SOCK 12 #define DT_WHT 14 /* * This is the "filldir" function type, used by readdir() to let * the kernel specify what kind of dirent layout it wants to have. * This allows the kernel to read directories into kernel space or * to have different dirent layouts depending on the binary type. */ typedef int (*filldir_t)(void *, const char *, int, loff_t, u64, unsigned); struct dir_context { const filldir_t actor; loff_t pos; }; struct block_device_operations; /* These macros are for out of kernel modules to test that * the kernel supports the unlocked_ioctl and compat_ioctl * fields in struct file_operations. */ #define HAVE_COMPAT_IOCTL 1 #define HAVE_UNLOCKED_IOCTL 1 struct iov_iter; struct file_operations { struct module *owner; loff_t (*llseek) (struct file *, loff_t, int); ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t (*read_iter) (struct kiocb *, struct iov_iter *); ssize_t (*write_iter) (struct kiocb *, struct iov_iter *); int (*iterate) (struct file *, struct dir_context *); unsigned int (*poll) (struct file *, struct poll_table_struct *); long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); long (*compat_ioctl) (struct file *, unsigned int, unsigned long); int (*mmap) (struct file *, struct vm_area_struct *); int (*open) (struct inode *, struct file *); int (*flush) (struct file *, fl_owner_t id); int (*release) (struct inode *, struct file *); int (*fsync) (struct file *, loff_t, loff_t, int datasync); int (*aio_fsync) (struct kiocb *, int datasync); int (*fasync) (int, struct file *, int); int (*lock) (struct file *, int, struct file_lock *); ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); int (*check_flags)(int); int (*flock) (struct file *, int, struct file_lock *); ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); int (*setlease)(struct file *, long, struct file_lock **, void **); long (*fallocate)(struct file *file, int mode, loff_t offset, loff_t len); int (*show_fdinfo)(struct seq_file *m, struct file *f); }; struct inode_operations { struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int); void * (*follow_link) (struct dentry *, struct nameidata *); int (*permission) (struct inode *, int); struct posix_acl * (*get_acl)(struct inode *, int); int (*readlink) (struct dentry *, char __user *,int); void (*put_link) (struct dentry *, struct nameidata *, void *); int (*create) (struct inode *,struct dentry *, umode_t, bool); int (*link) (struct dentry *,struct inode *,struct dentry *); int (*unlink) (struct inode *,struct dentry *); int (*symlink) (struct inode *,struct dentry *,const char *); int (*mkdir) (struct inode *,struct dentry *,umode_t); int (*rmdir) (struct inode *,struct dentry *); int (*mknod) (struct inode *,struct dentry *,umode_t,dev_t); int (*rename) (struct inode *, struct dentry *, struct inode *, struct dentry *); int (*rename2) (struct inode *, struct dentry *, struct inode *, struct dentry *, unsigned int); int (*setattr) (struct dentry *, struct iattr *); int (*getattr) (struct vfsmount *mnt, struct dentry *, struct kstat *); int (*setxattr) (struct dentry *, const char *,const void *,size_t,int); ssize_t (*getxattr) (struct dentry *, const char *, void *, size_t); ssize_t (*listxattr) (struct dentry *, char *, size_t); int (*removexattr) (struct dentry *, const char *); int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start, u64 len); int (*update_time)(struct inode *, struct timespec *, int); int (*atomic_open)(struct inode *, struct dentry *, struct file *, unsigned open_flag, umode_t create_mode, int *opened); int (*tmpfile) (struct inode *, struct dentry *, umode_t); int (*set_acl)(struct inode *, struct posix_acl *, int); /* WARNING: probably going away soon, do not use! */ } ____cacheline_aligned; ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector, unsigned long nr_segs, unsigned long fast_segs, struct iovec *fast_pointer, struct iovec **ret_pointer); extern ssize_t vfs_read(struct file *, char __user *, size_t, loff_t *); extern ssize_t vfs_write(struct file *, const char __user *, size_t, loff_t *); extern ssize_t vfs_readv(struct file *, const struct iovec __user *, unsigned long, loff_t *); extern ssize_t vfs_writev(struct file *, const struct iovec __user *, unsigned long, loff_t *); struct super_operations { struct inode *(*alloc_inode)(struct super_block *sb); void (*destroy_inode)(struct inode *); void (*dirty_inode) (struct inode *, int flags); int (*write_inode) (struct inode *, struct writeback_control *wbc); int (*drop_inode) (struct inode *); void (*evict_inode) (struct inode *); void (*put_super) (struct super_block *); int (*sync_fs)(struct super_block *sb, int wait); int (*freeze_fs) (struct super_block *); int (*unfreeze_fs) (struct super_block *); int (*statfs) (struct dentry *, struct kstatfs *); int (*remount_fs) (struct super_block *, int *, char *); void (*umount_begin) (struct super_block *); int (*show_options)(struct seq_file *, struct dentry *); int (*show_devname)(struct seq_file *, struct dentry *); int (*show_path)(struct seq_file *, struct dentry *); int (*show_stats)(struct seq_file *, struct dentry *); #ifdef CONFIG_QUOTA ssize_t (*quota_read)(struct super_block *, int, char *, size_t, loff_t); ssize_t (*quota_write)(struct super_block *, int, const char *, size_t, loff_t); #endif int (*bdev_try_to_free_page)(struct super_block*, struct page*, gfp_t); long (*nr_cached_objects)(struct super_block *, int); long (*free_cached_objects)(struct super_block *, long, int); }; /* * Inode flags - they have no relation to superblock flags now */ #define S_SYNC 1 /* Writes are synced at once */ #define S_NOATIME 2 /* Do not update access times */ #define S_APPEND 4 /* Append-only file */ #define S_IMMUTABLE 8 /* Immutable file */ #define S_DEAD 16 /* removed, but still open directory */ #define S_NOQUOTA 32 /* Inode is not counted to quota */ #define S_DIRSYNC 64 /* Directory modifications are synchronous */ #define S_NOCMTIME 128 /* Do not update file c/mtime */ #define S_SWAPFILE 256 /* Do not truncate: swapon got its bmaps */ #define S_PRIVATE 512 /* Inode is fs-internal */ #define S_IMA 1024 /* Inode has an associated IMA struct */ #define S_AUTOMOUNT 2048 /* Automount/referral quasi-directory */ #define S_NOSEC 4096 /* no suid or xattr security attributes */ /* * Note that nosuid etc flags are inode-specific: setting some file-system * flags just means all the inodes inherit those flags by default. It might be * possible to override it selectively if you really wanted to with some * ioctl() that is not currently implemented. * * Exception: MS_RDONLY is always applied to the entire file system. * * Unfortunately, it is possible to change a filesystems flags with it mounted * with files in use. This means that all of the inodes will not have their * i_flags updated. Hence, i_flags no longer inherit the superblock mount * flags, so these have to be checked separately. -- [email protected] */ #define __IS_FLG(inode, flg) ((inode)->i_sb->s_flags & (flg)) #define IS_RDONLY(inode) ((inode)->i_sb->s_flags & MS_RDONLY) #define IS_SYNC(inode) (__IS_FLG(inode, MS_SYNCHRONOUS) || \ ((inode)->i_flags & S_SYNC)) #define IS_DIRSYNC(inode) (__IS_FLG(inode, MS_SYNCHRONOUS|MS_DIRSYNC) || \ ((inode)->i_flags & (S_SYNC|S_DIRSYNC))) #define IS_MANDLOCK(inode) __IS_FLG(inode, MS_MANDLOCK) #define IS_NOATIME(inode) __IS_FLG(inode, MS_RDONLY|MS_NOATIME) #define IS_I_VERSION(inode) __IS_FLG(inode, MS_I_VERSION) #define IS_NOQUOTA(inode) ((inode)->i_flags & S_NOQUOTA) #define IS_APPEND(inode) ((inode)->i_flags & S_APPEND) #define IS_IMMUTABLE(inode) ((inode)->i_flags & S_IMMUTABLE) #define IS_POSIXACL(inode) __IS_FLG(inode, MS_POSIXACL) #define IS_DEADDIR(inode) ((inode)->i_flags & S_DEAD) #define IS_NOCMTIME(inode) ((inode)->i_flags & S_NOCMTIME) #define IS_SWAPFILE(inode) ((inode)->i_flags & S_SWAPFILE) #define IS_PRIVATE(inode) ((inode)->i_flags & S_PRIVATE) #define IS_IMA(inode) ((inode)->i_flags & S_IMA) #define IS_AUTOMOUNT(inode) ((inode)->i_flags & S_AUTOMOUNT) #define IS_NOSEC(inode) ((inode)->i_flags & S_NOSEC) #define IS_WHITEOUT(inode) (S_ISCHR(inode->i_mode) && \ (inode)->i_rdev == WHITEOUT_DEV) /* * Inode state bits. Protected by inode->i_lock * * Three bits determine the dirty state of the inode, I_DIRTY_SYNC, * I_DIRTY_DATASYNC and I_DIRTY_PAGES. * * Four bits define the lifetime of an inode. Initially, inodes are I_NEW, * until that flag is cleared. I_WILL_FREE, I_FREEING and I_CLEAR are set at * various stages of removing an inode. * * Two bits are used for locking and completion notification, I_NEW and I_SYNC. * * I_DIRTY_SYNC Inode is dirty, but doesn't have to be written on * fdatasync(). i_atime is the usual cause. * I_DIRTY_DATASYNC Data-related inode changes pending. We keep track of * these changes separately from I_DIRTY_SYNC so that we * don't have to write inode on fdatasync() when only * mtime has changed in it. * I_DIRTY_PAGES Inode has dirty pages. Inode itself may be clean. * I_NEW Serves as both a mutex and completion notification. * New inodes set I_NEW. If two processes both create * the same inode, one of them will release its inode and * wait for I_NEW to be released before returning. * Inodes in I_WILL_FREE, I_FREEING or I_CLEAR state can * also cause waiting on I_NEW, without I_NEW actually * being set. find_inode() uses this to prevent returning * nearly-dead inodes. * I_WILL_FREE Must be set when calling write_inode_now() if i_count * is zero. I_FREEING must be set when I_WILL_FREE is * cleared. * I_FREEING Set when inode is about to be freed but still has dirty * pages or buffers attached or the inode itself is still * dirty. * I_CLEAR Added by clear_inode(). In this state the inode is * clean and can be destroyed. Inode keeps I_FREEING. * * Inodes that are I_WILL_FREE, I_FREEING or I_CLEAR are * prohibited for many purposes. iget() must wait for * the inode to be completely released, then create it * anew. Other functions will just ignore such inodes, * if appropriate. I_NEW is used for waiting. * * I_SYNC Writeback of inode is running. The bit is set during * data writeback, and cleared with a wakeup on the bit * address once it is done. The bit is also used to pin * the inode in memory for flusher thread. * * I_REFERENCED Marks the inode as recently references on the LRU list. * * I_DIO_WAKEUP Never set. Only used as a key for wait_on_bit(). * * Q: What is the difference between I_WILL_FREE and I_FREEING? */ #define I_DIRTY_SYNC (1 << 0) #define I_DIRTY_DATASYNC (1 << 1) #define I_DIRTY_PAGES (1 << 2) #define __I_NEW 3 #define I_NEW (1 << __I_NEW) #define I_WILL_FREE (1 << 4) #define I_FREEING (1 << 5) #define I_CLEAR (1 << 6) #define __I_SYNC 7 #define I_SYNC (1 << __I_SYNC) #define I_REFERENCED (1 << 8) #define __I_DIO_WAKEUP 9 #define I_DIO_WAKEUP (1 << I_DIO_WAKEUP) #define I_LINKABLE (1 << 10) #define I_DIRTY (I_DIRTY_SYNC | I_DIRTY_DATASYNC | I_DIRTY_PAGES) extern void __mark_inode_dirty(struct inode *, int); static inline void mark_inode_dirty(struct inode *inode) { __mark_inode_dirty(inode, I_DIRTY); } static inline void mark_inode_dirty_sync(struct inode *inode) { __mark_inode_dirty(inode, I_DIRTY_SYNC); } extern void inc_nlink(struct inode *inode); extern void drop_nlink(struct inode *inode); extern void clear_nlink(struct inode *inode); extern void set_nlink(struct inode *inode, unsigned int nlink); static inline void inode_inc_link_count(struct inode *inode) { inc_nlink(inode); mark_inode_dirty(inode); } static inline void inode_dec_link_count(struct inode *inode) { drop_nlink(inode); mark_inode_dirty(inode); } /** * inode_inc_iversion - increments i_version * @inode: inode that need to be updated * * Every time the inode is modified, the i_version field will be incremented. * The filesystem has to be mounted with i_version flag */ static inline void inode_inc_iversion(struct inode *inode) { spin_lock(&inode->i_lock); inode->i_version++; spin_unlock(&inode->i_lock); } enum file_time_flags { S_ATIME = 1, S_MTIME = 2, S_CTIME = 4, S_VERSION = 8, }; extern void touch_atime(const struct path *); static inline void file_accessed(struct file *file) { if (!(file->f_flags & O_NOATIME)) touch_atime(&file->f_path); } int sync_inode(struct inode *inode, struct writeback_control *wbc); int sync_inode_metadata(struct inode *inode, int wait); struct file_system_type { const char *name; int fs_flags; #define FS_REQUIRES_DEV 1 #define FS_BINARY_MOUNTDATA 2 #define FS_HAS_SUBTYPE 4 #define FS_USERNS_MOUNT 8 /* Can be mounted by userns root */ #define FS_USERNS_DEV_MOUNT 16 /* A userns mount does not imply MNT_NODEV */ #define FS_USERNS_VISIBLE 32 /* FS must already be visible */ #define FS_RENAME_DOES_D_MOVE 32768 /* FS will handle d_move() during rename() internally. */ struct dentry *(*mount) (struct file_system_type *, int, const char *, void *); void (*kill_sb) (struct super_block *); struct module *owner; struct file_system_type * next; struct hlist_head fs_supers; struct lock_class_key s_lock_key; struct lock_class_key s_umount_key; struct lock_class_key s_vfs_rename_key; struct lock_class_key s_writers_key[SB_FREEZE_LEVELS]; struct lock_class_key i_lock_key; struct lock_class_key i_mutex_key; struct lock_class_key i_mutex_dir_key; }; #define MODULE_ALIAS_FS(NAME) MODULE_ALIAS("fs-" NAME) extern struct dentry *mount_ns(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)); extern struct dentry *mount_bdev(struct file_system_type *fs_type, int flags, const char *dev_name, void *data, int (*fill_super)(struct super_block *, void *, int)); extern struct dentry *mount_single(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)); extern struct dentry *mount_nodev(struct file_system_type *fs_type, int flags, void *data, int (*fill_super)(struct super_block *, void *, int)); extern struct dentry *mount_subtree(struct vfsmount *mnt, const char *path); void generic_shutdown_super(struct super_block *sb); void kill_block_super(struct super_block *sb); void kill_anon_super(struct super_block *sb); void kill_litter_super(struct super_block *sb); void deactivate_super(struct super_block *sb); void deactivate_locked_super(struct super_block *sb); int set_anon_super(struct super_block *s, void *data); int get_anon_bdev(dev_t *); void free_anon_bdev(dev_t); struct super_block *sget(struct file_system_type *type, int (*test)(struct super_block *,void *), int (*set)(struct super_block *,void *), int flags, void *data); extern struct dentry *mount_pseudo(struct file_system_type *, char *, const struct super_operations *ops, const struct dentry_operations *dops, unsigned long); /* Alas, no aliases. Too much hassle with bringing module.h everywhere */ #define fops_get(fops) \ (((fops) && try_module_get((fops)->owner) ? (fops) : NULL)) #define fops_put(fops) \ do { if (fops) module_put((fops)->owner); } while(0) /* * This one is to be used *ONLY* from ->open() instances. * fops must be non-NULL, pinned down *and* module dependencies * should be sufficient to pin the caller down as well. */ #define replace_fops(f, fops) \ do { \ struct file *__file = (f); \ fops_put(__file->f_op); \ BUG_ON(!(__file->f_op = (fops))); \ } while(0) extern int register_filesystem(struct file_system_type *); extern int unregister_filesystem(struct file_system_type *); extern struct vfsmount *kern_mount_data(struct file_system_type *, void *data); #define kern_mount(type) kern_mount_data(type, NULL) extern void kern_unmount(struct vfsmount *mnt); extern int may_umount_tree(struct vfsmount *); extern int may_umount(struct vfsmount *); extern long do_mount(const char *, const char __user *, const char *, unsigned long, void *); extern struct vfsmount *collect_mounts(struct path *); extern void drop_collected_mounts(struct vfsmount *); extern int iterate_mounts(int (*)(struct vfsmount *, void *), void *, struct vfsmount *); extern int vfs_statfs(struct path *, struct kstatfs *); extern int user_statfs(const char __user *, struct kstatfs *); extern int fd_statfs(int, struct kstatfs *); extern int vfs_ustat(dev_t, struct kstatfs *); extern int freeze_super(struct super_block *super); extern int thaw_super(struct super_block *super); extern bool our_mnt(struct vfsmount *mnt); extern int current_umask(void); extern void ihold(struct inode * inode); extern void iput(struct inode *); static inline struct inode *file_inode(const struct file *f) { return f->f_inode; } /* /sys/fs */ extern struct kobject *fs_kobj; #define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK) #define FLOCK_VERIFY_READ 1 #define FLOCK_VERIFY_WRITE 2 #ifdef CONFIG_FILE_LOCKING extern int locks_mandatory_locked(struct file *); extern int locks_mandatory_area(int, struct inode *, struct file *, loff_t, size_t); /* * Candidates for mandatory locking have the setgid bit set * but no group execute bit - an otherwise meaningless combination. */ static inline int __mandatory_lock(struct inode *ino) { return (ino->i_mode & (S_ISGID | S_IXGRP)) == S_ISGID; } /* * ... and these candidates should be on MS_MANDLOCK mounted fs, * otherwise these will be advisory locks */ static inline int mandatory_lock(struct inode *ino) { return IS_MANDLOCK(ino) && __mandatory_lock(ino); } static inline int locks_verify_locked(struct file *file) { if (mandatory_lock(file_inode(file))) return locks_mandatory_locked(file); return 0; } static inline int locks_verify_truncate(struct inode *inode, struct file *filp, loff_t size) { if (inode->i_flock && mandatory_lock(inode)) return locks_mandatory_area( FLOCK_VERIFY_WRITE, inode, filp, size < inode->i_size ? size : inode->i_size, (size < inode->i_size ? inode->i_size - size : size - inode->i_size) ); return 0; } static inline int break_lease(struct inode *inode, unsigned int mode) { /* * Since this check is lockless, we must ensure that any refcounts * taken are done before checking inode->i_flock. Otherwise, we could * end up racing with tasks trying to set a new lease on this file. */ smp_mb(); if (inode->i_flock) return __break_lease(inode, mode, FL_LEASE); return 0; } static inline int break_deleg(struct inode *inode, unsigned int mode) { /* * Since this check is lockless, we must ensure that any refcounts * taken are done before checking inode->i_flock. Otherwise, we could * end up racing with tasks trying to set a new lease on this file. */ smp_mb(); if (inode->i_flock) return __break_lease(inode, mode, FL_DELEG); return 0; } static inline int try_break_deleg(struct inode *inode, struct inode **delegated_inode) { int ret; ret = break_deleg(inode, O_WRONLY|O_NONBLOCK); if (ret == -EWOULDBLOCK && delegated_inode) { *delegated_inode = inode; ihold(inode); } return ret; } static inline int break_deleg_wait(struct inode **delegated_inode) { int ret; ret = break_deleg(*delegated_inode, O_WRONLY); iput(*delegated_inode); *delegated_inode = NULL; return ret; } #else /* !CONFIG_FILE_LOCKING */ static inline int locks_mandatory_locked(struct file *file) { return 0; } static inline int locks_mandatory_area(int rw, struct inode *inode, struct file *filp, loff_t offset, size_t count) { return 0; } static inline int __mandatory_lock(struct inode *inode) { return 0; } static inline int mandatory_lock(struct inode *inode) { return 0; } static inline int locks_verify_locked(struct file *file) { return 0; } static inline int locks_verify_truncate(struct inode *inode, struct file *filp, size_t size) { return 0; } static inline int break_lease(struct inode *inode, unsigned int mode) { return 0; } static inline int break_deleg(struct inode *inode, unsigned int mode) { return 0; } static inline int try_break_deleg(struct inode *inode, struct inode **delegated_inode) { return 0; } static inline int break_deleg_wait(struct inode **delegated_inode) { BUG(); return 0; } #endif /* CONFIG_FILE_LOCKING */ /* fs/open.c */ struct audit_names; struct filename { const char *name; /* pointer to actual string */ const __user char *uptr; /* original userland pointer */ struct audit_names *aname; bool separate; /* should "name" be freed? */ }; extern long vfs_truncate(struct path *, loff_t); extern int do_truncate(struct dentry *, loff_t start, unsigned int time_attrs, struct file *filp); extern int do_fallocate(struct file *file, int mode, loff_t offset, loff_t len); extern long do_sys_open(int dfd, const char __user *filename, int flags, umode_t mode); extern struct file *file_open_name(struct filename *, int, umode_t); extern struct file *filp_open(const char *, int, umode_t); extern struct file *file_open_root(struct dentry *, struct vfsmount *, const char *, int); extern struct file * dentry_open(const struct path *, int, const struct cred *); extern int filp_close(struct file *, fl_owner_t id); extern struct filename *getname(const char __user *); extern struct filename *getname_kernel(const char *); enum { FILE_CREATED = 1, FILE_OPENED = 2 }; extern int finish_open(struct file *file, struct dentry *dentry, int (*open)(struct inode *, struct file *), int *opened); extern int finish_no_open(struct file *file, struct dentry *dentry); /* fs/ioctl.c */ extern int ioctl_preallocate(struct file *filp, void __user *argp); /* fs/dcache.c */ extern void __init vfs_caches_init_early(void); extern void __init vfs_caches_init(unsigned long); extern struct kmem_cache *names_cachep; extern void final_putname(struct filename *name); #define __getname() kmem_cache_alloc(names_cachep, GFP_KERNEL) #define __putname(name) kmem_cache_free(names_cachep, (void *)(name)) #ifndef CONFIG_AUDITSYSCALL #define putname(name) final_putname(name) #else extern void putname(struct filename *name); #endif #ifdef CONFIG_BLOCK extern int register_blkdev(unsigned int, const char *); extern void unregister_blkdev(unsigned int, const char *); extern struct block_device *bdget(dev_t); extern struct block_device *bdgrab(struct block_device *bdev); extern void bd_set_size(struct block_device *, loff_t size); extern void bd_forget(struct inode *inode); extern void bdput(struct block_device *); extern void invalidate_bdev(struct block_device *); extern void iterate_bdevs(void (*)(struct block_device *, void *), void *); extern int sync_blockdev(struct block_device *bdev); extern void kill_bdev(struct block_device *); extern struct super_block *freeze_bdev(struct block_device *); extern void emergency_thaw_all(void); extern int thaw_bdev(struct block_device *bdev, struct super_block *sb); extern int fsync_bdev(struct block_device *); extern int sb_is_blkdev_sb(struct super_block *sb); #else static inline void bd_forget(struct inode *inode) {} static inline int sync_blockdev(struct block_device *bdev) { return 0; } static inline void kill_bdev(struct block_device *bdev) {} static inline void invalidate_bdev(struct block_device *bdev) {} static inline struct super_block *freeze_bdev(struct block_device *sb) { return NULL; } static inline int thaw_bdev(struct block_device *bdev, struct super_block *sb) { return 0; } static inline void iterate_bdevs(void (*f)(struct block_device *, void *), void *arg) { } static inline int sb_is_blkdev_sb(struct super_block *sb) { return 0; } #endif extern int sync_filesystem(struct super_block *); extern const struct file_operations def_blk_fops; extern const struct file_operations def_chr_fops; extern const struct file_operations bad_sock_fops; #ifdef CONFIG_BLOCK extern int ioctl_by_bdev(struct block_device *, unsigned, unsigned long); extern int blkdev_ioctl(struct block_device *, fmode_t, unsigned, unsigned long); extern long compat_blkdev_ioctl(struct file *, unsigned, unsigned long); extern int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder); extern struct block_device *blkdev_get_by_path(const char *path, fmode_t mode, void *holder); extern struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode, void *holder); extern void blkdev_put(struct block_device *bdev, fmode_t mode); #ifdef CONFIG_SYSFS extern int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk); extern void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk); #else static inline int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk) { return 0; } static inline void bd_unlink_disk_holder(struct block_device *bdev, struct gendisk *disk) { } #endif #endif /* fs/char_dev.c */ #define CHRDEV_MAJOR_HASH_SIZE 255 extern int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *); extern int register_chrdev_region(dev_t, unsigned, const char *); extern int __register_chrdev(unsigned int major, unsigned int baseminor, unsigned int count, const char *name, const struct file_operations *fops); extern void __unregister_chrdev(unsigned int major, unsigned int baseminor, unsigned int count, const char *name); extern void unregister_chrdev_region(dev_t, unsigned); extern void chrdev_show(struct seq_file *,off_t); static inline int register_chrdev(unsigned int major, const char *name, const struct file_operations *fops) { return __register_chrdev(major, 0, 256, name, fops); } static inline void unregister_chrdev(unsigned int major, const char *name) { __unregister_chrdev(major, 0, 256, name); } /* fs/block_dev.c */ #define BDEVNAME_SIZE 32 /* Largest string for a blockdev identifier */ #define BDEVT_SIZE 10 /* Largest string for MAJ:MIN for blkdev */ #ifdef CONFIG_BLOCK #define BLKDEV_MAJOR_HASH_SIZE 255 extern const char *__bdevname(dev_t, char *buffer); extern const char *bdevname(struct block_device *bdev, char *buffer); extern struct block_device *lookup_bdev(const char *); extern void blkdev_show(struct seq_file *,off_t); #else #define BLKDEV_MAJOR_HASH_SIZE 0 #endif extern void init_special_inode(struct inode *, umode_t, dev_t); /* Invalid inode operations -- fs/bad_inode.c */ extern void make_bad_inode(struct inode *); extern int is_bad_inode(struct inode *); #ifdef CONFIG_BLOCK /* * return READ, READA, or WRITE */ #define bio_rw(bio) ((bio)->bi_rw & (RW_MASK | RWA_MASK)) /* * return data direction, READ or WRITE */ #define bio_data_dir(bio) ((bio)->bi_rw & 1) extern void check_disk_size_change(struct gendisk *disk, struct block_device *bdev); extern int revalidate_disk(struct gendisk *); extern int check_disk_change(struct block_device *); extern int __invalidate_device(struct block_device *, bool); extern int invalidate_partition(struct gendisk *, int); #endif unsigned long invalidate_mapping_pages(struct address_space *mapping, pgoff_t start, pgoff_t end); static inline void invalidate_remote_inode(struct inode *inode) { if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) invalidate_mapping_pages(inode->i_mapping, 0, -1); } extern int invalidate_inode_pages2(struct address_space *mapping); extern int invalidate_inode_pages2_range(struct address_space *mapping, pgoff_t start, pgoff_t end); extern int write_inode_now(struct inode *, int); extern int filemap_fdatawrite(struct address_space *); extern int filemap_flush(struct address_space *); extern int filemap_fdatawait(struct address_space *); extern int filemap_fdatawait_range(struct address_space *, loff_t lstart, loff_t lend); extern int filemap_write_and_wait(struct address_space *mapping); extern int filemap_write_and_wait_range(struct address_space *mapping, loff_t lstart, loff_t lend); extern int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start, loff_t end, int sync_mode); extern int filemap_fdatawrite_range(struct address_space *mapping, loff_t start, loff_t end); extern int vfs_fsync_range(struct file *file, loff_t start, loff_t end, int datasync); extern int vfs_fsync(struct file *file, int datasync); static inline int generic_write_sync(struct file *file, loff_t pos, loff_t count) { if (!(file->f_flags & O_DSYNC) && !IS_SYNC(file->f_mapping->host)) return 0; return vfs_fsync_range(file, pos, pos + count - 1, (file->f_flags & __O_SYNC) ? 0 : 1); } extern void emergency_sync(void); extern void emergency_remount(void); #ifdef CONFIG_BLOCK extern sector_t bmap(struct inode *, sector_t); #endif extern int notify_change(struct dentry *, struct iattr *, struct inode **); extern int inode_permission(struct inode *, int); extern int __inode_permission(struct inode *, int); extern int generic_permission(struct inode *, int); extern int __check_sticky(struct inode *dir, struct inode *inode); static inline bool execute_ok(struct inode *inode) { return (inode->i_mode & S_IXUGO) || S_ISDIR(inode->i_mode); } static inline void file_start_write(struct file *file) { if (!S_ISREG(file_inode(file)->i_mode)) return; __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, true); } static inline bool file_start_write_trylock(struct file *file) { if (!S_ISREG(file_inode(file)->i_mode)) return true; return __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, false); } static inline void file_end_write(struct file *file) { if (!S_ISREG(file_inode(file)->i_mode)) return; __sb_end_write(file_inode(file)->i_sb, SB_FREEZE_WRITE); } /* * get_write_access() gets write permission for a file. * put_write_access() releases this write permission. * This is used for regular files. * We cannot support write (and maybe mmap read-write shared) accesses and * MAP_DENYWRITE mmappings simultaneously. The i_writecount field of an inode * can have the following values: * 0: no writers, no VM_DENYWRITE mappings * < 0: (-i_writecount) vm_area_structs with VM_DENYWRITE set exist * > 0: (i_writecount) users are writing to the file. * * Normally we operate on that counter with atomic_{inc,dec} and it's safe * except for the cases where we don't hold i_writecount yet. Then we need to * use {get,deny}_write_access() - these functions check the sign and refuse * to do the change if sign is wrong. */ static inline int get_write_access(struct inode *inode) { return atomic_inc_unless_negative(&inode->i_writecount) ? 0 : -ETXTBSY; } static inline int deny_write_access(struct file *file) { struct inode *inode = file_inode(file); return atomic_dec_unless_positive(&inode->i_writecount) ? 0 : -ETXTBSY; } static inline void put_write_access(struct inode * inode) { atomic_dec(&inode->i_writecount); } static inline void allow_write_access(struct file *file) { if (file) atomic_inc(&file_inode(file)->i_writecount); } static inline bool inode_is_open_for_write(const struct inode *inode) { return atomic_read(&inode->i_writecount) > 0; } #ifdef CONFIG_IMA static inline void i_readcount_dec(struct inode *inode) { BUG_ON(!atomic_read(&inode->i_readcount)); atomic_dec(&inode->i_readcount); } static inline void i_readcount_inc(struct inode *inode) { atomic_inc(&inode->i_readcount); } #else static inline void i_readcount_dec(struct inode *inode) { return; } static inline void i_readcount_inc(struct inode *inode) { return; } #endif extern int do_pipe_flags(int *, int); extern int kernel_read(struct file *, loff_t, char *, unsigned long); extern ssize_t kernel_write(struct file *, const char *, size_t, loff_t); extern ssize_t __kernel_write(struct file *, const char *, size_t, loff_t *); extern struct file * open_exec(const char *); /* fs/dcache.c -- generic fs support functions */ extern int is_subdir(struct dentry *, struct dentry *); extern int path_is_under(struct path *, struct path *); #include <linux/err.h> /* needed for stackable file system support */ extern loff_t default_llseek(struct file *file, loff_t offset, int whence); extern loff_t vfs_llseek(struct file *file, loff_t offset, int whence); extern int inode_init_always(struct super_block *, struct inode *); extern void inode_init_once(struct inode *); extern void address_space_init_once(struct address_space *mapping); extern struct inode * igrab(struct inode *); extern ino_t iunique(struct super_block *, ino_t); extern int inode_needs_sync(struct inode *inode); extern int generic_delete_inode(struct inode *inode); static inline int generic_drop_inode(struct inode *inode) { return !inode->i_nlink || inode_unhashed(inode); } extern struct inode *ilookup5_nowait(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data); extern struct inode *ilookup5(struct super_block *sb, unsigned long hashval, int (*test)(struct inode *, void *), void *data); extern struct inode *ilookup(struct super_block *sb, unsigned long ino); extern struct inode * iget5_locked(struct super_block *, unsigned long, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *); extern struct inode * iget_locked(struct super_block *, unsigned long); extern int insert_inode_locked4(struct inode *, unsigned long, int (*test)(struct inode *, void *), void *); extern int insert_inode_locked(struct inode *); #ifdef CONFIG_DEBUG_LOCK_ALLOC extern void lockdep_annotate_inode_mutex_key(struct inode *inode); #else static inline void lockdep_annotate_inode_mutex_key(struct inode *inode) { }; #endif extern void unlock_new_inode(struct inode *); extern unsigned int get_next_ino(void); extern void __iget(struct inode * inode); extern void iget_failed(struct inode *); extern void clear_inode(struct inode *); extern void __destroy_inode(struct inode *); extern struct inode *new_inode_pseudo(struct super_block *sb); extern struct inode *new_inode(struct super_block *sb); extern void free_inode_nonrcu(struct inode *inode); extern int should_remove_suid(struct dentry *); extern int file_remove_suid(struct file *); extern void __insert_inode_hash(struct inode *, unsigned long hashval); static inline void insert_inode_hash(struct inode *inode) { __insert_inode_hash(inode, inode->i_ino); } extern void __remove_inode_hash(struct inode *); static inline void remove_inode_hash(struct inode *inode) { if (!inode_unhashed(inode)) __remove_inode_hash(inode); } extern void inode_sb_list_add(struct inode *inode); #ifdef CONFIG_BLOCK extern void submit_bio(int, struct bio *); extern int bdev_read_only(struct block_device *); #endif extern int set_blocksize(struct block_device *, int); extern int sb_set_blocksize(struct super_block *, int); extern int sb_min_blocksize(struct super_block *, int); extern int generic_file_mmap(struct file *, struct vm_area_struct *); extern int generic_file_readonly_mmap(struct file *, struct vm_area_struct *); extern int generic_file_remap_pages(struct vm_area_struct *, unsigned long addr, unsigned long size, pgoff_t pgoff); int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk); extern ssize_t generic_file_read_iter(struct kiocb *, struct iov_iter *); extern ssize_t __generic_file_write_iter(struct kiocb *, struct iov_iter *); extern ssize_t generic_file_write_iter(struct kiocb *, struct iov_iter *); extern ssize_t generic_file_direct_write(struct kiocb *, struct iov_iter *, loff_t); extern ssize_t generic_perform_write(struct file *, struct iov_iter *, loff_t); extern ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos); extern ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos); extern ssize_t new_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos); extern ssize_t new_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos); /* fs/block_dev.c */ extern ssize_t blkdev_read_iter(struct kiocb *iocb, struct iov_iter *to); extern ssize_t blkdev_write_iter(struct kiocb *iocb, struct iov_iter *from); extern int blkdev_fsync(struct file *filp, loff_t start, loff_t end, int datasync); extern void block_sync_page(struct page *page); /* fs/splice.c */ extern ssize_t generic_file_splice_read(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); extern ssize_t default_file_splice_read(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); extern ssize_t iter_file_splice_write(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); extern ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe, struct file *out, loff_t *, size_t len, unsigned int flags); extern long do_splice_direct(struct file *in, loff_t *ppos, struct file *out, loff_t *opos, size_t len, unsigned int flags); extern void file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping); extern loff_t noop_llseek(struct file *file, loff_t offset, int whence); extern loff_t no_llseek(struct file *file, loff_t offset, int whence); extern loff_t vfs_setpos(struct file *file, loff_t offset, loff_t maxsize); extern loff_t generic_file_llseek(struct file *file, loff_t offset, int whence); extern loff_t generic_file_llseek_size(struct file *file, loff_t offset, int whence, loff_t maxsize, loff_t eof); extern loff_t fixed_size_llseek(struct file *file, loff_t offset, int whence, loff_t size); extern int generic_file_open(struct inode * inode, struct file * filp); extern int nonseekable_open(struct inode * inode, struct file * filp); #ifdef CONFIG_FS_XIP extern ssize_t xip_file_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos); extern int xip_file_mmap(struct file * file, struct vm_area_struct * vma); extern ssize_t xip_file_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos); extern int xip_truncate_page(struct address_space *mapping, loff_t from); #else static inline int xip_truncate_page(struct address_space *mapping, loff_t from) { return 0; } #endif #ifdef CONFIG_BLOCK typedef void (dio_submit_t)(int rw, struct bio *bio, struct inode *inode, loff_t file_offset); enum { /* need locking between buffered and direct access */ DIO_LOCKING = 0x01, /* filesystem does not support filling holes */ DIO_SKIP_HOLES = 0x02, /* filesystem can handle aio writes beyond i_size */ DIO_ASYNC_EXTEND = 0x04, }; void dio_end_io(struct bio *bio, int error); ssize_t __blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode, struct block_device *bdev, struct iov_iter *iter, loff_t offset, get_block_t get_block, dio_iodone_t end_io, dio_submit_t submit_io, int flags); static inline ssize_t blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode, struct iov_iter *iter, loff_t offset, get_block_t get_block) { return __blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iter, offset, get_block, NULL, NULL, DIO_LOCKING | DIO_SKIP_HOLES); } #endif void inode_dio_wait(struct inode *inode); void inode_dio_done(struct inode *inode); extern void inode_set_flags(struct inode *inode, unsigned int flags, unsigned int mask); extern const struct file_operations generic_ro_fops; #define special_file(m) (S_ISCHR(m)||S_ISBLK(m)||S_ISFIFO(m)||S_ISSOCK(m)) extern int readlink_copy(char __user *, int, const char *); extern int page_readlink(struct dentry *, char __user *, int); extern void *page_follow_link_light(struct dentry *, struct nameidata *); extern void page_put_link(struct dentry *, struct nameidata *, void *); extern int __page_symlink(struct inode *inode, const char *symname, int len, int nofs); extern int page_symlink(struct inode *inode, const char *symname, int len); extern const struct inode_operations page_symlink_inode_operations; extern void kfree_put_link(struct dentry *, struct nameidata *, void *); extern int generic_readlink(struct dentry *, char __user *, int); extern void generic_fillattr(struct inode *, struct kstat *); int vfs_getattr_nosec(struct path *path, struct kstat *stat); extern int vfs_getattr(struct path *, struct kstat *); void __inode_add_bytes(struct inode *inode, loff_t bytes); void inode_add_bytes(struct inode *inode, loff_t bytes); void __inode_sub_bytes(struct inode *inode, loff_t bytes); void inode_sub_bytes(struct inode *inode, loff_t bytes); loff_t inode_get_bytes(struct inode *inode); void inode_set_bytes(struct inode *inode, loff_t bytes); extern int vfs_readdir(struct file *, filldir_t, void *); extern int iterate_dir(struct file *, struct dir_context *); extern int vfs_stat(const char __user *, struct kstat *); extern int vfs_lstat(const char __user *, struct kstat *); extern int vfs_fstat(unsigned int, struct kstat *); extern int vfs_fstatat(int , const char __user *, struct kstat *, int); extern int do_vfs_ioctl(struct file *filp, unsigned int fd, unsigned int cmd, unsigned long arg); extern int __generic_block_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, loff_t start, loff_t len, get_block_t *get_block); extern int generic_block_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, u64 start, u64 len, get_block_t *get_block); extern void get_filesystem(struct file_system_type *fs); extern void put_filesystem(struct file_system_type *fs); extern struct file_system_type *get_fs_type(const char *name); extern struct super_block *get_super(struct block_device *); extern struct super_block *get_super_thawed(struct block_device *); extern struct super_block *get_active_super(struct block_device *bdev); extern void drop_super(struct super_block *sb); extern void iterate_supers(void (*)(struct super_block *, void *), void *); extern void iterate_supers_type(struct file_system_type *, void (*)(struct super_block *, void *), void *); extern int dcache_dir_open(struct inode *, struct file *); extern int dcache_dir_close(struct inode *, struct file *); extern loff_t dcache_dir_lseek(struct file *, loff_t, int); extern int dcache_readdir(struct file *, struct dir_context *); extern int simple_setattr(struct dentry *, struct iattr *); extern int simple_getattr(struct vfsmount *, struct dentry *, struct kstat *); extern int simple_statfs(struct dentry *, struct kstatfs *); extern int simple_open(struct inode *inode, struct file *file); extern int simple_link(struct dentry *, struct inode *, struct dentry *); extern int simple_unlink(struct inode *, struct dentry *); extern int simple_rmdir(struct inode *, struct dentry *); extern int simple_rename(struct inode *, struct dentry *, struct inode *, struct dentry *); extern int noop_fsync(struct file *, loff_t, loff_t, int); extern int simple_empty(struct dentry *); extern int simple_readpage(struct file *file, struct page *page); extern int simple_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata); extern int simple_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata); extern int always_delete_dentry(const struct dentry *); extern struct inode *alloc_anon_inode(struct super_block *); extern int simple_nosetlease(struct file *, long, struct file_lock **, void **); extern const struct dentry_operations simple_dentry_operations; extern struct dentry *simple_lookup(struct inode *, struct dentry *, unsigned int flags); extern ssize_t generic_read_dir(struct file *, char __user *, size_t, loff_t *); extern const struct file_operations simple_dir_operations; extern const struct inode_operations simple_dir_inode_operations; struct tree_descr { char *name; const struct file_operations *ops; int mode; }; struct dentry *d_alloc_name(struct dentry *, const char *); extern int simple_fill_super(struct super_block *, unsigned long, struct tree_descr *); extern int simple_pin_fs(struct file_system_type *, struct vfsmount **mount, int *count); extern void simple_release_fs(struct vfsmount **mount, int *count); extern ssize_t simple_read_from_buffer(void __user *to, size_t count, loff_t *ppos, const void *from, size_t available); extern ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos, const void __user *from, size_t count); extern int __generic_file_fsync(struct file *, loff_t, loff_t, int); extern int generic_file_fsync(struct file *, loff_t, loff_t, int); extern int generic_check_addressable(unsigned, u64); #ifdef CONFIG_MIGRATION extern int buffer_migrate_page(struct address_space *, struct page *, struct page *, enum migrate_mode); #else #define buffer_migrate_page NULL #endif extern int inode_change_ok(const struct inode *, struct iattr *); extern int inode_newsize_ok(const struct inode *, loff_t offset); extern void setattr_copy(struct inode *inode, const struct iattr *attr); extern int file_update_time(struct file *file); extern int generic_show_options(struct seq_file *m, struct dentry *root); extern void save_mount_options(struct super_block *sb, char *options); extern void replace_mount_options(struct super_block *sb, char *options); static inline ino_t parent_ino(struct dentry *dentry) { ino_t res; /* * Don't strictly need d_lock here? If the parent ino could change * then surely we'd have a deeper race in the caller? */ spin_lock(&dentry->d_lock); res = dentry->d_parent->d_inode->i_ino; spin_unlock(&dentry->d_lock); return res; } /* Transaction based IO helpers */ /* * An argresp is stored in an allocated page and holds the * size of the argument or response, along with its content */ struct simple_transaction_argresp { ssize_t size; char data[0]; }; #define SIMPLE_TRANSACTION_LIMIT (PAGE_SIZE - sizeof(struct simple_transaction_argresp)) char *simple_transaction_get(struct file *file, const char __user *buf, size_t size); ssize_t simple_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos); int simple_transaction_release(struct inode *inode, struct file *file); void simple_transaction_set(struct file *file, size_t n); /* * simple attribute files * * These attributes behave similar to those in sysfs: * * Writing to an attribute immediately sets a value, an open file can be * written to multiple times. * * Reading from an attribute creates a buffer from the value that might get * read with multiple read calls. When the attribute has been read * completely, no further read calls are possible until the file is opened * again. * * All attributes contain a text representation of a numeric value * that are accessed with the get() and set() functions. */ #define DEFINE_SIMPLE_ATTRIBUTE(__fops, __get, __set, __fmt) \ static int __fops ## _open(struct inode *inode, struct file *file) \ { \ __simple_attr_check_format(__fmt, 0ull); \ return simple_attr_open(inode, file, __get, __set, __fmt); \ } \ static const struct file_operations __fops = { \ .owner = THIS_MODULE, \ .open = __fops ## _open, \ .release = simple_attr_release, \ .read = simple_attr_read, \ .write = simple_attr_write, \ .llseek = generic_file_llseek, \ } static inline __printf(1, 2) void __simple_attr_check_format(const char *fmt, ...) { /* don't do anything, just let the compiler check the arguments; */ } int simple_attr_open(struct inode *inode, struct file *file, int (*get)(void *, u64 *), int (*set)(void *, u64), const char *fmt); int simple_attr_release(struct inode *inode, struct file *file); ssize_t simple_attr_read(struct file *file, char __user *buf, size_t len, loff_t *ppos); ssize_t simple_attr_write(struct file *file, const char __user *buf, size_t len, loff_t *ppos); struct ctl_table; int proc_nr_files(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos); int proc_nr_dentry(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos); int proc_nr_inodes(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos); int __init get_filesystem_list(char *buf); #define __FMODE_EXEC ((__force int) FMODE_EXEC) #define __FMODE_NONOTIFY ((__force int) FMODE_NONOTIFY) #define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE]) #define OPEN_FMODE(flag) ((__force fmode_t)(((flag + 1) & O_ACCMODE) | \ (flag & __FMODE_NONOTIFY))) static inline int is_sxid(umode_t mode) { return (mode & S_ISUID) || ((mode & S_ISGID) && (mode & S_IXGRP)); } static inline int check_sticky(struct inode *dir, struct inode *inode) { if (!(dir->i_mode & S_ISVTX)) return 0; return __check_sticky(dir, inode); } static inline void inode_has_no_xattr(struct inode *inode) { if (!is_sxid(inode->i_mode) && (inode->i_sb->s_flags & MS_NOSEC)) inode->i_flags |= S_NOSEC; } static inline bool dir_emit(struct dir_context *ctx, const char *name, int namelen, u64 ino, unsigned type) { return ctx->actor(ctx, name, namelen, ctx->pos, ino, type) == 0; } static inline bool dir_emit_dot(struct file *file, struct dir_context *ctx) { return ctx->actor(ctx, ".", 1, ctx->pos, file->f_path.dentry->d_inode->i_ino, DT_DIR) == 0; } static inline bool dir_emit_dotdot(struct file *file, struct dir_context *ctx) { return ctx->actor(ctx, "..", 2, ctx->pos, parent_ino(file->f_path.dentry), DT_DIR) == 0; } static inline bool dir_emit_dots(struct file *file, struct dir_context *ctx) { if (ctx->pos == 0) { if (!dir_emit_dot(file, ctx)) return false; ctx->pos = 1; } if (ctx->pos == 1) { if (!dir_emit_dotdot(file, ctx)) return false; ctx->pos = 2; } return true; } static inline bool dir_relax(struct inode *inode) { mutex_unlock(&inode->i_mutex); mutex_lock(&inode->i_mutex); return !IS_DEADDIR(inode); } #endif /* _LINUX_FS_H */
alianmohammad/linux-kernel-3.18-hacks
include/linux/fs.h
C
gpl-2.0
95,809
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <[email protected]> * Mark Evans, <[email protected]> * Corey Minyard <[email protected]> * Florian La Roche, <[email protected]> * Charles Hedrick, <[email protected]> * Linus Torvalds, <[email protected]> * Alan Cox, <[email protected]> * Matthew Dillon, <[email protected]> * Arnt Gulbrandsen, <[email protected]> * Jorge Cwik, <[email protected]> * * Fixes: * Alan Cox : Numerous verify_area() calls * Alan Cox : Set the ACK bit on a reset * Alan Cox : Stopped it crashing if it closed while * sk->inuse=1 and was trying to connect * (tcp_err()). * Alan Cox : All icmp error handling was broken * pointers passed where wrong and the * socket was looked up backwards. Nobody * tested any icmp error code obviously. * Alan Cox : tcp_err() now handled properly. It * wakes people on errors. poll * behaves and the icmp error race * has gone by moving it into sock.c * Alan Cox : tcp_send_reset() fixed to work for * everything not just packets for * unknown sockets. * Alan Cox : tcp option processing. * Alan Cox : Reset tweaked (still not 100%) [Had * syn rule wrong] * Herp Rosmanith : More reset fixes * Alan Cox : No longer acks invalid rst frames. * Acking any kind of RST is right out. * Alan Cox : Sets an ignore me flag on an rst * receive otherwise odd bits of prattle * escape still * Alan Cox : Fixed another acking RST frame bug. * Should stop LAN workplace lockups. * Alan Cox : Some tidyups using the new skb list * facilities * Alan Cox : sk->keepopen now seems to work * Alan Cox : Pulls options out correctly on accepts * Alan Cox : Fixed assorted sk->rqueue->next errors * Alan Cox : PSH doesn't end a TCP read. Switched a * bit to skb ops. * Alan Cox : Tidied tcp_data to avoid a potential * nasty. * Alan Cox : Added some better commenting, as the * tcp is hard to follow * Alan Cox : Removed incorrect check for 20 * psh * Michael O'Reilly : ack < copied bug fix. * Johannes Stille : Misc tcp fixes (not all in yet). * Alan Cox : FIN with no memory -> CRASH * Alan Cox : Added socket option proto entries. * Also added awareness of them to accept. * Alan Cox : Added TCP options (SOL_TCP) * Alan Cox : Switched wakeup calls to callbacks, * so the kernel can layer network * sockets. * Alan Cox : Use ip_tos/ip_ttl settings. * Alan Cox : Handle FIN (more) properly (we hope). * Alan Cox : RST frames sent on unsynchronised * state ack error. * Alan Cox : Put in missing check for SYN bit. * Alan Cox : Added tcp_select_window() aka NET2E * window non shrink trick. * Alan Cox : Added a couple of small NET2E timer * fixes * Charles Hedrick : TCP fixes * Toomas Tamm : TCP window fixes * Alan Cox : Small URG fix to rlogin ^C ack fight * Charles Hedrick : Rewrote most of it to actually work * Linus : Rewrote tcp_read() and URG handling * completely * Gerhard Koerting: Fixed some missing timer handling * Matthew Dillon : Reworked TCP machine states as per RFC * Gerhard Koerting: PC/TCP workarounds * Adam Caldwell : Assorted timer/timing errors * Matthew Dillon : Fixed another RST bug * Alan Cox : Move to kernel side addressing changes. * Alan Cox : Beginning work on TCP fastpathing * (not yet usable) * Arnt Gulbrandsen: Turbocharged tcp_check() routine. * Alan Cox : TCP fast path debugging * Alan Cox : Window clamping * Michael Riepe : Bug in tcp_check() * Matt Dillon : More TCP improvements and RST bug fixes * Matt Dillon : Yet more small nasties remove from the * TCP code (Be very nice to this man if * tcp finally works 100%) 8) * Alan Cox : BSD accept semantics. * Alan Cox : Reset on closedown bug. * Peter De Schrijver : ENOTCONN check missing in tcp_sendto(). * Michael Pall : Handle poll() after URG properly in * all cases. * Michael Pall : Undo the last fix in tcp_read_urg() * (multi URG PUSH broke rlogin). * Michael Pall : Fix the multi URG PUSH problem in * tcp_readable(), poll() after URG * works now. * Michael Pall : recv(...,MSG_OOB) never blocks in the * BSD api. * Alan Cox : Changed the semantics of sk->socket to * fix a race and a signal problem with * accept() and async I/O. * Alan Cox : Relaxed the rules on tcp_sendto(). * Yury Shevchuk : Really fixed accept() blocking problem. * Craig I. Hagan : Allow for BSD compatible TIME_WAIT for * clients/servers which listen in on * fixed ports. * Alan Cox : Cleaned the above up and shrank it to * a sensible code size. * Alan Cox : Self connect lockup fix. * Alan Cox : No connect to multicast. * Ross Biro : Close unaccepted children on master * socket close. * Alan Cox : Reset tracing code. * Alan Cox : Spurious resets on shutdown. * Alan Cox : Giant 15 minute/60 second timer error * Alan Cox : Small whoops in polling before an * accept. * Alan Cox : Kept the state trace facility since * it's handy for debugging. * Alan Cox : More reset handler fixes. * Alan Cox : Started rewriting the code based on * the RFC's for other useful protocol * references see: Comer, KA9Q NOS, and * for a reference on the difference * between specifications and how BSD * works see the 4.4lite source. * A.N.Kuznetsov : Don't time wait on completion of tidy * close. * Linus Torvalds : Fin/Shutdown & copied_seq changes. * Linus Torvalds : Fixed BSD port reuse to work first syn * Alan Cox : Reimplemented timers as per the RFC * and using multiple timers for sanity. * Alan Cox : Small bug fixes, and a lot of new * comments. * Alan Cox : Fixed dual reader crash by locking * the buffers (much like datagram.c) * Alan Cox : Fixed stuck sockets in probe. A probe * now gets fed up of retrying without * (even a no space) answer. * Alan Cox : Extracted closing code better * Alan Cox : Fixed the closing state machine to * resemble the RFC. * Alan Cox : More 'per spec' fixes. * Jorge Cwik : Even faster checksumming. * Alan Cox : tcp_data() doesn't ack illegal PSH * only frames. At least one pc tcp stack * generates them. * Alan Cox : Cache last socket. * Alan Cox : Per route irtt. * Matt Day : poll()->select() match BSD precisely on error * Alan Cox : New buffers * Marc Tamsky : Various sk->prot->retransmits and * sk->retransmits misupdating fixed. * Fixed tcp_write_timeout: stuck close, * and TCP syn retries gets used now. * Mark Yarvis : In tcp_read_wakeup(), don't send an * ack if state is TCP_CLOSED. * Alan Cox : Look up device on a retransmit - routes may * change. Doesn't yet cope with MSS shrink right * but it's a start! * Marc Tamsky : Closing in closing fixes. * Mike Shaver : RFC1122 verifications. * Alan Cox : rcv_saddr errors. * Alan Cox : Block double connect(). * Alan Cox : Small hooks for enSKIP. * Alexey Kuznetsov: Path MTU discovery. * Alan Cox : Support soft errors. * Alan Cox : Fix MTU discovery pathological case * when the remote claims no mtu! * Marc Tamsky : TCP_CLOSE fix. * Colin (G3TNE) : Send a reset on syn ack replies in * window but wrong (fixes NT lpd problems) * Pedro Roque : Better TCP window handling, delayed ack. * Joerg Reuter : No modification of locked buffers in * tcp_do_retransmit() * Eric Schenk : Changed receiver side silly window * avoidance algorithm to BSD style * algorithm. This doubles throughput * against machines running Solaris, * and seems to result in general * improvement. * Stefan Magdalinski : adjusted tcp_readable() to fix FIONREAD * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * Keith Owens : Do proper merging with partial SKB's in * tcp_do_sendmsg to avoid burstiness. * Eric Schenk : Fix fast close down bug with * shutdown() followed by close(). * Andi Kleen : Make poll agree with SIGIO * Salvatore Sanfilippo : Support SO_LINGER with linger == 1 and * lingertime == 0 (RFC 793 ABORT Call) * Hirokazu Takahashi : Use copy_from_user() instead of * csum_and_copy_from_user() if possible. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or(at your option) any later version. * * Description of States: * * TCP_SYN_SENT sent a connection request, waiting for ack * * TCP_SYN_RECV received a connection request, sent ack, * waiting for final ack in three-way handshake. * * TCP_ESTABLISHED connection established * * TCP_FIN_WAIT1 our side has shutdown, waiting to complete * transmission of remaining buffered data * * TCP_FIN_WAIT2 all buffered data sent, waiting for remote * to shutdown * * TCP_CLOSING both sides have shutdown but we still have * data we have to finish sending * * TCP_TIME_WAIT timeout to catch resent junk before entering * closed, can only be entered from FIN_WAIT2 * or CLOSING. Required because the other end * may not have gotten our last ACK causing it * to retransmit the data packet (which we ignore) * * TCP_CLOSE_WAIT remote side has shutdown and is waiting for * us to finish writing our data and to shutdown * (we have to close() to move on to LAST_ACK) * * TCP_LAST_ACK out side has shutdown after remote has * shutdown. There may still be data in our * buffer that we have to finish sending * * TCP_CLOSE socket is finished */ #define pr_fmt(fmt) "TCP: " fmt #include <linux/kernel.h> #include <linux/module.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/poll.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/skbuff.h> #include <linux/scatterlist.h> #include <linux/splice.h> #include <linux/net.h> #include <linux/socket.h> #include <linux/random.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/cache.h> #include <linux/err.h> #include <linux/crypto.h> #include <linux/time.h> #include <linux/slab.h> #include <linux/uid_stat.h> #include <net/icmp.h> #include <net/inet_common.h> #include <net/tcp.h> #include <net/xfrm.h> #include <net/ip.h> #include <net/ip6_route.h> #include <net/ipv6.h> #include <net/transp_v6.h> #include <net/netdma.h> #include <net/sock.h> #include <asm/uaccess.h> #include <asm/ioctls.h> int sysctl_tcp_fin_timeout __read_mostly = TCP_FIN_TIMEOUT; int sysctl_tcp_min_tso_segs __read_mostly = 2; struct percpu_counter tcp_orphan_count; EXPORT_SYMBOL_GPL(tcp_orphan_count); int sysctl_tcp_wmem[3] __read_mostly; int sysctl_tcp_rmem[3] __read_mostly; EXPORT_SYMBOL(sysctl_tcp_rmem); EXPORT_SYMBOL(sysctl_tcp_wmem); atomic_long_t tcp_memory_allocated; /* Current allocated memory. */ EXPORT_SYMBOL(tcp_memory_allocated); /* * Current number of TCP sockets. */ struct percpu_counter tcp_sockets_allocated; EXPORT_SYMBOL(tcp_sockets_allocated); /* * TCP splice context */ struct tcp_splice_state { struct pipe_inode_info *pipe; size_t len; unsigned int flags; }; /* * Pressure flag: try to collapse. * Technical note: it is used by multiple contexts non atomically. * All the __sk_mem_schedule() is of this nature: accounting * is strict, actions are advisory and have some latency. */ int tcp_memory_pressure __read_mostly; EXPORT_SYMBOL(tcp_memory_pressure); void tcp_enter_memory_pressure(struct sock *sk) { if (!tcp_memory_pressure) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMEMORYPRESSURES); tcp_memory_pressure = 1; } } EXPORT_SYMBOL(tcp_enter_memory_pressure); /* Convert seconds to retransmits based on initial and max timeout */ static u8 secs_to_retrans(int seconds, int timeout, int rto_max) { u8 res = 0; if (seconds > 0) { int period = timeout; res = 1; while (seconds > period && res < 255) { res++; timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return res; } /* Convert retransmits to seconds based on initial and max timeout */ static int retrans_to_secs(u8 retrans, int timeout, int rto_max) { int period = 0; if (retrans > 0) { period = timeout; while (--retrans) { timeout <<= 1; if (timeout > rto_max) timeout = rto_max; period += timeout; } } return period; } /* Address-family independent initialization for a tcp_sock. * * NOTE: A lot of things set to zero explicitly by call to * sk_alloc() so need not be done here. */ void tcp_init_sock(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); skb_queue_head_init(&tp->out_of_order_queue); tcp_init_xmit_timers(sk); tcp_prequeue_init(tp); INIT_LIST_HEAD(&tp->tsq_node); icsk->icsk_rto = TCP_TIMEOUT_INIT; tp->mdev = TCP_TIMEOUT_INIT; /* So many TCP implementations out there (incorrectly) count the * initial SYN frame in their delayed-ACK and congestion control * algorithms that we must have the following bandaid to talk * efficiently to them. -DaveM */ tp->snd_cwnd = TCP_INIT_CWND; /* See draft-stevens-tcpca-spec-01 for discussion of the * initialization of these values. */ tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_clamp = ~0; tp->mss_cache = TCP_MSS_DEFAULT; tp->reordering = sysctl_tcp_reordering; tcp_enable_early_retrans(tp); icsk->icsk_ca_ops = &tcp_init_congestion_ops; tp->tsoffset = 0; sk->sk_state = TCP_CLOSE; sk->sk_write_space = sk_stream_write_space; sock_set_flag(sk, SOCK_USE_WRITE_QUEUE); icsk->icsk_sync_mss = tcp_sync_mss; /* Presumed zeroed, in order of appearance: * cookie_in_always, cookie_out_never, * s_data_constant, s_data_in, s_data_out */ sk->sk_sndbuf = sysctl_tcp_wmem[1]; sk->sk_rcvbuf = sysctl_tcp_rmem[1]; local_bh_disable(); sock_update_memcg(sk); sk_sockets_allocated_inc(sk); local_bh_enable(); } EXPORT_SYMBOL(tcp_init_sock); /* * Wait for a TCP event. * * Note that we don't need to lock the socket, as the upper poll layers * take care of normal races (between the test and the event) and we don't * go look at any of the socket buffers directly. */ unsigned int tcp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask; struct sock *sk = sock->sk; const struct tcp_sock *tp = tcp_sk(sk); sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == TCP_LISTEN) return inet_csk_listen_poll(sk); /* Socket is not locked. We are protected from async events * by poll logic and correct handling of state changes * made by other threads is impossible in any case. */ mask = 0; /* * POLLHUP is certainly not done right. But poll() doesn't * have a notion of HUP in just one direction, and for a * socket the read side is more interesting. * * Some poll() documentation says that POLLHUP is incompatible * with the POLLOUT/POLLWR flags, so somebody should check this * all. But careful, it tends to be safer to return too many * bits than too few, and you can easily break real applications * if you don't tell them that something has hung up! * * Check-me. * * Check number 1. POLLHUP is _UNMASKABLE_ event (see UNIX98 and * our fs/select.c). It means that after we received EOF, * poll always returns immediately, making impossible poll() on write() * in state CLOSE_WAIT. One solution is evident --- to set POLLHUP * if and only if shutdown has been made in both directions. * Actually, it is interesting to look how Solaris and DUX * solve this dilemma. I would prefer, if POLLHUP were maskable, * then we could set it on SND_SHUTDOWN. BTW examples given * in Stevens' books assume exactly this behaviour, it explains * why POLLHUP is incompatible with POLLOUT. --ANK * * NOTE. Check for TCP_CLOSE is added. The goal is to prevent * blocking on fresh not-connected or disconnected socket. --ANK */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLIN | POLLRDNORM | POLLRDHUP; /* Connected or passive Fast Open socket? */ if (sk->sk_state != TCP_SYN_SENT && (sk->sk_state != TCP_SYN_RECV || tp->fastopen_rsk != NULL)) { int target = sock_rcvlowat(sk, 0, INT_MAX); if (tp->urg_seq == tp->copied_seq && !sock_flag(sk, SOCK_URGINLINE) && tp->urg_data) target++; /* Potential race condition. If read of tp below will * escape above sk->sk_state, we can be illegally awaken * in SYN_* states. */ if (tp->rcv_nxt - tp->copied_seq >= target) mask |= POLLIN | POLLRDNORM; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) { mask |= POLLOUT | POLLWRNORM; } else { /* send SIGIO later */ set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); /* Race breaker. If space is freed after * wspace test but before the flags are set, * IO signal will be lost. */ if (sk_stream_wspace(sk) >= sk_stream_min_wspace(sk)) mask |= POLLOUT | POLLWRNORM; } } else mask |= POLLOUT | POLLWRNORM; if (tp->urg_data & TCP_URG_VALID) mask |= POLLPRI; } /* This barrier is coupled with smp_wmb() in tcp_reset() */ smp_rmb(); if (sk->sk_err) mask |= POLLERR; return mask; } EXPORT_SYMBOL(tcp_poll); int tcp_ioctl(struct sock *sk, int cmd, unsigned long arg) { struct tcp_sock *tp = tcp_sk(sk); int answ; bool slow; switch (cmd) { case SIOCINQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; slow = lock_sock_fast(sk); if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data || before(tp->urg_seq, tp->copied_seq) || !before(tp->urg_seq, tp->rcv_nxt)) { answ = tp->rcv_nxt - tp->copied_seq; /* Subtract 1, if FIN was received */ if (answ && sock_flag(sk, SOCK_DONE)) answ--; } else answ = tp->urg_seq - tp->copied_seq; unlock_sock_fast(sk, slow); break; case SIOCATMARK: answ = tp->urg_data && tp->urg_seq == tp->copied_seq; break; case SIOCOUTQ: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_una; break; case SIOCOUTQNSD: if (sk->sk_state == TCP_LISTEN) return -EINVAL; if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) answ = 0; else answ = tp->write_seq - tp->snd_nxt; break; /* MTK_NET_CHANGES */ case SIOCKILLSOCK: { struct uid_err uid_e; if (copy_from_user(&uid_e, (char __user *)arg, sizeof(uid_e))) return -EFAULT; printk(KERN_WARNING "SIOCKILLSOCK uid = %d , err = %d", uid_e.appuid, uid_e.errNum); if (uid_e.errNum == 0) { // handle BR release problem tcp_v4_handle_retrans_time_by_uid(uid_e); } else { tcp_v4_reset_connections_by_uid(uid_e); } return 0; } default: return -ENOIOCTLCMD; } return put_user(answ, (int __user *)arg); } EXPORT_SYMBOL(tcp_ioctl); static inline void tcp_mark_push(struct tcp_sock *tp, struct sk_buff *skb) { TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; tp->pushed_seq = tp->write_seq; } static inline bool forced_push(const struct tcp_sock *tp) { return after(tp->write_seq, tp->pushed_seq + (tp->max_window >> 1)); } static inline void skb_entail(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); skb->csum = 0; tcb->seq = tcb->end_seq = tp->write_seq; tcb->tcp_flags = TCPHDR_ACK; tcb->sacked = 0; skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); if (tp->nonagle & TCP_NAGLE_PUSH) tp->nonagle &= ~TCP_NAGLE_PUSH; } static inline void tcp_mark_urg(struct tcp_sock *tp, int flags) { if (flags & MSG_OOB) tp->snd_up = tp->write_seq; } static inline void tcp_push(struct sock *sk, int flags, int mss_now, int nonagle) { if (tcp_send_head(sk)) { struct tcp_sock *tp = tcp_sk(sk); if (!(flags & MSG_MORE) || forced_push(tp)) tcp_mark_push(tp, tcp_write_queue_tail(sk)); tcp_mark_urg(tp, flags); __tcp_push_pending_frames(sk, mss_now, (flags & MSG_MORE) ? TCP_NAGLE_CORK : nonagle); } } static int tcp_splice_data_recv(read_descriptor_t *rd_desc, struct sk_buff *skb, unsigned int offset, size_t len) { struct tcp_splice_state *tss = rd_desc->arg.data; int ret; ret = skb_splice_bits(skb, offset, tss->pipe, min(rd_desc->count, len), tss->flags); if (ret > 0) rd_desc->count -= ret; return ret; } static int __tcp_splice_read(struct sock *sk, struct tcp_splice_state *tss) { /* Store TCP splice context information in read_descriptor_t. */ read_descriptor_t rd_desc = { .arg.data = tss, .count = tss->len, }; return tcp_read_sock(sk, &rd_desc, tcp_splice_data_recv); } /** * tcp_splice_read - splice data from TCP socket to a pipe * @sock: socket to splice from * @ppos: position (not valid) * @pipe: pipe to splice to * @len: number of bytes to splice * @flags: splice modifier flags * * Description: * Will read pages from given socket and fill them into a pipe. * **/ ssize_t tcp_splice_read(struct socket *sock, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct sock *sk = sock->sk; struct tcp_splice_state tss = { .pipe = pipe, .len = len, .flags = flags, }; long timeo; ssize_t spliced; int ret; sock_rps_record_flow(sk); /* * We can't seek on a socket input */ if (unlikely(*ppos)) return -ESPIPE; ret = spliced = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, sock->file->f_flags & O_NONBLOCK); while (tss.len) { ret = __tcp_splice_read(sk, &tss); if (ret < 0) break; else if (!ret) { if (spliced) break; if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { ret = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { /* * This occurs when user tries to read * from never connected socket. */ if (!sock_flag(sk, SOCK_DONE)) ret = -ENOTCONN; break; } if (!timeo) { ret = -EAGAIN; break; } sk_wait_data(sk, &timeo); if (signal_pending(current)) { ret = sock_intr_errno(timeo); break; } continue; } tss.len -= ret; spliced += ret; if (!timeo) break; release_sock(sk); lock_sock(sk); if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || signal_pending(current)) break; } release_sock(sk); if (spliced) return spliced; return ret; } EXPORT_SYMBOL(tcp_splice_read); struct sk_buff *sk_stream_alloc_skb(struct sock *sk, int size, gfp_t gfp) { struct sk_buff *skb; /* The TCP header must be at least 32-bit aligned. */ size = ALIGN(size, 4); skb = alloc_skb_fclone(size + sk->sk_prot->max_header, gfp); if (skb) { if (sk_wmem_schedule(sk, skb->truesize)) { skb_reserve(skb, sk->sk_prot->max_header); /* * Make sure that we have exactly size bytes * available to the caller, no more, no less. */ skb->reserved_tailroom = skb->end - skb->tail - size; return skb; } __kfree_skb(skb); } else { sk->sk_prot->enter_memory_pressure(sk); sk_stream_moderate_sndbuf(sk); } return NULL; } static unsigned int tcp_xmit_size_goal(struct sock *sk, u32 mss_now, int large_allowed) { struct tcp_sock *tp = tcp_sk(sk); u32 xmit_size_goal, old_size_goal; xmit_size_goal = mss_now; if (large_allowed && sk_can_gso(sk)) { u32 gso_size, hlen; /* Maybe we should/could use sk->sk_prot->max_header here ? */ hlen = inet_csk(sk)->icsk_af_ops->net_header_len + inet_csk(sk)->icsk_ext_hdr_len + tp->tcp_header_len; /* Goal is to send at least one packet per ms, * not one big TSO packet every 100 ms. * This preserves ACK clocking and is consistent * with tcp_tso_should_defer() heuristic. */ gso_size = sk->sk_pacing_rate / (2 * MSEC_PER_SEC); gso_size = max_t(u32, gso_size, sysctl_tcp_min_tso_segs * mss_now); xmit_size_goal = min_t(u32, gso_size, sk->sk_gso_max_size - 1 - hlen); xmit_size_goal = tcp_bound_to_half_wnd(tp, xmit_size_goal); /* We try hard to avoid divides here */ old_size_goal = tp->xmit_size_goal_segs * mss_now; if (likely(old_size_goal <= xmit_size_goal && old_size_goal + mss_now > xmit_size_goal)) { xmit_size_goal = old_size_goal; } else { tp->xmit_size_goal_segs = min_t(u16, xmit_size_goal / mss_now, sk->sk_gso_max_segs); xmit_size_goal = tp->xmit_size_goal_segs * mss_now; } } return max(xmit_size_goal, mss_now); } static int tcp_send_mss(struct sock *sk, int *size_goal, int flags) { int mss_now; mss_now = tcp_current_mss(sk); *size_goal = tcp_xmit_size_goal(sk, mss_now, !(flags & MSG_OOB)); return mss_now; } static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct tcp_sock *tp = tcp_sk(sk); int mss_now, size_goal; int err; ssize_t copied; long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { if ((err = sk_stream_wait_connect(sk, &timeo)) != 0) goto out_err; } clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); mss_now = tcp_send_mss(sk, &size_goal, flags); copied = 0; err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto out_err; while (size > 0) { struct sk_buff *skb = tcp_write_queue_tail(sk); int copy, i; bool can_coalesce; if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0) { new_segment: if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation); if (!skb) goto wait_for_memory; skb_entail(sk, skb); copy = size_goal; } if (copy > size) copy = size; i = skb_shinfo(skb)->nr_frags; can_coalesce = skb_can_coalesce(skb, i, page, offset); if (!can_coalesce && i >= MAX_SKB_FRAGS) { tcp_mark_push(tp, skb); goto new_segment; } if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; if (can_coalesce) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { get_page(page); skb_fill_page_desc(skb, i, page, offset, copy); } skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; skb->len += copy; skb->data_len += copy; skb->truesize += copy; sk->sk_wmem_queued += copy; sk_mem_charge(sk, copy); skb->ip_summed = CHECKSUM_PARTIAL; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; skb_shinfo(skb)->gso_segs = 0; if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; copied += copy; offset += copy; if (!(size -= copy)) goto out; if (skb->len < size_goal || (flags & MSG_OOB)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH); if ((err = sk_stream_wait_memory(sk, &timeo)) != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } out: if (copied && !(flags & MSG_SENDPAGE_NOTLAST)) tcp_push(sk, flags, mss_now, tp->nonagle); return copied; do_error: if (copied) goto out; out_err: return sk_stream_error(sk, flags, err); } int tcp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { ssize_t res; if (!(sk->sk_route_caps & NETIF_F_SG) || !(sk->sk_route_caps & NETIF_F_ALL_CSUM)) return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); lock_sock(sk); res = do_tcp_sendpages(sk, page, offset, size, flags); release_sock(sk); return res; } EXPORT_SYMBOL(tcp_sendpage); static inline int select_size(const struct sock *sk, bool sg) { const struct tcp_sock *tp = tcp_sk(sk); int tmp = tp->mss_cache; if (sg) { if (sk_can_gso(sk)) { /* Small frames wont use a full page: * Payload will immediately follow tcp header. */ tmp = SKB_WITH_OVERHEAD(2048 - MAX_TCP_HEADER); } else { int pgbreak = SKB_MAX_HEAD(MAX_TCP_HEADER); if (tmp >= pgbreak && tmp <= pgbreak + (MAX_SKB_FRAGS - 1) * PAGE_SIZE) tmp = pgbreak; } } return tmp; } void tcp_free_fastopen_req(struct tcp_sock *tp) { if (tp->fastopen_req != NULL) { kfree(tp->fastopen_req); tp->fastopen_req = NULL; } } static int tcp_sendmsg_fastopen(struct sock *sk, struct msghdr *msg, int *copied, size_t size) { struct tcp_sock *tp = tcp_sk(sk); int err, flags; if (!(sysctl_tcp_fastopen & TFO_CLIENT_ENABLE)) return -EOPNOTSUPP; if (tp->fastopen_req != NULL) return -EALREADY; /* Another Fast Open is in progress */ tp->fastopen_req = kzalloc(sizeof(struct tcp_fastopen_request), sk->sk_allocation); if (unlikely(tp->fastopen_req == NULL)) return -ENOBUFS; tp->fastopen_req->data = msg; tp->fastopen_req->size = size; flags = (msg->msg_flags & MSG_DONTWAIT) ? O_NONBLOCK : 0; err = __inet_stream_connect(sk->sk_socket, msg->msg_name, msg->msg_namelen, flags); *copied = tp->fastopen_req->copied; tcp_free_fastopen_req(tp); return err; } int tcp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t size) { struct iovec *iov; struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int iovlen, flags, err, copied = 0; int mss_now = 0, size_goal, copied_syn = 0, offset = 0; bool sg; long timeo; lock_sock(sk); flags = msg->msg_flags; if (flags & MSG_FASTOPEN) { err = tcp_sendmsg_fastopen(sk, msg, &copied_syn, size); if (err == -EINPROGRESS && copied_syn > 0) goto out; else if (err) goto out_err; offset = copied_syn; } timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); /* Wait for a connection to finish. One exception is TCP Fast Open * (passive side) where data is allowed to be sent before a connection * is fully established. */ if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && !tcp_passive_fastopen(sk)) { if ((err = sk_stream_wait_connect(sk, &timeo)) != 0) goto do_error; } if (unlikely(tp->repair)) { if (tp->repair_queue == TCP_RECV_QUEUE) { copied = tcp_send_rcvq(sk, msg, size); goto out_nopush; } err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out_err; /* 'common' sending to sendq */ } /* This should be in poll */ clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); mss_now = tcp_send_mss(sk, &size_goal, flags); /* Ok commence sending. */ iovlen = msg->msg_iovlen; iov = msg->msg_iov; copied = 0; err = -EPIPE; if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) goto out_err; sg = !!(sk->sk_route_caps & NETIF_F_SG); while (--iovlen >= 0) { size_t seglen = iov->iov_len; unsigned char __user *from = iov->iov_base; iov++; if (unlikely(offset > 0)) { /* Skip bytes copied in SYN */ if (offset >= seglen) { offset -= seglen; continue; } seglen -= offset; from += offset; offset = 0; } while (seglen > 0) { int copy = 0; int max = size_goal; skb = tcp_write_queue_tail(sk); if (tcp_send_head(sk)) { if (skb->ip_summed == CHECKSUM_NONE) max = mss_now; copy = max - skb->len; } if (copy <= 0) { new_segment: /* Allocate new segment. If the interface is SG, * allocate skb fitting to single page. */ if (!sk_stream_memory_free(sk)) goto wait_for_sndbuf; skb = sk_stream_alloc_skb(sk, select_size(sk, sg), sk->sk_allocation); if (!skb) goto wait_for_memory; /* * All packets are restored as if they have * already been sent. */ if (tp->repair) TCP_SKB_CB(skb)->when = tcp_time_stamp; /* * Check whether we can use HW checksum. */ if (sk->sk_route_caps & NETIF_F_ALL_CSUM) skb->ip_summed = CHECKSUM_PARTIAL; skb_entail(sk, skb); copy = size_goal; max = size_goal; } /* Try to append data to the end of skb. */ if (copy > seglen) copy = seglen; /* Where to copy to? */ if (skb_availroom(skb) > 0) { /* We have some space in skb head. Superb! */ copy = min_t(int, copy, skb_availroom(skb)); err = skb_add_data_nocache(sk, skb, from, copy); if (err) goto do_fault; } else { bool merge = true; int i = skb_shinfo(skb)->nr_frags; struct page_frag *pfrag = sk_page_frag(sk); if (!sk_page_frag_refill(sk, pfrag)) goto wait_for_memory; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { if (i == MAX_SKB_FRAGS || !sg) { tcp_mark_push(tp, skb); goto new_segment; } merge = false; } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (!sk_wmem_schedule(sk, copy)) goto wait_for_memory; err = skb_copy_to_page_nocache(sk, from, skb, pfrag->page, pfrag->offset, copy); if (err) goto do_error; /* Update the skb. */ if (merge) { skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); } else { skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, copy); get_page(pfrag->page); } pfrag->offset += copy; } if (!copied) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; tp->write_seq += copy; TCP_SKB_CB(skb)->end_seq += copy; skb_shinfo(skb)->gso_segs = 0; from += copy; copied += copy; if ((seglen -= copy) == 0 && iovlen == 0) goto out; if (skb->len < max || (flags & MSG_OOB) || unlikely(tp->repair)) continue; if (forced_push(tp)) { tcp_mark_push(tp, skb); __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); } else if (skb == tcp_send_head(sk)) tcp_push_one(sk, mss_now); continue; wait_for_sndbuf: set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); wait_for_memory: if (copied) tcp_push(sk, flags & ~MSG_MORE, mss_now, TCP_NAGLE_PUSH); if ((err = sk_stream_wait_memory(sk, &timeo)) != 0) goto do_error; mss_now = tcp_send_mss(sk, &size_goal, flags); } } out: if (copied) tcp_push(sk, flags, mss_now, tp->nonagle); out_nopush: release_sock(sk); if (copied + copied_syn) uid_stat_tcp_snd(current_uid(), copied + copied_syn); return copied + copied_syn; do_fault: if (!skb->len) { tcp_unlink_write_queue(skb, sk); /* It is the one place in all of TCP, except connection * reset, where we can be unlinking the send_head. */ tcp_check_send_head(sk, skb); sk_wmem_free_skb(sk, skb); } do_error: if (copied + copied_syn) goto out; out_err: err = sk_stream_error(sk, flags, err); release_sock(sk); return err; } EXPORT_SYMBOL(tcp_sendmsg); /* * Handle reading urgent data. BSD has very simple semantics for * this, no blocking and very strange errors 8) */ static int tcp_recv_urg(struct sock *sk, struct msghdr *msg, int len, int flags) { struct tcp_sock *tp = tcp_sk(sk); /* No URG data to read. */ if (sock_flag(sk, SOCK_URGINLINE) || !tp->urg_data || tp->urg_data == TCP_URG_READ) return -EINVAL; /* Yes this is right ! */ if (sk->sk_state == TCP_CLOSE && !sock_flag(sk, SOCK_DONE)) return -ENOTCONN; if (tp->urg_data & TCP_URG_VALID) { int err = 0; char c = tp->urg_data; if (!(flags & MSG_PEEK)) tp->urg_data = TCP_URG_READ; /* Read urgent data. */ msg->msg_flags |= MSG_OOB; if (len > 0) { if (!(flags & MSG_TRUNC)) err = memcpy_toiovec(msg->msg_iov, &c, 1); len = 1; } else msg->msg_flags |= MSG_TRUNC; return err ? -EFAULT : len; } if (sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN)) return 0; /* Fixed the recv(..., MSG_OOB) behaviour. BSD docs and * the available implementations agree in this case: * this call should never block, independent of the * blocking state of the socket. * Mike <[email protected]> */ return -EAGAIN; } static int tcp_peek_sndq(struct sock *sk, struct msghdr *msg, int len) { struct sk_buff *skb; int copied = 0, err = 0; /* XXX -- need to support SO_PEEK_OFF */ skb_queue_walk(&sk->sk_write_queue, skb) { err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, skb->len); if (err) break; copied += skb->len; } return err ?: copied; } /* Clean up the receive buffer for full frames taken by the user, * then send an ACK if necessary. COPIED is the number of bytes * tcp_recvmsg has given to the user so far, it speeds up the * calculation of whether or not we must ACK for the sake of * a window update. */ void tcp_cleanup_rbuf(struct sock *sk, int copied) { struct tcp_sock *tp = tcp_sk(sk); bool time_to_ack = false; struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); WARN(skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq), "cleanup rbuf bug: copied %X seq %X rcvnxt %X\n", tp->copied_seq, TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt); if (inet_csk_ack_scheduled(sk)) { const struct inet_connection_sock *icsk = inet_csk(sk); /* Delayed ACKs frequently hit locked sockets during bulk * receive. */ if (icsk->icsk_ack.blocked || /* Once-per-two-segments ACK was not sent by tcp_input.c */ tp->rcv_nxt - tp->rcv_wup > icsk->icsk_ack.rcv_mss || /* * If this read emptied read buffer, we send ACK, if * connection is not bidirectional, user drained * receive buffer and there was a small segment * in queue. */ (copied > 0 && ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED2) || ((icsk->icsk_ack.pending & ICSK_ACK_PUSHED) && !icsk->icsk_ack.pingpong)) && !atomic_read(&sk->sk_rmem_alloc))) time_to_ack = true; } /* We send an ACK if we can now advertise a non-zero window * which has been raised "significantly". * * Even if window raised up to infinity, do not send window open ACK * in states, where we will not receive more. It is useless. */ if (copied > 0 && !time_to_ack && !(sk->sk_shutdown & RCV_SHUTDOWN)) { __u32 rcv_window_now = tcp_receive_window(tp); /* Optimize, __tcp_select_window() is not cheap. */ if (2*rcv_window_now <= tp->window_clamp) { __u32 new_window = __tcp_select_window(sk); /* Send ACK now, if this read freed lots of space * in our buffer. Certainly, new_window is new window. * We can advertise it now, if it is not less than current one. * "Lots" means "at least twice" here. */ if (new_window && new_window >= 2 * rcv_window_now) time_to_ack = true; } } if (time_to_ack) tcp_send_ack(sk); } static void tcp_prequeue_process(struct sock *sk) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPPREQUEUED); /* RX process wants to run with disabled BHs, though it is not * necessary */ local_bh_disable(); while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL) sk_backlog_rcv(sk, skb); local_bh_enable(); /* Clear memory counter. */ tp->ucopy.memory = 0; } #ifdef CONFIG_NET_DMA static void tcp_service_net_dma(struct sock *sk, bool wait) { dma_cookie_t done, used; dma_cookie_t last_issued; struct tcp_sock *tp = tcp_sk(sk); if (!tp->ucopy.dma_chan) return; last_issued = tp->ucopy.dma_cookie; dma_async_issue_pending(tp->ucopy.dma_chan); do { if (dma_async_is_tx_complete(tp->ucopy.dma_chan, last_issued, &done, &used) == DMA_SUCCESS) { /* Safe to free early-copied skbs now */ __skb_queue_purge(&sk->sk_async_wait_queue); break; } else { struct sk_buff *skb; while ((skb = skb_peek(&sk->sk_async_wait_queue)) && (dma_async_is_complete(skb->dma_cookie, done, used) == DMA_SUCCESS)) { __skb_dequeue(&sk->sk_async_wait_queue); kfree_skb(skb); } } } while (wait); } #endif static struct sk_buff *tcp_recv_skb(struct sock *sk, u32 seq, u32 *off) { struct sk_buff *skb; u32 offset; while ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) { offset = seq - TCP_SKB_CB(skb)->seq; if (tcp_hdr(skb)->syn) offset--; if (offset < skb->len || tcp_hdr(skb)->fin) { *off = offset; return skb; } /* This looks weird, but this can happen if TCP collapsing * splitted a fat GRO packet, while we released socket lock * in skb_splice_bits() */ sk_eat_skb(sk, skb, false); } return NULL; } /* * This routine provides an alternative to tcp_recvmsg() for routines * that would like to handle copying from skbuffs directly in 'sendfile' * fashion. * Note: * - It is assumed that the socket was locked by the caller. * - The routine does not block. * - At present, there is no support for reading OOB data * or for 'peeking' the socket using this routine * (although both would be easy to implement). */ int tcp_read_sock(struct sock *sk, read_descriptor_t *desc, sk_read_actor_t recv_actor) { struct sk_buff *skb; struct tcp_sock *tp = tcp_sk(sk); u32 seq = tp->copied_seq; u32 offset; int copied = 0; if (sk->sk_state == TCP_LISTEN) return -ENOTCONN; while ((skb = tcp_recv_skb(sk, seq, &offset)) != NULL) { if (offset < skb->len) { int used; size_t len; len = skb->len - offset; /* Stop reading if we hit a patch of urgent data */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - seq; if (urg_offset < len) len = urg_offset; if (!len) break; } used = recv_actor(desc, skb, offset, len); if (used <= 0) { if (!copied) copied = used; break; } else if (used <= len) { seq += used; copied += used; offset += used; } /* If recv_actor drops the lock (e.g. TCP splice * receive) the skb pointer might be invalid when * getting here: tcp_collapse might have deleted it * while aggregating skbs from the socket queue. */ skb = tcp_recv_skb(sk, seq - 1, &offset); if (!skb) break; /* TCP coalescing might have appended data to the skb. * Try to splice more frags */ if (offset + 1 != skb->len) continue; } if (tcp_hdr(skb)->fin) { sk_eat_skb(sk, skb, false); ++seq; break; } sk_eat_skb(sk, skb, false); if (!desc->count) break; tp->copied_seq = seq; } tp->copied_seq = seq; tcp_rcv_space_adjust(sk); /* Clean up data we have read: This will do ACK frames. */ if (copied > 0) { tcp_recv_skb(sk, seq, &offset); tcp_cleanup_rbuf(sk, copied); uid_stat_tcp_rcv(current_uid(), copied); } return copied; } EXPORT_SYMBOL(tcp_read_sock); /* * This routine copies from a sock struct into the user buffer. * * Technical note: in 2.3 we work on _locked_ socket, so that * tricks with *seq access order and skb->users are not required. * Probably, code can be easily improved even more. */ int tcp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int nonblock, int flags, int *addr_len) { struct tcp_sock *tp = tcp_sk(sk); int copied = 0; u32 peek_seq; u32 *seq; unsigned long used; int err; int target; /* Read at least this many bytes */ long timeo; struct task_struct *user_recv = NULL; bool copied_early = false; struct sk_buff *skb; u32 urg_hole = 0; lock_sock(sk); err = -ENOTCONN; if (sk->sk_state == TCP_LISTEN) goto out; timeo = sock_rcvtimeo(sk, nonblock); /* Urgent data needs to be handled specially. */ if (flags & MSG_OOB) goto recv_urg; if (unlikely(tp->repair)) { err = -EPERM; if (!(flags & MSG_PEEK)) goto out; if (tp->repair_queue == TCP_SEND_QUEUE) goto recv_sndq; err = -EINVAL; if (tp->repair_queue == TCP_NO_QUEUE) goto out; /* 'common' recv queue MSG_PEEK-ing */ } seq = &tp->copied_seq; if (flags & MSG_PEEK) { peek_seq = tp->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); #ifdef CONFIG_NET_DMA tp->ucopy.dma_chan = NULL; preempt_disable(); skb = skb_peek_tail(&sk->sk_receive_queue); { int available = 0; if (skb) available = TCP_SKB_CB(skb)->seq + skb->len - (*seq); if ((available < target) && (len > sysctl_tcp_dma_copybreak) && !(flags & MSG_PEEK) && !sysctl_tcp_low_latency && net_dma_find_channel()) { preempt_enable_no_resched(); tp->ucopy.pinned_list = dma_pin_iovec_pages(msg->msg_iov, len); } else { preempt_enable_no_resched(); } } #endif do { u32 offset; /* Are we at urgent data? Stop if we have read anything or have SIGURG pending. */ if (tp->urg_data && tp->urg_seq == *seq) { if (copied) break; if (signal_pending(current)) { copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } } /* Next get a buffer. */ skb_queue_walk(&sk->sk_receive_queue, skb) { /* Now that we have two receive queues this * shouldn't happen. */ if (WARN(before(*seq, TCP_SKB_CB(skb)->seq), "recvmsg bug: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags)) break; offset = *seq - TCP_SKB_CB(skb)->seq; if (tcp_hdr(skb)->syn) offset--; if (offset < skb->len) goto found_ok_skb; if (tcp_hdr(skb)->fin) goto found_fin_ok; WARN(!(flags & MSG_PEEK), "recvmsg bug 2: copied %X seq %X rcvnxt %X fl %X\n", *seq, TCP_SKB_CB(skb)->seq, tp->rcv_nxt, flags); } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || signal_pending(current)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } if (signal_pending(current)) { copied = sock_intr_errno(timeo); break; } } tcp_cleanup_rbuf(sk, copied); if (!sysctl_tcp_low_latency && tp->ucopy.task == user_recv) { /* Install new reader */ if (!user_recv && !(flags & (MSG_TRUNC | MSG_PEEK))) { user_recv = current; tp->ucopy.task = user_recv; tp->ucopy.iov = msg->msg_iov; } tp->ucopy.len = len; WARN_ON(tp->copied_seq != tp->rcv_nxt && !(flags & (MSG_PEEK | MSG_TRUNC))); /* Ugly... If prequeue is not empty, we have to * process it before releasing socket, otherwise * order will be broken at second iteration. * More elegant solution is required!!! * * Look: we have the following (pseudo)queues: * * 1. packets in flight * 2. backlog * 3. prequeue * 4. receive_queue * * Each queue can be processed only if the next ones * are empty. At this point we have empty receive_queue. * But prequeue _can_ be not empty after 2nd iteration, * when we jumped to start of loop because backlog * processing added something to receive_queue. * We cannot release_sock(), because backlog contains * packets arrived _after_ prequeued ones. * * Shortly, algorithm is clear --- to process all * the queues in order. We could make it more directly, * requeueing packets from backlog to prequeue, if * is not empty. It is more elegant, but eats cycles, * unfortunately. */ if (!skb_queue_empty(&tp->ucopy.prequeue)) goto do_prequeue; /* __ Set realtime policy in scheduler __ */ } #ifdef CONFIG_NET_DMA if (tp->ucopy.dma_chan) { if (tp->rcv_wnd == 0 && !skb_queue_empty(&sk->sk_async_wait_queue)) { tcp_service_net_dma(sk, true); tcp_cleanup_rbuf(sk, copied); } else dma_async_issue_pending(tp->ucopy.dma_chan); } #endif if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); #ifdef CONFIG_NET_DMA tcp_service_net_dma(sk, false); /* Don't block */ tp->ucopy.wakeup = 0; #endif if (user_recv) { int chunk; /* __ Restore normal policy in scheduler __ */ if ((chunk = len - tp->ucopy.len) != 0) { NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMBACKLOG, chunk); len -= chunk; copied += chunk; } if (tp->rcv_nxt == tp->copied_seq && !skb_queue_empty(&tp->ucopy.prequeue)) { do_prequeue: tcp_prequeue_process(sk); if ((chunk = len - tp->ucopy.len) != 0) { NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } } if ((flags & MSG_PEEK) && (peek_seq - copied - urg_hole != tp->copied_seq)) { net_dbg_ratelimited("TCP(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = tp->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; /* Do we have urgent data here? */ if (tp->urg_data) { u32 urg_offset = tp->urg_seq - *seq; if (urg_offset < used) { if (!urg_offset) { if (!sock_flag(sk, SOCK_URGINLINE)) { ++*seq; urg_hole++; offset++; used--; if (!used) goto skip_copy; } } else used = urg_offset; } } if (!(flags & MSG_TRUNC)) { #ifdef CONFIG_NET_DMA if (!tp->ucopy.dma_chan && tp->ucopy.pinned_list) tp->ucopy.dma_chan = net_dma_find_channel(); if (tp->ucopy.dma_chan) { tp->ucopy.dma_cookie = dma_skb_copy_datagram_iovec( tp->ucopy.dma_chan, skb, offset, msg->msg_iov, used, tp->ucopy.pinned_list); if (tp->ucopy.dma_cookie < 0) { pr_alert("%s: dma_cookie < 0\n", __func__); /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } dma_async_issue_pending(tp->ucopy.dma_chan); if ((offset + used) == skb->len) copied_early = true; } else #endif { err = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (err) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } } *seq += used; copied += used; len -= used; tcp_rcv_space_adjust(sk); skip_copy: if (tp->urg_data && after(tp->copied_seq, tp->urg_seq)) { tp->urg_data = 0; tcp_fast_path_check(sk); } if (used + offset < skb->len) continue; if (tcp_hdr(skb)->fin) goto found_fin_ok; if (!(flags & MSG_PEEK)) { sk_eat_skb(sk, skb, copied_early); copied_early = false; } continue; found_fin_ok: /* Process the FIN. */ ++*seq; if (!(flags & MSG_PEEK)) { sk_eat_skb(sk, skb, copied_early); copied_early = false; } break; } while (len > 0); if (user_recv) { if (!skb_queue_empty(&tp->ucopy.prequeue)) { int chunk; tp->ucopy.len = copied > 0 ? len : 0; tcp_prequeue_process(sk); if (copied > 0 && (chunk = len - tp->ucopy.len) != 0) { NET_ADD_STATS_USER(sock_net(sk), LINUX_MIB_TCPDIRECTCOPYFROMPREQUEUE, chunk); len -= chunk; copied += chunk; } } tp->ucopy.task = NULL; tp->ucopy.len = 0; } #ifdef CONFIG_NET_DMA tcp_service_net_dma(sk, true); /* Wait for queue to drain */ tp->ucopy.dma_chan = NULL; if (tp->ucopy.pinned_list) { dma_unpin_iovec_pages(tp->ucopy.pinned_list); tp->ucopy.pinned_list = NULL; } #endif /* According to UNIX98, msg_name/msg_namelen are ignored * on connected socket. I was just happy when found this 8) --ANK */ /* Clean up data we have read: This will do ACK frames. */ tcp_cleanup_rbuf(sk, copied); release_sock(sk); if (copied > 0) uid_stat_tcp_rcv(current_uid(), copied); return copied; out: release_sock(sk); return err; recv_urg: err = tcp_recv_urg(sk, msg, len, flags); if (err > 0) uid_stat_tcp_rcv(current_uid(), err); goto out; recv_sndq: err = tcp_peek_sndq(sk, msg, len); goto out; } EXPORT_SYMBOL(tcp_recvmsg); void tcp_set_state(struct sock *sk, int state) { int oldstate = sk->sk_state; switch (state) { case TCP_ESTABLISHED: if (oldstate != TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); break; case TCP_CLOSE: if (oldstate == TCP_CLOSE_WAIT || oldstate == TCP_ESTABLISHED) TCP_INC_STATS(sock_net(sk), TCP_MIB_ESTABRESETS); sk->sk_prot->unhash(sk); if (inet_csk(sk)->icsk_bind_hash && !(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) inet_put_port(sk); /* fall through */ default: if (oldstate == TCP_ESTABLISHED) TCP_DEC_STATS(sock_net(sk), TCP_MIB_CURRESTAB); } /* Change state AFTER socket is unhashed to avoid closed * socket sitting in hash tables. */ sk->sk_state = state; #ifdef STATE_TRACE SOCK_DEBUG(sk, "TCP sk=%p, State %s -> %s\n", sk, statename[oldstate], statename[state]); #endif } EXPORT_SYMBOL_GPL(tcp_set_state); /* * State processing on a close. This implements the state shift for * sending our FIN frame. Note that we only send a FIN for some * states. A shutdown() may have already sent the FIN, or we may be * closed. */ static const unsigned char new_state[16] = { /* current state: new state: action: */ /* (Invalid) */ TCP_CLOSE, /* TCP_ESTABLISHED */ TCP_FIN_WAIT1 | TCP_ACTION_FIN, /* TCP_SYN_SENT */ TCP_CLOSE, /* TCP_SYN_RECV */ TCP_FIN_WAIT1 | TCP_ACTION_FIN, /* TCP_FIN_WAIT1 */ TCP_FIN_WAIT1, /* TCP_FIN_WAIT2 */ TCP_FIN_WAIT2, /* TCP_TIME_WAIT */ TCP_CLOSE, /* TCP_CLOSE */ TCP_CLOSE, /* TCP_CLOSE_WAIT */ TCP_LAST_ACK | TCP_ACTION_FIN, /* TCP_LAST_ACK */ TCP_LAST_ACK, /* TCP_LISTEN */ TCP_CLOSE, /* TCP_CLOSING */ TCP_CLOSING, }; static int tcp_close_state(struct sock *sk) { int next = (int)new_state[sk->sk_state]; int ns = next & TCP_STATE_MASK; tcp_set_state(sk, ns); return next & TCP_ACTION_FIN; } /* * Shutdown the sending side of a connection. Much like close except * that we don't receive shut down or sock_set_flag(sk, SOCK_DEAD). */ void tcp_shutdown(struct sock *sk, int how) { /* We need to grab some memory, and put together a FIN, * and then put it into the queue to be sent. * Tim MacKenzie([email protected]) 4 Dec '92. */ if (!(how & SEND_SHUTDOWN)) return; /* If we've already sent a FIN, or it's a closed state, skip this. */ if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE_WAIT)) { /* Clear out any half completed packets. FIN if needed. */ if (tcp_close_state(sk)) tcp_send_fin(sk); } } EXPORT_SYMBOL(tcp_shutdown); bool tcp_check_oom(struct sock *sk, int shift) { bool too_many_orphans, out_of_socket_memory; too_many_orphans = tcp_too_many_orphans(sk, shift); out_of_socket_memory = tcp_out_of_memory(sk); if (too_many_orphans) net_info_ratelimited("too many orphaned sockets\n"); if (out_of_socket_memory) net_info_ratelimited("out of memory -- consider tuning tcp_mem\n"); return too_many_orphans || out_of_socket_memory; } void tcp_close(struct sock *sk, long timeout) { struct sk_buff *skb; int data_was_unread = 0; int state; lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); /* Special case. */ inet_csk_listen_stop(sk); goto adjudge_to_death; } /* We need to flush the recv. buffs. We do this only on the * descriptor close, not protocol-sourced closes, because the * reader process may not have drained the data yet! */ while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) { u32 len = TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq - tcp_hdr(skb)->fin; data_was_unread += len; __kfree_skb(skb); } sk_mem_reclaim(sk); /* If socket has been already reset (e.g. in tcp_reset()) - kill it. */ if (sk->sk_state == TCP_CLOSE) goto adjudge_to_death; /* As outlined in RFC 2525, section 2.17, we send a RST here because * data was lost. To witness the awful effects of the old behavior of * always doing a FIN, run an older 2.1.x kernel or 2.0.x, start a bulk * GET in an FTP client, suspend the process, wait for the client to * advertise a zero window, then kill -9 the FTP client, wheee... * Note: timeout is always zero in such a case. */ if (unlikely(tcp_sk(sk)->repair)) { sk->sk_prot->disconnect(sk, 0); } else if (data_was_unread) { /* Unread data was tossed, zap the connection. */ NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONCLOSE); tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, sk->sk_allocation); } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) { /* Check zero linger _after_ checking for unread data. */ sk->sk_prot->disconnect(sk, 0); NET_INC_STATS_USER(sock_net(sk), LINUX_MIB_TCPABORTONDATA); } else if (tcp_close_state(sk)) { /* We FIN if the application ate all the data before * zapping the connection. */ /* RED-PEN. Formally speaking, we have broken TCP state * machine. State transitions: * * TCP_ESTABLISHED -> TCP_FIN_WAIT1 * TCP_SYN_RECV -> TCP_FIN_WAIT1 (forget it, it's impossible) * TCP_CLOSE_WAIT -> TCP_LAST_ACK * * are legal only when FIN has been sent (i.e. in window), * rather than queued out of window. Purists blame. * * F.e. "RFC state" is ESTABLISHED, * if Linux state is FIN-WAIT-1, but FIN is still not sent. * * The visible declinations are that sometimes * we enter time-wait state, when it is not required really * (harmless), do not send active resets, when they are * required by specs (TCP_ESTABLISHED, TCP_CLOSE_WAIT, when * they look as CLOSING or LAST_ACK for Linux) * Probably, I missed some more holelets. * --ANK * XXX (TFO) - To start off we don't support SYN+ACK+FIN * in a single packet! (May consider it later but will * probably need API support or TCP_CORK SYN-ACK until * data is written and socket is closed.) */ tcp_send_fin(sk); } sk_stream_wait_close(sk, timeout); adjudge_to_death: state = sk->sk_state; sock_hold(sk); sock_orphan(sk); /* It is the last release_sock in its life. It will remove backlog. */ release_sock(sk); /* Now socket is owned by kernel and we acquire BH lock to finish close. No need to check for user refs. */ local_bh_disable(); bh_lock_sock(sk); WARN_ON(sock_owned_by_user(sk)); percpu_counter_inc(sk->sk_prot->orphan_count); /* Have we already been destroyed by a softirq or backlog? */ if (state != TCP_CLOSE && sk->sk_state == TCP_CLOSE) goto out; /* This is a (useful) BSD violating of the RFC. There is a * problem with TCP as specified in that the other end could * keep a socket open forever with no application left this end. * We use a 3 minute timeout (about the same as BSD) then kill * our end. If they send after that then tough - BUT: long enough * that we won't make the old 4*rto = almost no time - whoops * reset mistake. * * Nope, it was not mistake. It is really desired behaviour * f.e. on http servers, when such sockets are useless, but * consume significant resources. Let's do it with special * linger2 option. --ANK */ if (sk->sk_state == TCP_FIN_WAIT2) { struct tcp_sock *tp = tcp_sk(sk); if (tp->linger2 < 0) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONLINGER); } else { const int tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto out; } } } if (sk->sk_state != TCP_CLOSE) { sk_mem_reclaim(sk); if (tcp_check_oom(sk, 0)) { tcp_set_state(sk, TCP_CLOSE); tcp_send_active_reset(sk, GFP_ATOMIC); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY); } } if (sk->sk_state == TCP_CLOSE) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; /* We could get here with a non-NULL req if the socket is * aborted (e.g., closed with unread data) before 3WHS * finishes. */ if (req != NULL) reqsk_fastopen_remove(sk, req, false); inet_csk_destroy_sock(sk); } /* Otherwise, socket is reprieved until protocol close. */ out: bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); } EXPORT_SYMBOL(tcp_close); /* These states need RST on ABORT according to RFC793 */ static inline bool tcp_need_reset(int state) { return (1 << state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT | TCPF_FIN_WAIT1 | TCPF_FIN_WAIT2 | TCPF_SYN_RECV); } int tcp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err = 0; int old_state = sk->sk_state; if (old_state != TCP_CLOSE) tcp_set_state(sk, TCP_CLOSE); /* ABORT function of RFC793 */ if (old_state == TCP_LISTEN) { inet_csk_listen_stop(sk); } else if (unlikely(tp->repair)) { sk->sk_err = ECONNABORTED; } else if (tcp_need_reset(old_state) || (tp->snd_nxt != tp->write_seq && (1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) { /* The last check adjusts for discrepancy of Linux wrt. RFC * states */ tcp_send_active_reset(sk, gfp_any()); sk->sk_err = ECONNRESET; } else if (old_state == TCP_SYN_SENT) sk->sk_err = ECONNRESET; tcp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); tcp_write_queue_purge(sk); __skb_queue_purge(&tp->out_of_order_queue); #ifdef CONFIG_NET_DMA __skb_queue_purge(&sk->sk_async_wait_queue); #endif inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); tp->srtt = 0; if ((tp->write_seq += tp->max_window + 2) == 0) tp->write_seq = 1; icsk->icsk_backoff = 0; tp->snd_cwnd = 2; icsk->icsk_probes_out = 0; tp->packets_out = 0; tp->snd_ssthresh = TCP_INFINITE_SSTHRESH; tp->snd_cwnd_cnt = 0; tp->window_clamp = 0; tcp_set_ca_state(sk, TCP_CA_Open); tcp_clear_retrans(tp); inet_csk_delack_init(sk); tcp_init_send_head(sk); memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); __sk_dst_reset(sk); WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } EXPORT_SYMBOL(tcp_disconnect); void tcp_sock_destruct(struct sock *sk) { inet_sock_destruct(sk); kfree(inet_csk(sk)->icsk_accept_queue.fastopenq); } static inline bool tcp_can_repair_sock(const struct sock *sk) { return ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN) && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_ESTABLISHED)); } static int tcp_repair_options_est(struct tcp_sock *tp, struct tcp_repair_opt __user *optbuf, unsigned int len) { struct tcp_repair_opt opt; while (len >= sizeof(opt)) { if (copy_from_user(&opt, optbuf, sizeof(opt))) return -EFAULT; optbuf++; len -= sizeof(opt); switch (opt.opt_code) { case TCPOPT_MSS: tp->rx_opt.mss_clamp = opt.opt_val; break; case TCPOPT_WINDOW: { u16 snd_wscale = opt.opt_val & 0xFFFF; u16 rcv_wscale = opt.opt_val >> 16; if (snd_wscale > 14 || rcv_wscale > 14) return -EFBIG; tp->rx_opt.snd_wscale = snd_wscale; tp->rx_opt.rcv_wscale = rcv_wscale; tp->rx_opt.wscale_ok = 1; } break; case TCPOPT_SACK_PERM: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.sack_ok |= TCP_SACK_SEEN; if (sysctl_tcp_fack) tcp_enable_fack(tp); break; case TCPOPT_TIMESTAMP: if (opt.opt_val != 0) return -EINVAL; tp->rx_opt.tstamp_ok = 1; break; } } return 0; } /* * Socket option code for TCP. */ static int do_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int val; int err = 0; /* These are data/string values, all the others are ints */ switch (optname) { case TCP_CONGESTION: { char name[TCP_CA_NAME_MAX]; if (optlen < 1) return -EINVAL; val = strncpy_from_user(name, optval, min_t(long, TCP_CA_NAME_MAX-1, optlen)); if (val < 0) return -EFAULT; name[val] = 0; lock_sock(sk); err = tcp_set_congestion_control(sk, name); release_sock(sk); return err; } default: /* fallthru */ break; } if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; lock_sock(sk); switch (optname) { case TCP_MAXSEG: /* Values greater than interface MTU won't take effect. However * at the point when this call is done we typically don't yet * know which interface is going to be used */ if (val < TCP_MIN_MSS || val > MAX_TCP_WINDOW) { err = -EINVAL; break; } tp->rx_opt.user_mss = val; break; case TCP_NODELAY: if (val) { /* TCP_NODELAY is weaker than TCP_CORK, so that * this option on corked socket is remembered, but * it is not activated until cork is cleared. * * However, when TCP_NODELAY is set we make * an explicit push, which overrides even TCP_CORK * for currently queued segments. */ tp->nonagle |= TCP_NAGLE_OFF|TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } else { tp->nonagle &= ~TCP_NAGLE_OFF; } break; case TCP_THIN_LINEAR_TIMEOUTS: if (val < 0 || val > 1) err = -EINVAL; else tp->thin_lto = val; break; case TCP_THIN_DUPACK: if (val < 0 || val > 1) err = -EINVAL; else { tp->thin_dupack = val; if (tp->thin_dupack) tcp_disable_early_retrans(tp); } break; case TCP_REPAIR: if (!tcp_can_repair_sock(sk)) err = -EPERM; else if (val == 1) { tp->repair = 1; sk->sk_reuse = SK_FORCE_REUSE; tp->repair_queue = TCP_NO_QUEUE; } else if (val == 0) { tp->repair = 0; sk->sk_reuse = SK_NO_REUSE; tcp_send_window_probe(sk); } else err = -EINVAL; break; case TCP_REPAIR_QUEUE: if (!tp->repair) err = -EPERM; else if (val < TCP_QUEUES_NR) tp->repair_queue = val; else err = -EINVAL; break; case TCP_QUEUE_SEQ: if (sk->sk_state != TCP_CLOSE) err = -EPERM; else if (tp->repair_queue == TCP_SEND_QUEUE) tp->write_seq = val; else if (tp->repair_queue == TCP_RECV_QUEUE) tp->rcv_nxt = val; else err = -EINVAL; break; case TCP_REPAIR_OPTIONS: if (!tp->repair) err = -EINVAL; else if (sk->sk_state == TCP_ESTABLISHED) err = tcp_repair_options_est(tp, (struct tcp_repair_opt __user *)optval, optlen); else err = -EPERM; break; case TCP_CORK: /* When set indicates to always queue non-full frames. * Later the user clears this option and we transmit * any pending partial frames in the queue. This is * meant to be used alongside sendfile() to get properly * filled frames when the user (for example) must write * out headers with a write() call first and then use * sendfile to send out the data parts. * * TCP_CORK can be set together with TCP_NODELAY and it is * stronger than TCP_NODELAY. */ if (val) { tp->nonagle |= TCP_NAGLE_CORK; } else { tp->nonagle &= ~TCP_NAGLE_CORK; if (tp->nonagle&TCP_NAGLE_OFF) tp->nonagle |= TCP_NAGLE_PUSH; tcp_push_pending_frames(sk); } break; case TCP_KEEPIDLE: if (val < 1 || val > MAX_TCP_KEEPIDLE) err = -EINVAL; else { tp->keepalive_time = val * HZ; if (sock_flag(sk, SOCK_KEEPOPEN) && !((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) { u32 elapsed = keepalive_time_elapsed(tp); if (tp->keepalive_time > elapsed) elapsed = tp->keepalive_time - elapsed; else elapsed = 0; inet_csk_reset_keepalive_timer(sk, elapsed); } } break; case TCP_KEEPINTVL: if (val < 1 || val > MAX_TCP_KEEPINTVL) err = -EINVAL; else tp->keepalive_intvl = val * HZ; break; case TCP_KEEPCNT: if (val < 1 || val > MAX_TCP_KEEPCNT) err = -EINVAL; else tp->keepalive_probes = val; break; case TCP_SYNCNT: if (val < 1 || val > MAX_TCP_SYNCNT) err = -EINVAL; else icsk->icsk_syn_retries = val; break; case TCP_LINGER2: if (val < 0) tp->linger2 = -1; else if (val > sysctl_tcp_fin_timeout / HZ) tp->linger2 = 0; else tp->linger2 = val * HZ; break; case TCP_DEFER_ACCEPT: /* Translate value in seconds to number of retransmits */ icsk->icsk_accept_queue.rskq_defer_accept = secs_to_retrans(val, TCP_TIMEOUT_INIT / HZ, sysctl_tcp_rto_max / HZ); break; case TCP_WINDOW_CLAMP: if (!val) { if (sk->sk_state != TCP_CLOSE) { err = -EINVAL; break; } tp->window_clamp = 0; } else tp->window_clamp = val < SOCK_MIN_RCVBUF / 2 ? SOCK_MIN_RCVBUF / 2 : val; break; case TCP_QUICKACK: if (!val) { icsk->icsk_ack.pingpong = 1; } else { icsk->icsk_ack.pingpong = 0; if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_CLOSE_WAIT) && inet_csk_ack_scheduled(sk)) { icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; tcp_cleanup_rbuf(sk, 1); if (!(val & 1)) icsk->icsk_ack.pingpong = 1; } } break; #ifdef CONFIG_TCP_MD5SIG case TCP_MD5SIG: /* Read the IP->Key mappings from userspace */ err = tp->af_specific->md5_parse(sk, optval, optlen); break; #endif case TCP_USER_TIMEOUT: /* Cap the max timeout in ms TCP will retry/retrans * before giving up and aborting (ETIMEDOUT) a connection. */ if (val < 0) err = -EINVAL; else icsk->icsk_user_timeout = msecs_to_jiffies(val); break; case TCP_FASTOPEN: if (val >= 0 && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) err = fastopen_init_queue(sk, val); else err = -EINVAL; break; case TCP_TIMESTAMP: if (!tp->repair) err = -EPERM; else tp->tsoffset = val - tcp_time_stamp; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } int tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { const struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_setsockopt); #ifdef CONFIG_COMPAT int compat_tcp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level != SOL_TCP) return inet_csk_compat_setsockopt(sk, level, optname, optval, optlen); return do_tcp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_setsockopt); #endif /* Return information about state of tcp endpoint in API format. */ void tcp_get_info(const struct sock *sk, struct tcp_info *info) { const struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); u32 now = tcp_time_stamp; memset(info, 0, sizeof(*info)); info->tcpi_state = sk->sk_state; info->tcpi_ca_state = icsk->icsk_ca_state; info->tcpi_retransmits = icsk->icsk_retransmits; info->tcpi_probes = icsk->icsk_probes_out; info->tcpi_backoff = icsk->icsk_backoff; if (tp->rx_opt.tstamp_ok) info->tcpi_options |= TCPI_OPT_TIMESTAMPS; if (tcp_is_sack(tp)) info->tcpi_options |= TCPI_OPT_SACK; if (tp->rx_opt.wscale_ok) { info->tcpi_options |= TCPI_OPT_WSCALE; info->tcpi_snd_wscale = tp->rx_opt.snd_wscale; info->tcpi_rcv_wscale = tp->rx_opt.rcv_wscale; } if (tp->ecn_flags & TCP_ECN_OK) info->tcpi_options |= TCPI_OPT_ECN; if (tp->ecn_flags & TCP_ECN_SEEN) info->tcpi_options |= TCPI_OPT_ECN_SEEN; if (tp->syn_data_acked) info->tcpi_options |= TCPI_OPT_SYN_DATA; info->tcpi_rto = jiffies_to_usecs(icsk->icsk_rto); info->tcpi_ato = jiffies_to_usecs(icsk->icsk_ack.ato); info->tcpi_snd_mss = tp->mss_cache; info->tcpi_rcv_mss = icsk->icsk_ack.rcv_mss; if (sk->sk_state == TCP_LISTEN) { info->tcpi_unacked = sk->sk_ack_backlog; info->tcpi_sacked = sk->sk_max_ack_backlog; } else { info->tcpi_unacked = tp->packets_out; info->tcpi_sacked = tp->sacked_out; } info->tcpi_lost = tp->lost_out; info->tcpi_retrans = tp->retrans_out; info->tcpi_fackets = tp->fackets_out; info->tcpi_last_data_sent = jiffies_to_msecs(now - tp->lsndtime); info->tcpi_last_data_recv = jiffies_to_msecs(now - icsk->icsk_ack.lrcvtime); info->tcpi_last_ack_recv = jiffies_to_msecs(now - tp->rcv_tstamp); info->tcpi_pmtu = icsk->icsk_pmtu_cookie; info->tcpi_rcv_ssthresh = tp->rcv_ssthresh; info->tcpi_rtt = jiffies_to_usecs(tp->srtt)>>3; info->tcpi_rttvar = jiffies_to_usecs(tp->mdev)>>2; info->tcpi_snd_ssthresh = tp->snd_ssthresh; info->tcpi_snd_cwnd = tp->snd_cwnd; info->tcpi_advmss = tp->advmss; info->tcpi_reordering = tp->reordering; info->tcpi_rcv_rtt = jiffies_to_usecs(tp->rcv_rtt_est.rtt)>>3; info->tcpi_rcv_space = tp->rcvq_space.space; info->tcpi_total_retrans = tp->total_retrans; } EXPORT_SYMBOL_GPL(tcp_get_info); static int do_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case TCP_MAXSEG: val = tp->mss_cache; if (!val && ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))) val = tp->rx_opt.user_mss; if (tp->repair) val = tp->rx_opt.mss_clamp; break; case TCP_NODELAY: val = !!(tp->nonagle&TCP_NAGLE_OFF); break; case TCP_CORK: val = !!(tp->nonagle&TCP_NAGLE_CORK); break; case TCP_KEEPIDLE: val = keepalive_time_when(tp) / HZ; break; case TCP_KEEPINTVL: val = keepalive_intvl_when(tp) / HZ; break; case TCP_KEEPCNT: val = keepalive_probes(tp); break; case TCP_SYNCNT: val = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries; break; case TCP_LINGER2: val = tp->linger2; if (val >= 0) val = (val ? : sysctl_tcp_fin_timeout) / HZ; break; case TCP_DEFER_ACCEPT: val = retrans_to_secs(icsk->icsk_accept_queue.rskq_defer_accept, TCP_TIMEOUT_INIT / HZ, sysctl_tcp_rto_max / HZ); break; case TCP_WINDOW_CLAMP: val = tp->window_clamp; break; case TCP_INFO: { struct tcp_info info; if (get_user(len, optlen)) return -EFAULT; tcp_get_info(sk, &info); len = min_t(unsigned int, len, sizeof(info)); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &info, len)) return -EFAULT; return 0; } case TCP_QUICKACK: val = !icsk->icsk_ack.pingpong; break; case TCP_CONGESTION: if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, TCP_CA_NAME_MAX); if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, icsk->icsk_ca_ops->name, len)) return -EFAULT; return 0; case TCP_THIN_LINEAR_TIMEOUTS: val = tp->thin_lto; break; case TCP_THIN_DUPACK: val = tp->thin_dupack; break; case TCP_REPAIR: val = tp->repair; break; case TCP_REPAIR_QUEUE: if (tp->repair) val = tp->repair_queue; else return -EINVAL; break; case TCP_QUEUE_SEQ: if (tp->repair_queue == TCP_SEND_QUEUE) val = tp->write_seq; else if (tp->repair_queue == TCP_RECV_QUEUE) val = tp->rcv_nxt; else return -EINVAL; break; case TCP_USER_TIMEOUT: val = jiffies_to_msecs(icsk->icsk_user_timeout); break; case TCP_TIMESTAMP: val = tcp_time_stamp + tp->tsoffset; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } int tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct inet_connection_sock *icsk = inet_csk(sk); if (level != SOL_TCP) return icsk->icsk_af_ops->getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(tcp_getsockopt); #ifdef CONFIG_COMPAT int compat_tcp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level != SOL_TCP) return inet_csk_compat_getsockopt(sk, level, optname, optval, optlen); return do_tcp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL(compat_tcp_getsockopt); #endif struct sk_buff *tcp_tso_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); unsigned int sum_truesize = 0; struct tcphdr *th; unsigned int thlen; unsigned int seq; __be32 delta; unsigned int oldlen; unsigned int mss; struct sk_buff *gso_skb = skb; __sum16 newcheck; bool ooo_okay, copy_destructor; if (!pskb_may_pull(skb, sizeof(*th))) goto out; th = tcp_hdr(skb); thlen = th->doff * 4; if (thlen < sizeof(*th)) goto out; if (!pskb_may_pull(skb, thlen)) goto out; oldlen = (u16)~skb->len; __skb_pull(skb, thlen); mss = skb_shinfo(skb)->gso_size; if (unlikely(skb->len <= mss)) goto out; if (skb_gso_ok(skb, features | NETIF_F_GSO_ROBUST)) { /* Packet is from an untrusted source, reset gso_segs. */ int type = skb_shinfo(skb)->gso_type; if (unlikely(type & ~(SKB_GSO_TCPV4 | SKB_GSO_DODGY | SKB_GSO_TCP_ECN | SKB_GSO_TCPV6 | SKB_GSO_GRE | SKB_GSO_UDP_TUNNEL | 0) || !(type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))) goto out; skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss); segs = NULL; goto out; } copy_destructor = gso_skb->destructor == tcp_wfree; ooo_okay = gso_skb->ooo_okay; /* All segments but the first should have ooo_okay cleared */ skb->ooo_okay = 0; segs = skb_segment(skb, features); if (IS_ERR(segs)) goto out; /* Only first segment might have ooo_okay set */ segs->ooo_okay = ooo_okay; delta = htonl(oldlen + (thlen + mss)); skb = segs; th = tcp_hdr(skb); seq = ntohl(th->seq); newcheck = ~csum_fold((__force __wsum)((__force u32)th->check + (__force u32)delta)); do { th->fin = th->psh = 0; th->check = newcheck; if (skb->ip_summed != CHECKSUM_PARTIAL) th->check = csum_fold(csum_partial(skb_transport_header(skb), thlen, skb->csum)); seq += mss; if (copy_destructor) { skb->destructor = gso_skb->destructor; skb->sk = gso_skb->sk; sum_truesize += skb->truesize; } skb = skb->next; th = tcp_hdr(skb); th->seq = htonl(seq); th->cwr = 0; } while (skb->next); /* Following permits TCP Small Queues to work well with GSO : * The callback to TCP stack will be called at the time last frag * is freed at TX completion, and not right now when gso_skb * is freed by GSO engine */ if (copy_destructor) { swap(gso_skb->sk, skb->sk); swap(gso_skb->destructor, skb->destructor); sum_truesize += skb->truesize; atomic_add(sum_truesize - gso_skb->truesize, &skb->sk->sk_wmem_alloc); } delta = htonl(oldlen + (skb->tail - skb->transport_header) + skb->data_len); th->check = ~csum_fold((__force __wsum)((__force u32)th->check + (__force u32)delta)); if (skb->ip_summed != CHECKSUM_PARTIAL) th->check = csum_fold(csum_partial(skb_transport_header(skb), thlen, skb->csum)); out: return segs; } EXPORT_SYMBOL(tcp_tso_segment); struct sk_buff **tcp_gro_receive(struct sk_buff **head, struct sk_buff *skb) { struct sk_buff **pp = NULL; struct sk_buff *p; struct tcphdr *th; struct tcphdr *th2; unsigned int len; unsigned int thlen; __be32 flags; unsigned int mss = 1; unsigned int hlen; unsigned int off; int flush = 1; int i; off = skb_gro_offset(skb); hlen = off + sizeof(*th); th = skb_gro_header_fast(skb, off); if (skb_gro_header_hard(skb, hlen)) { th = skb_gro_header_slow(skb, hlen, off); if (unlikely(!th)) goto out; } thlen = th->doff * 4; if (thlen < sizeof(*th)) goto out; hlen = off + thlen; if (skb_gro_header_hard(skb, hlen)) { th = skb_gro_header_slow(skb, hlen, off); if (unlikely(!th)) goto out; } skb_gro_pull(skb, thlen); len = skb_gro_len(skb); flags = tcp_flag_word(th); for (; (p = *head); head = &p->next) { if (!NAPI_GRO_CB(p)->same_flow) continue; th2 = tcp_hdr(p); if (*(u32 *)&th->source ^ *(u32 *)&th2->source) { NAPI_GRO_CB(p)->same_flow = 0; continue; } goto found; } goto out_check_final; found: flush = NAPI_GRO_CB(p)->flush; flush |= (__force int)(flags & TCP_FLAG_CWR); flush |= (__force int)((flags ^ tcp_flag_word(th2)) & ~(TCP_FLAG_CWR | TCP_FLAG_FIN | TCP_FLAG_PSH)); flush |= (__force int)(th->ack_seq ^ th2->ack_seq); for (i = sizeof(*th); i < thlen; i += 4) flush |= *(u32 *)((u8 *)th + i) ^ *(u32 *)((u8 *)th2 + i); mss = skb_shinfo(p)->gso_size; flush |= (len - 1) >= mss; flush |= (ntohl(th2->seq) + skb_gro_len(p)) ^ ntohl(th->seq); if (flush || skb_gro_receive(head, skb)) { mss = 1; goto out_check_final; } p = *head; th2 = tcp_hdr(p); tcp_flag_word(th2) |= flags & (TCP_FLAG_FIN | TCP_FLAG_PSH); out_check_final: flush = len < mss; flush |= (__force int)(flags & (TCP_FLAG_URG | TCP_FLAG_PSH | TCP_FLAG_RST | TCP_FLAG_SYN | TCP_FLAG_FIN)); if (p && (!NAPI_GRO_CB(skb)->same_flow || flush)) pp = head; out: NAPI_GRO_CB(skb)->flush |= flush; return pp; } EXPORT_SYMBOL(tcp_gro_receive); int tcp_gro_complete(struct sk_buff *skb) { struct tcphdr *th = tcp_hdr(skb); skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct tcphdr, check); skb->ip_summed = CHECKSUM_PARTIAL; skb_shinfo(skb)->gso_segs = NAPI_GRO_CB(skb)->count; if (th->cwr) skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; return 0; } EXPORT_SYMBOL(tcp_gro_complete); #ifdef CONFIG_TCP_MD5SIG static unsigned long tcp_md5sig_users; static struct tcp_md5sig_pool __percpu *tcp_md5sig_pool; static DEFINE_SPINLOCK(tcp_md5sig_pool_lock); static void __tcp_free_md5sig_pool(struct tcp_md5sig_pool __percpu *pool) { int cpu; for_each_possible_cpu(cpu) { struct tcp_md5sig_pool *p = per_cpu_ptr(pool, cpu); if (p->md5_desc.tfm) crypto_free_hash(p->md5_desc.tfm); } free_percpu(pool); } void tcp_free_md5sig_pool(void) { struct tcp_md5sig_pool __percpu *pool = NULL; spin_lock_bh(&tcp_md5sig_pool_lock); if (--tcp_md5sig_users == 0) { pool = tcp_md5sig_pool; tcp_md5sig_pool = NULL; } spin_unlock_bh(&tcp_md5sig_pool_lock); if (pool) __tcp_free_md5sig_pool(pool); } EXPORT_SYMBOL(tcp_free_md5sig_pool); static struct tcp_md5sig_pool __percpu * __tcp_alloc_md5sig_pool(struct sock *sk) { int cpu; struct tcp_md5sig_pool __percpu *pool; pool = alloc_percpu(struct tcp_md5sig_pool); if (!pool) return NULL; for_each_possible_cpu(cpu) { struct crypto_hash *hash; hash = crypto_alloc_hash("md5", 0, CRYPTO_ALG_ASYNC); if (IS_ERR_OR_NULL(hash)) goto out_free; per_cpu_ptr(pool, cpu)->md5_desc.tfm = hash; } return pool; out_free: __tcp_free_md5sig_pool(pool); return NULL; } struct tcp_md5sig_pool __percpu *tcp_alloc_md5sig_pool(struct sock *sk) { struct tcp_md5sig_pool __percpu *pool; bool alloc = false; retry: spin_lock_bh(&tcp_md5sig_pool_lock); pool = tcp_md5sig_pool; if (tcp_md5sig_users++ == 0) { alloc = true; spin_unlock_bh(&tcp_md5sig_pool_lock); } else if (!pool) { tcp_md5sig_users--; spin_unlock_bh(&tcp_md5sig_pool_lock); cpu_relax(); goto retry; } else spin_unlock_bh(&tcp_md5sig_pool_lock); if (alloc) { /* we cannot hold spinlock here because this may sleep. */ struct tcp_md5sig_pool __percpu *p; p = __tcp_alloc_md5sig_pool(sk); spin_lock_bh(&tcp_md5sig_pool_lock); if (!p) { tcp_md5sig_users--; spin_unlock_bh(&tcp_md5sig_pool_lock); return NULL; } pool = tcp_md5sig_pool; if (pool) { /* oops, it has already been assigned. */ spin_unlock_bh(&tcp_md5sig_pool_lock); __tcp_free_md5sig_pool(p); } else { tcp_md5sig_pool = pool = p; spin_unlock_bh(&tcp_md5sig_pool_lock); } } return pool; } EXPORT_SYMBOL(tcp_alloc_md5sig_pool); /** * tcp_get_md5sig_pool - get md5sig_pool for this user * * We use percpu structure, so if we succeed, we exit with preemption * and BH disabled, to make sure another thread or softirq handling * wont try to get same context. */ struct tcp_md5sig_pool *tcp_get_md5sig_pool(void) { struct tcp_md5sig_pool __percpu *p; local_bh_disable(); spin_lock(&tcp_md5sig_pool_lock); p = tcp_md5sig_pool; if (p) tcp_md5sig_users++; spin_unlock(&tcp_md5sig_pool_lock); if (p) return this_cpu_ptr(p); local_bh_enable(); return NULL; } EXPORT_SYMBOL(tcp_get_md5sig_pool); void tcp_put_md5sig_pool(void) { local_bh_enable(); tcp_free_md5sig_pool(); } EXPORT_SYMBOL(tcp_put_md5sig_pool); int tcp_md5_hash_header(struct tcp_md5sig_pool *hp, const struct tcphdr *th) { struct scatterlist sg; struct tcphdr hdr; int err; /* We are not allowed to change tcphdr, make a local copy */ memcpy(&hdr, th, sizeof(hdr)); hdr.check = 0; /* options aren't included in the hash */ sg_init_one(&sg, &hdr, sizeof(hdr)); err = crypto_hash_update(&hp->md5_desc, &sg, sizeof(hdr)); return err; } EXPORT_SYMBOL(tcp_md5_hash_header); int tcp_md5_hash_skb_data(struct tcp_md5sig_pool *hp, const struct sk_buff *skb, unsigned int header_len) { struct scatterlist sg; const struct tcphdr *tp = tcp_hdr(skb); struct hash_desc *desc = &hp->md5_desc; unsigned int i; const unsigned int head_data_len = skb_headlen(skb) > header_len ? skb_headlen(skb) - header_len : 0; const struct skb_shared_info *shi = skb_shinfo(skb); struct sk_buff *frag_iter; sg_init_table(&sg, 1); sg_set_buf(&sg, ((u8 *) tp) + header_len, head_data_len); if (crypto_hash_update(desc, &sg, head_data_len)) return 1; for (i = 0; i < shi->nr_frags; ++i) { const struct skb_frag_struct *f = &shi->frags[i]; unsigned int offset = f->page_offset; struct page *page = skb_frag_page(f) + (offset >> PAGE_SHIFT); sg_set_page(&sg, page, skb_frag_size(f), offset_in_page(offset)); if (crypto_hash_update(desc, &sg, skb_frag_size(f))) return 1; } skb_walk_frags(skb, frag_iter) if (tcp_md5_hash_skb_data(hp, frag_iter, 0)) return 1; return 0; } EXPORT_SYMBOL(tcp_md5_hash_skb_data); int tcp_md5_hash_key(struct tcp_md5sig_pool *hp, const struct tcp_md5sig_key *key) { struct scatterlist sg; sg_init_one(&sg, key->key, key->keylen); return crypto_hash_update(&hp->md5_desc, &sg, key->keylen); } EXPORT_SYMBOL(tcp_md5_hash_key); #endif void tcp_done(struct sock *sk) { struct request_sock *req = tcp_sk(sk)->fastopen_rsk; if (sk->sk_state == TCP_SYN_SENT || sk->sk_state == TCP_SYN_RECV) TCP_INC_STATS_BH(sock_net(sk), TCP_MIB_ATTEMPTFAILS); tcp_set_state(sk, TCP_CLOSE); tcp_clear_xmit_timers(sk); if (req != NULL) reqsk_fastopen_remove(sk, req, false); sk->sk_shutdown = SHUTDOWN_MASK; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_state_change(sk); else inet_csk_destroy_sock(sk); } EXPORT_SYMBOL_GPL(tcp_done); int tcp_abort(struct sock *sk, int err) { if (sk->sk_state == TCP_TIME_WAIT) { inet_twsk_put((struct inet_timewait_sock *)sk); return -EOPNOTSUPP; } /* Don't race with userspace socket closes such as tcp_close. */ lock_sock(sk); if (sk->sk_state == TCP_LISTEN) { tcp_set_state(sk, TCP_CLOSE); inet_csk_listen_stop(sk); } /* Don't race with BH socket closes such as inet_csk_listen_stop. */ local_bh_disable(); bh_lock_sock(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_err = err; /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); sk->sk_error_report(sk); if (tcp_need_reset(sk->sk_state)) tcp_send_active_reset(sk, GFP_ATOMIC); tcp_done(sk); } bh_unlock_sock(sk); local_bh_enable(); release_sock(sk); sock_put(sk); return 0; } EXPORT_SYMBOL_GPL(tcp_abort); extern struct tcp_congestion_ops tcp_reno; static __initdata unsigned long thash_entries; static int __init set_thash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &thash_entries); if (ret) return 0; return 1; } __setup("thash_entries=", set_thash_entries); void tcp_init_mem(struct net *net) { unsigned long limit = nr_free_buffer_pages() / 8; limit = max(limit, 128UL); net->ipv4.sysctl_tcp_mem[0] = limit / 4 * 3; net->ipv4.sysctl_tcp_mem[1] = limit; net->ipv4.sysctl_tcp_mem[2] = net->ipv4.sysctl_tcp_mem[0] * 2; } void __init tcp_init(void) { struct sk_buff *skb = NULL; unsigned long limit; int max_rshare, max_wshare, cnt; unsigned int i; BUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb)); percpu_counter_init(&tcp_sockets_allocated, 0); percpu_counter_init(&tcp_orphan_count, 0); tcp_hashinfo.bind_bucket_cachep = kmem_cache_create("tcp_bind_bucket", sizeof(struct inet_bind_bucket), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); /* Size and allocate the main established and bind bucket * hash tables. * * The methodology is similar to that of the buffer cache. */ tcp_hashinfo.ehash = alloc_large_system_hash("TCP established", sizeof(struct inet_ehash_bucket), thash_entries, 17, /* one slot per 128 KB of memory */ 0, NULL, &tcp_hashinfo.ehash_mask, 0, thash_entries ? 0 : 512 * 1024); for (i = 0; i <= tcp_hashinfo.ehash_mask; i++) { INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i); INIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].twchain, i); } if (inet_ehash_locks_alloc(&tcp_hashinfo)) panic("TCP: failed to alloc ehash_locks"); tcp_hashinfo.bhash = alloc_large_system_hash("TCP bind", sizeof(struct inet_bind_hashbucket), tcp_hashinfo.ehash_mask + 1, 17, /* one slot per 128 KB of memory */ 0, &tcp_hashinfo.bhash_size, NULL, 0, 64 * 1024); tcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size; for (i = 0; i < tcp_hashinfo.bhash_size; i++) { spin_lock_init(&tcp_hashinfo.bhash[i].lock); INIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain); } cnt = tcp_hashinfo.ehash_mask + 1; tcp_death_row.sysctl_max_tw_buckets = cnt / 2; sysctl_tcp_max_orphans = cnt / 2; sysctl_max_syn_backlog = max(128, cnt / 256); tcp_init_mem(&init_net); /* Set per-socket limits to no more than 1/128 the pressure threshold */ limit = nr_free_buffer_pages() << (PAGE_SHIFT - 7); max_wshare = min(4UL*1024*1024, limit); max_rshare = min(6UL*1024*1024, limit); sysctl_tcp_wmem[0] = SK_MEM_QUANTUM; sysctl_tcp_wmem[1] = 16*1024; sysctl_tcp_wmem[2] = max(64*1024, max_wshare); sysctl_tcp_rmem[0] = SK_MEM_QUANTUM; sysctl_tcp_rmem[1] = 87380; sysctl_tcp_rmem[2] = max(87380, max_rshare); pr_info("Hash tables configured (established %u bind %u)\n", tcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size); tcp_metrics_init(); tcp_register_congestion_control(&tcp_reno); tcp_tasklet_init(); } static int tcp_is_local(struct net *net, __be32 addr) { struct rtable *rt; struct flowi4 fl4 = { .daddr = addr }; rt = ip_route_output_key(net, &fl4); if (IS_ERR_OR_NULL(rt)) return 0; return rt->dst.dev && (rt->dst.dev->flags & IFF_LOOPBACK); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static int tcp_is_local6(struct net *net, struct in6_addr *addr) { struct rt6_info *rt6 = rt6_lookup(net, addr, addr, 0, 0); return rt6 && rt6->dst.dev && (rt6->dst.dev->flags & IFF_LOOPBACK); } #endif /* * tcp_nuke_addr - destroy all sockets on the given local address * if local address is the unspecified address (0.0.0.0 or ::), destroy all * sockets with local addresses that are not configured. */ int tcp_nuke_addr(struct net *net, struct sockaddr *addr) { int family = addr->sa_family; unsigned int bucket; /*mtk_net:debug log*/ int count = 0; struct in_addr *in; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) struct in6_addr *in6 = NULL ; #endif if (family == AF_INET) { in = &((struct sockaddr_in *)addr)->sin_addr; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) } else if (family == AF_INET6) { in6 = &((struct sockaddr_in6 *)addr)->sin6_addr; #endif } else { return -EAFNOSUPPORT; } /*mtk_net:debug log*/ printk(KERN_INFO "[mtk_net][tcp]tcp_nuke_addr: tcp_hashinfo.ehash_mask = %d\n",tcp_hashinfo.ehash_mask); for (bucket = 0; bucket <= tcp_hashinfo.ehash_mask; bucket++) { struct hlist_nulls_node *node; struct sock *sk; spinlock_t *lock = inet_ehash_lockp(&tcp_hashinfo, bucket); restart: spin_lock_bh(lock); sk_nulls_for_each(sk, node, &tcp_hashinfo.ehash[bucket].chain) { struct inet_sock *inet = inet_sk(sk); if (sysctl_ip_dynaddr && sk->sk_state == TCP_SYN_SENT) continue; if (sock_flag(sk, SOCK_DEAD)) continue; if (family == AF_INET) { __be32 s4 = inet->inet_rcv_saddr; if (s4 == LOOPBACK4_IPV6) continue; if (in->s_addr != s4 && !(in->s_addr == INADDR_ANY && !tcp_is_local(net, s4))) continue; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) if (family == AF_INET6) { struct in6_addr *s6; if (!inet->pinet6) continue; s6 = &inet->pinet6->rcv_saddr; if (ipv6_addr_type(s6) == IPV6_ADDR_MAPPED) continue; if (!ipv6_addr_equal(in6, s6) && !(ipv6_addr_equal(in6, &in6addr_any) && !tcp_is_local6(net, s6))) continue; } #endif sock_hold(sk); spin_unlock_bh(lock); local_bh_disable(); bh_lock_sock(sk); sk->sk_err = ETIMEDOUT; sk->sk_error_report(sk); count++; /*mtk_net: skip closed sk*/ if(sk->sk_state != TCP_CLOSE && sk->sk_shutdown != SHUTDOWN_MASK) { printk(KERN_INFO "[mtk_net][tcp]skip ALPS01866438 Google Issue!\n"); } tcp_done(sk); bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); goto restart; } spin_unlock_bh(lock); } printk(KERN_INFO "[mtk_net][tcp]tcp_nuke_addr : count = %d\n",count); return 0; }
DKingCN/android_kernel_jiayu_s3_h560
net/ipv4/tcp.c
C
gpl-2.0
94,926
# Copyright 2015 Miguel Angel Ajo Pelayo <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # class NoDefaultUnits(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
KiCad/kicad-python
kicad/exceptions.py
Python
gpl-2.0
936
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2022 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ /// Mandatory fields for change template class /// since version 0.83 class ChangeTemplateMandatoryField extends ITILTemplateMandatoryField { // From CommonDBChild public static $itemtype = 'ChangeTemplate'; public static $items_id = 'changetemplates_id'; public static $itiltype = 'Change'; }
stweil/glpi
src/ChangeTemplateMandatoryField.php
PHP
gpl-2.0
1,476
<?php class FordefprobleMapBuilder { const CLASS_NAME = 'lib.model.map.FordefprobleMapBuilder'; private $dbMap; public function isBuilt() { return ($this->dbMap !== null); } public function getDatabaseMap() { return $this->dbMap; } public function doBuild() { $this->dbMap = Propel::getDatabaseMap('propel'); $tMap = $this->dbMap->addTable('fordefproble'); $tMap->setPhpName('Fordefproble'); $tMap->setUseIdGenerator(true); $tMap->setPrimaryKeyMethodInfo('fordefproble_SEQ'); $tMap->addColumn('CODPRO', 'Codpro', 'string', CreoleTypes::VARCHAR, true, 4); $tMap->addColumn('NOMPRO', 'Nompro', 'string', CreoleTypes::VARCHAR, false, 4000); $tMap->addColumn('PROGRA', 'Progra', 'string', CreoleTypes::VARCHAR, false, 4000); $tMap->addColumn('PLAECO', 'Plaeco', 'string', CreoleTypes::VARCHAR, false, 4000); $tMap->addColumn('OBJEST', 'Objest', 'string', CreoleTypes::VARCHAR, false, 4000); $tMap->addColumn('PLAGOB', 'Plagob', 'string', CreoleTypes::VARCHAR, false, 4000); $tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null); } }
cidesa/roraima
lib/model/map/FordefprobleMapBuilder.php
PHP
gpl-2.0
1,118
// ALIADA - Automatic publication under Linked Data paradigm // of library and museum data // // Component: aliada-rdfizer // Responsible: ALIADA Consortium package eu.aliada.rdfizer.datasource.rdbms; import java.util.List; import org.springframework.data.repository.PagingAndSortingRepository; /** * Job instance repository. * Provides CRUD access to job instance entity. * * @author Andrea Gazzarini * @since 1.0 */ public interface ValidationMessageRepository extends PagingAndSortingRepository<ValidationMessage, Integer> { List<ValidationMessage> findByJobId(Integer jobid); }
ALIADA/aliada-tool
aliada/aliada-rdfizer/src/main/java/eu/aliada/rdfizer/datasource/rdbms/ValidationMessageRepository.java
Java
gpl-3.0
600
#ifndef __njl1_solve_mf_h__ #define __njl1_solve_mf_h__ /////// suffixe _der : use of derivatives ////// suffixe _plot : if the minim or root routine returns an error, the func (and its deriv) are plotted /// min and root finding 1D : //// bound(0,0) : low bound //// bound(0,1) : high bound /////////// Resolution of MF equations: /////// Min Gp ( % m , T , mu ) void mingp_njl1_m ( Param * P , Var * V , gsl_matrix * bound); void mingp_njl1_T ( Param * P , Var * V , gsl_matrix * bound); void mingp_njl1_mu ( Param * P , Var * V , gsl_matrix * bound); /////// Root gm ( % m , T , mu ) void rootgm_njl1_m ( Param * P , Var * V , gsl_matrix * bound); void rootgm_njl1_T ( Param * P , Var * V , gsl_matrix * bound); void rootgm_njl1_mu ( Param * P , Var * V , gsl_matrix * bound); void rootgm_njl1_m_der ( Param * P , Var * V , gsl_matrix * bound); void rootgm_njl1_T_der ( Param * P , Var * V , gsl_matrix * bound); void rootgm_njl1_mu_der ( Param * P , Var * V , gsl_matrix * bound); /////////// The following routines plot the function to be minimized or rooted ////////// only if the rooting or minimizing routine did converge on a boundary void mingp_njl1_m_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void mingp_njl1_T_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void mingp_njl1_mu_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_m_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_T_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_mu_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_m_der_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_T_der_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_mu_der_plot ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); /////////// The following routines plot the function to be minimized or rooted ////////// always void mingp_njl1_m_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void mingp_njl1_T_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void mingp_njl1_mu_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_m_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_T_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_mu_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_m_der_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_T_der_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); void rootgm_njl1_mu_der_plot_always ( Param *P , Var *V , gsl_matrix *bound, char *namefile, char *comment); #endif
AlexandreBiguet/NJLlikeModels
legacy/programs/njl-1/njl1/solve_mf.h
C
gpl-3.0
3,190
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QPAGESETUPDIALOG_H #define QPAGESETUPDIALOG_H #include <QtGui/qabstractpagesetupdialog.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_PRINTDIALOG class QPageSetupDialogPrivate; class Q_GUI_EXPORT QPageSetupDialog : public QAbstractPageSetupDialog { Q_OBJECT Q_DECLARE_PRIVATE(QPageSetupDialog) Q_ENUMS(PageSetupDialogOption) Q_PROPERTY(PageSetupDialogOptions options READ options WRITE setOptions) public: enum PageSetupDialogOption { None = 0x00000000, // internal DontUseSheet = 0x00000001, OwnsPrinter = 0x80000000 // internal }; Q_DECLARE_FLAGS(PageSetupDialogOptions, PageSetupDialogOption) explicit QPageSetupDialog(QPrinter *printer, QWidget *parent = 0); explicit QPageSetupDialog(QWidget *parent = 0); // obsolete void addEnabledOption(PageSetupDialogOption option); void setEnabledOptions(PageSetupDialogOptions options); PageSetupDialogOptions enabledOptions() const; bool isOptionEnabled(PageSetupDialogOption option) const; void setOption(PageSetupDialogOption option, bool on = true); bool testOption(PageSetupDialogOption option) const; void setOptions(PageSetupDialogOptions options); PageSetupDialogOptions options() const; #if defined(Q_WS_MAC) || defined(Q_OS_WIN) virtual void setVisible(bool visible); #endif virtual int exec(); #ifdef Q_NO_USING_KEYWORD #ifndef Q_QDOC void open() { QDialog::open(); } #endif #else using QDialog::open; #endif void open(QObject *receiver, const char *member); #ifdef qdoc QPrinter *printer(); #endif }; #endif // QT_NO_PRINTDIALOG QT_END_NAMESPACE QT_END_HEADER #endif // QPAGESETUPDIALOG_H
JimmyLzy/MusicGame
Assets/Plugins/AudioProcessorPlugin.bundle/Contents/Resources/gaia2/QtCore/QtGui.framework/Versions/Current/Headers/qpagesetupdialog.h
C
gpl-3.0
3,771
/* * Copyright (C) 2011 Whisper Systems * * 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/>. */ package org.thoughtcrime.securesms; import android.animation.Animator; import android.app.KeyguardManager; import android.content.Context; import android.content.Intent; import android.graphics.PorterDuff; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.InputType; import android.text.SpannableString; import android.text.Spanned; import android.text.style.RelativeSizeSpan; import android.text.style.TypefaceSpan; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.BounceInterpolator; import android.view.animation.TranslateAnimation; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.widget.Toolbar; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricManager.Authenticators; import androidx.biometric.BiometricPrompt; import org.signal.core.util.ThreadUtil; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.animation.AnimationCompleteListener; import org.thoughtcrime.securesms.components.AnimatingToggle; import org.thoughtcrime.securesms.crypto.InvalidPassphraseException; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.crypto.MasterSecretUtil; import org.thoughtcrime.securesms.logsubmit.SubmitDebugLogActivity; import org.thoughtcrime.securesms.util.CommunicationActions; import org.thoughtcrime.securesms.util.DynamicIntroTheme; import org.thoughtcrime.securesms.util.DynamicLanguage; import org.thoughtcrime.securesms.util.SupportEmailUtil; import org.thoughtcrime.securesms.util.TextSecurePreferences; /** * Activity that prompts for a user's passphrase. * * @author Moxie Marlinspike */ public class PassphrasePromptActivity extends PassphraseActivity { private static final String TAG = Log.tag(PassphrasePromptActivity.class); private static final int BIOMETRIC_AUTHENTICATORS = Authenticators.BIOMETRIC_STRONG | Authenticators.BIOMETRIC_WEAK; private static final int ALLOWED_AUTHENTICATORS = BIOMETRIC_AUTHENTICATORS | Authenticators.DEVICE_CREDENTIAL; private static final short AUTHENTICATE_REQUEST_CODE = 1007; private static final String BUNDLE_ALREADY_SHOWN = "bundle_already_shown"; public static final String FROM_FOREGROUND = "from_foreground"; private DynamicIntroTheme dynamicTheme = new DynamicIntroTheme(); private DynamicLanguage dynamicLanguage = new DynamicLanguage(); private View passphraseAuthContainer; private ImageView fingerprintPrompt; private TextView lockScreenButton; private EditText passphraseText; private ImageButton showButton; private ImageButton hideButton; private AnimatingToggle visibilityToggle; private BiometricManager biometricManager; private BiometricPrompt biometricPrompt; private BiometricPrompt.PromptInfo biometricPromptInfo; private boolean authenticated; private boolean hadFailure; private boolean alreadyShown; private final Runnable resumeScreenLockRunnable = () -> { resumeScreenLock(!alreadyShown); alreadyShown = true; }; @Override public void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate()"); dynamicTheme.onCreate(this); dynamicLanguage.onCreate(this); super.onCreate(savedInstanceState); setContentView(R.layout.prompt_passphrase_activity); initializeResources(); alreadyShown = (savedInstanceState != null && savedInstanceState.getBoolean(BUNDLE_ALREADY_SHOWN)) || getIntent().getBooleanExtra(FROM_FOREGROUND, false); } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(BUNDLE_ALREADY_SHOWN, alreadyShown); } @Override public void onResume() { super.onResume(); dynamicTheme.onResume(this); dynamicLanguage.onResume(this); setLockTypeVisibility(); if (TextSecurePreferences.isScreenLockEnabled(this) && !authenticated && !hadFailure) { ThreadUtil.postToMain(resumeScreenLockRunnable); } hadFailure = false; fingerprintPrompt.setImageResource(R.drawable.ic_fingerprint_white_48dp); fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.signal_accent_primary), PorterDuff.Mode.SRC_IN); } @Override public void onPause() { super.onPause(); ThreadUtil.cancelRunnableOnMain(resumeScreenLockRunnable); biometricPrompt.cancelAuthentication(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = this.getMenuInflater(); menu.clear(); inflater.inflate(R.menu.passphrase_prompt, menu); super.onCreateOptionsMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); if (item.getItemId() == R.id.menu_submit_debug_logs) { handleLogSubmit(); return true; } else if (item.getItemId() == R.id.menu_contact_support) { sendEmailToSupport(); return true; } return false; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode != AUTHENTICATE_REQUEST_CODE) return; if (resultCode == RESULT_OK) { handleAuthenticated(); } else { Log.w(TAG, "Authentication failed"); hadFailure = true; } } private void handleLogSubmit() { Intent intent = new Intent(this, SubmitDebugLogActivity.class); startActivity(intent); } private void handlePassphrase() { try { Editable text = passphraseText.getText(); String passphrase = (text == null ? "" : text.toString()); MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(this, passphrase); setMasterSecret(masterSecret); } catch (InvalidPassphraseException ipe) { passphraseText.setText(""); passphraseText.setError( getString(R.string.PassphrasePromptActivity_invalid_passphrase_exclamation)); } } private void handleAuthenticated() { try { authenticated = true; MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(this, MasterSecretUtil.UNENCRYPTED_PASSPHRASE); setMasterSecret(masterSecret); } catch (InvalidPassphraseException e) { throw new AssertionError(e); } } private void setPassphraseVisibility(boolean visibility) { int cursorPosition = passphraseText.getSelectionStart(); if (visibility) { passphraseText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { passphraseText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } passphraseText.setSelection(cursorPosition); } private void initializeResources() { ImageButton okButton = findViewById(R.id.ok_button); Toolbar toolbar = findViewById(R.id.toolbar); showButton = findViewById(R.id.passphrase_visibility); hideButton = findViewById(R.id.passphrase_visibility_off); visibilityToggle = findViewById(R.id.button_toggle); passphraseText = findViewById(R.id.passphrase_edit); passphraseAuthContainer = findViewById(R.id.password_auth_container); fingerprintPrompt = findViewById(R.id.fingerprint_auth_container); lockScreenButton = findViewById(R.id.lock_screen_auth_container); biometricManager = BiometricManager.from(this); biometricPrompt = new BiometricPrompt(this, new BiometricAuthenticationListener()); biometricPromptInfo = new BiometricPrompt.PromptInfo .Builder() .setAllowedAuthenticators(ALLOWED_AUTHENTICATORS) .setTitle(getString(R.string.PassphrasePromptActivity_unlock_signal)) .build(); setSupportActionBar(toolbar); getSupportActionBar().setTitle(""); SpannableString hint = new SpannableString(" " + getString(R.string.PassphrasePromptActivity_enter_passphrase)); hint.setSpan(new RelativeSizeSpan(0.9f), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); hint.setSpan(new TypefaceSpan("sans-serif"), 0, hint.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); passphraseText.setHint(hint); okButton.setOnClickListener(new OkButtonClickListener()); showButton.setOnClickListener(new ShowButtonOnClickListener()); hideButton.setOnClickListener(new HideButtonOnClickListener()); passphraseText.setOnEditorActionListener(new PassphraseActionListener()); passphraseText.setImeActionLabel(getString(R.string.prompt_passphrase_activity__unlock), EditorInfo.IME_ACTION_DONE); fingerprintPrompt.setImageResource(R.drawable.ic_fingerprint_white_48dp); fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.core_ultramarine), PorterDuff.Mode.SRC_IN); lockScreenButton.setOnClickListener(v -> resumeScreenLock(true)); } private void setLockTypeVisibility() { if (TextSecurePreferences.isScreenLockEnabled(this)) { passphraseAuthContainer.setVisibility(View.GONE); fingerprintPrompt.setVisibility(biometricManager.canAuthenticate(BIOMETRIC_AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS ? View.VISIBLE : View.GONE); lockScreenButton.setVisibility(View.VISIBLE); } else { passphraseAuthContainer.setVisibility(View.VISIBLE); fingerprintPrompt.setVisibility(View.GONE); lockScreenButton.setVisibility(View.GONE); } } private void resumeScreenLock(boolean force) { KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); assert keyguardManager != null; if (!keyguardManager.isKeyguardSecure()) { Log.w(TAG ,"Keyguard not secure..."); handleAuthenticated(); return; } if (Build.VERSION.SDK_INT != 29 && biometricManager.canAuthenticate(ALLOWED_AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS) { if (force) { Log.i(TAG, "Listening for biometric authentication..."); biometricPrompt.authenticate(biometricPromptInfo); } else { Log.i(TAG, "Skipping show system biometric dialog unless forced"); } } else if (Build.VERSION.SDK_INT >= 21) { if (force) { Log.i(TAG, "firing intent..."); Intent intent = keyguardManager.createConfirmDeviceCredentialIntent(getString(R.string.PassphrasePromptActivity_unlock_signal), ""); startActivityForResult(intent, AUTHENTICATE_REQUEST_CODE); } else { Log.i(TAG, "Skipping firing intent unless forced"); } } else { Log.w(TAG, "Not compatible..."); handleAuthenticated(); } } private void sendEmailToSupport() { String body = SupportEmailUtil.generateSupportEmailBody(this, R.string.PassphrasePromptActivity_signal_android_lock_screen, null, null); CommunicationActions.openEmail(this, SupportEmailUtil.getSupportEmailAddress(this), getString(R.string.PassphrasePromptActivity_signal_android_lock_screen), body); } private class PassphraseActionListener implements TextView.OnEditorActionListener { @Override public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent keyEvent) { if ((keyEvent == null && actionId == EditorInfo.IME_ACTION_DONE) || (keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_DOWN && (actionId == EditorInfo.IME_NULL))) { handlePassphrase(); return true; } else if (keyEvent != null && keyEvent.getAction() == KeyEvent.ACTION_UP && actionId == EditorInfo.IME_NULL) { return true; } return false; } } private class OkButtonClickListener implements OnClickListener { @Override public void onClick(View v) { handlePassphrase(); } } private class ShowButtonOnClickListener implements OnClickListener { @Override public void onClick(View v) { visibilityToggle.display(hideButton); setPassphraseVisibility(true); } } private class HideButtonOnClickListener implements OnClickListener { @Override public void onClick(View v) { visibilityToggle.display(showButton); setPassphraseVisibility(false); } } @Override protected void cleanup() { this.passphraseText.setText(""); System.gc(); } private class BiometricAuthenticationListener extends BiometricPrompt.AuthenticationCallback { @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errorString) { Log.w(TAG, "Authentication error: " + errorCode); hadFailure = true; if (errorCode != BiometricPrompt.ERROR_CANCELED && errorCode != BiometricPrompt.ERROR_USER_CANCELED) { onAuthenticationFailed(); } } @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { Log.i(TAG, "onAuthenticationSucceeded"); fingerprintPrompt.setImageResource(R.drawable.ic_check_white_48dp); fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.green_500), PorterDuff.Mode.SRC_IN); fingerprintPrompt.animate().setInterpolator(new BounceInterpolator()).scaleX(1.1f).scaleY(1.1f).setDuration(500).setListener(new AnimationCompleteListener() { @Override public void onAnimationEnd(Animator animation) { handleAuthenticated(); } }).start(); } @Override public void onAuthenticationFailed() { Log.w(TAG, "onAuthenticationFailed()"); fingerprintPrompt.setImageResource(R.drawable.ic_close_white_48dp); fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.red_500), PorterDuff.Mode.SRC_IN); TranslateAnimation shake = new TranslateAnimation(0, 30, 0, 0); shake.setDuration(50); shake.setRepeatCount(7); shake.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { fingerprintPrompt.setImageResource(R.drawable.ic_fingerprint_white_48dp); fingerprintPrompt.getBackground().setColorFilter(getResources().getColor(R.color.signal_accent_primary), PorterDuff.Mode.SRC_IN); } @Override public void onAnimationRepeat(Animation animation) {} }); fingerprintPrompt.startAnimation(shake); } } }
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/PassphrasePromptActivity.java
Java
gpl-3.0
16,513
/* * This file is part of AtlasMapper server and clients. * * Copyright (C) 2011 Australian Institute of Marine Science * * Contact: Gael Lafond <[email protected]> * * 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/>. */ package au.gov.aims.atlasmapperserver.layerConfig; import au.gov.aims.atlasmapperserver.ConfigManager; import au.gov.aims.atlasmapperserver.annotation.ConfigField; public class ArcGISMapServerLayerConfig extends AbstractLayerConfig { @ConfigField private String arcGISPath; public ArcGISMapServerLayerConfig(ConfigManager configManager) { super(configManager); } public String getArcGISPath() { return this.arcGISPath; } public void setArcGISPath(String arcGISPath) { this.arcGISPath = arcGISPath; } }
windrobin/atlasmapper
src/main/java/au/gov/aims/atlasmapperserver/layerConfig/ArcGISMapServerLayerConfig.java
Java
gpl-3.0
1,361
package net.shadowmage.ancientwarfare.npc.entity; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.DamageSource; import net.minecraft.world.World; import net.shadowmage.ancientwarfare.core.config.AWLog; import net.shadowmage.ancientwarfare.core.util.BlockPosition; import net.shadowmage.ancientwarfare.npc.AncientWarfareNPC; import net.shadowmage.ancientwarfare.npc.ai.NpcAI; import net.shadowmage.ancientwarfare.npc.ai.owned.NpcAIPlayerOwnedRideHorse; import net.shadowmage.ancientwarfare.npc.config.AWNPCStatics; import net.shadowmage.ancientwarfare.npc.entity.faction.NpcFaction; import net.shadowmage.ancientwarfare.npc.npc_command.NpcCommand.Command; import net.shadowmage.ancientwarfare.npc.npc_command.NpcCommand.CommandType; import net.shadowmage.ancientwarfare.npc.orders.UpkeepOrder; import net.shadowmage.ancientwarfare.npc.tile.TileTownHall; import java.util.List; public abstract class NpcPlayerOwned extends NpcBase implements IKeepFood{ public boolean isAlarmed = false; public boolean deathNotifiedTownhall = false; private Command playerIssuedCommand;//TODO load/save private int foodValueRemaining = 0; protected NpcAIPlayerOwnedRideHorse horseAI; private BlockPosition townHallPosition; private BlockPosition upkeepAutoBlock; public NpcPlayerOwned(World par1World) { super(par1World); } @Override public final int getMaxSafePointTries() { return super.getMaxSafePointTries() - 1; } @Override public void onDeath(DamageSource source) { if (!worldObj.isRemote) { if (horseAI != null) { horseAI.onKilled(); } validateTownHallPosition(); TileTownHall townHall = getTownHall(); if (townHall != null) { deathNotifiedTownhall = true; townHall.handleNpcDeath(this, source); } } super.onDeath(source); } @Override public final int getArmorValueOverride() { return -1; } @Override public final int getAttackDamageOverride() { return -1; } public void setTownHallPosition(BlockPosition pos) { if (pos != null) { this.townHallPosition = pos.copy(); } else { this.townHallPosition = null; } } @Override public BlockPosition getTownHallPosition() { return townHallPosition; } public TileTownHall getTownHall() { BlockPosition pos = getTownHallPosition(); if (pos != null) { TileEntity te = worldObj.getTileEntity(pos.x, pos.y, pos.z); if (te instanceof TileTownHall) { return (TileTownHall) te; } } return null; } public void handleTownHallBroadcast(TileTownHall tile, BlockPosition position) { validateTownHallPosition(); BlockPosition pos = getTownHallPosition(); if (pos != null) { double curDist = getDistanceSq(pos.x + 0.5d, pos.y, pos.z + 0.5d); double newDist = getDistanceSq(position.x + 0.5d, position.y, position.z + 0.5d); if (newDist < curDist) { setTownHallPosition(position); if (upkeepAutoBlock == null || upkeepAutoBlock.equals(pos)) { upkeepAutoBlock = position; } } } else { setTownHallPosition(position); if (upkeepAutoBlock == null) { upkeepAutoBlock = position; } } // (un)set alarmed status isAlarmed = getTownHall().alarmActive; } private boolean validateTownHallPosition() { BlockPosition pos = getTownHallPosition(); if (pos == null) { return false; } if (!worldObj.blockExists(pos.x, pos.y, pos.z)) { return true; }//cannot validate, unloaded...assume good TileEntity te = worldObj.getTileEntity(pos.x, pos.y, pos.z); if (te instanceof TileTownHall) { if (hasCommandPermissions(((TileTownHall) te).getOwnerName())) return true; } setTownHallPosition(null); return false; } /** * Returns the currently following player-issues command, or null if none */ public Command getCurrentCommand() { return playerIssuedCommand; } /** * input path from command baton - default implementation for player-owned NPC is to set current command==input command and then let AI do the rest */ public void handlePlayerCommand(Command cmd) { if (cmd != null && cmd.type == CommandType.ATTACK) { Entity e = cmd.getEntityTarget(worldObj); AWLog.logDebug("Handling attack command : " + e); if (e instanceof EntityLivingBase) { EntityLivingBase elb = (EntityLivingBase) e; if (canTarget(elb))//only attacked allowed targets { setAttackTarget(elb); } } cmd = null; } this.setPlayerCommand(cmd); } public void setPlayerCommand(Command cmd) { this.playerIssuedCommand = cmd; } @Override public boolean isHostileTowards(Entity entityTarget) { if (NpcAI.isAlwaysHostileToNpcs(entityTarget)) return true; else if ((entityTarget instanceof NpcPlayerOwned) || (entityTarget instanceof EntityPlayer)) { return !isEntitySameTeamOrFriends(entityTarget); } else if (entityTarget instanceof NpcFaction) { return ((NpcFaction) entityTarget).isHostileTowards(this); // hostility is based on faction standing } else { // TODO // This is for forced inclusions, which we don't currently support in new auto-targeting. This // is complicated because reasons. See comments in the AWNPCStatics class for details. if (!AncientWarfareNPC.statics.autoTargetting) { String n = EntityList.getEntityString(entityTarget); List<String> targets = AncientWarfareNPC.statics.getValidTargetsFor(getNpcType(), getNpcSubType()); if (targets.contains(n)) { return true; } } } return false; } @Override public boolean canTarget(Entity e) { if (isEntitySameTeamOrFriends(e)) return false; // don't let npcs target their own teams npcs/players return e instanceof EntityLivingBase; } @Override public boolean canBeAttackedBy(Entity e) { if (isEntitySameTeamOrFriends(e)) return false; // can only be attacked by different team - prevent friendly fire and neutral infighting return true; } /* protected boolean isHostileTowards(Team team) { Team a = getTeam(); return a != null && !a.isSameTeam(team); } */ @Override public void onWeaponInventoryChanged() { updateTexture(); } @Override public int getFoodRemaining() { return foodValueRemaining; } @Override public void setFoodRemaining(int food) { this.foodValueRemaining = food; } @Override public BlockPosition getUpkeepPoint() { UpkeepOrder order = UpkeepOrder.getUpkeepOrder(upkeepStack); if (order != null) { return order.getUpkeepPosition(); } return upkeepAutoBlock; } @Override public void setUpkeepAutoPosition(BlockPosition pos) { upkeepAutoBlock = pos; } @Override public int getUpkeepBlockSide() { UpkeepOrder order = UpkeepOrder.getUpkeepOrder(upkeepStack); if (order != null) { return order.getUpkeepBlockSide(); } return 0; } @Override public int getUpkeepDimensionId() { UpkeepOrder order = UpkeepOrder.getUpkeepOrder(upkeepStack); if (order != null) { return order.getUpkeepDimension(); } return worldObj.provider.dimensionId; } @Override public int getUpkeepAmount() { UpkeepOrder order = UpkeepOrder.getUpkeepOrder(upkeepStack); if (order != null) { return order.getUpkeepAmount(); } return AWNPCStatics.npcDefaultUpkeepWithdraw; } @Override protected boolean tryCommand(EntityPlayer player) { if (hasCommandPermissions(player.getCommandSenderName())) return super.tryCommand(player); return false; } public boolean withdrawFood(IInventory inventory, int side) { int amount = getUpkeepAmount() - getFoodRemaining(); if (amount <= 0) { return true; } ItemStack stack; int val; int eaten = 0; if (side >= 0 && inventory instanceof ISidedInventory) { int[] ind = ((ISidedInventory) inventory).getAccessibleSlotsFromSide(side); for (int i : ind) { stack = inventory.getStackInSlot(i); val = AncientWarfareNPC.statics.getFoodValue(stack); if (val <= 0) { continue; } while (eaten < amount && stack.stackSize > 0) { eaten += val; stack.stackSize--; inventory.markDirty(); } if (stack.stackSize <= 0) { inventory.setInventorySlotContents(i, null); } } } else { for (int i = 0; i < inventory.getSizeInventory(); i++) { stack = inventory.getStackInSlot(i); val = AncientWarfareNPC.statics.getFoodValue(stack); if (val <= 0) { continue; } while (eaten < amount && stack.stackSize > 0) { eaten += val; stack.stackSize--; inventory.markDirty(); } if (stack.stackSize <= 0) { inventory.setInventorySlotContents(i, null); } } } setFoodRemaining(getFoodRemaining() + eaten); return getFoodRemaining() >= getUpkeepAmount(); } @Override protected boolean interact(EntityPlayer player) { if(getFoodRemaining() < getUpkeepAmount()){ int value = AncientWarfareNPC.statics.getFoodValue(player.getHeldItem()); if(value>0){ if(!worldObj.isRemote){ player.getHeldItem().stackSize--; } foodValueRemaining += value; return true; } } return super.interact(player); } @Override public void onLivingUpdate() { super.onLivingUpdate(); if (foodValueRemaining > 0 && !getSleeping()) { foodValueRemaining--; } } @Override public void travelToDimension(int par1) { this.townHallPosition = null; this.upkeepAutoBlock = null; super.travelToDimension(par1); } @Override public void readEntityFromNBT(NBTTagCompound tag) { super.readEntityFromNBT(tag); foodValueRemaining = tag.getInteger("foodValue"); if (tag.hasKey("command")) { playerIssuedCommand = new Command(tag.getCompoundTag("command")); } if (tag.hasKey("townHall")) { townHallPosition = new BlockPosition(tag.getCompoundTag("townHall")); } if (tag.hasKey("upkeepPos")) { upkeepAutoBlock = new BlockPosition(tag.getCompoundTag("upkeepPos")); } onOrdersInventoryChanged(); } @Override public void writeEntityToNBT(NBTTagCompound tag) { super.writeEntityToNBT(tag); tag.setInteger("foodValue", foodValueRemaining); if (playerIssuedCommand != null) { tag.setTag("command", playerIssuedCommand.writeToNBT(new NBTTagCompound())); } if (townHallPosition != null) { tag.setTag("townHall", townHallPosition.writeToNBT(new NBTTagCompound())); } if (upkeepAutoBlock != null) { tag.setTag("upkeepPos", upkeepAutoBlock.writeToNBT(new NBTTagCompound())); } } }
CosmicDan-Minecraft/AncientWarfare2_CosmicDanFork
src/main/java/net/shadowmage/ancientwarfare/npc/entity/NpcPlayerOwned.java
Java
gpl-3.0
13,150
package main import . "./template_typedef_cplx4" func main() { // this is OK s := NewSin() s.Get_base_value() s.Get_value() s.Get_arith_value() My_func_r(s) Make_Multiplies_double_double_double_double(s, s) z := NewCSin() z.Get_base_value() z.Get_value() z.Get_arith_value() My_func_c(z) Make_Multiplies_complex_complex_complex_complex(z, z) // Here we fail d := Make_Identity_double() My_func_r(d) c := Make_Identity_complex() My_func_c(c) }
DGA-MI-SSI/YaCo
deps/swig-3.0.7/Examples/test-suite/go/template_typedef_cplx4_runme.go
GO
gpl-3.0
467
package org.cell2d.space; import java.awt.Point; import java.util.ArrayList; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.cell2d.CellGame; import org.cell2d.CellVector; import org.cell2d.Direction; import org.cell2d.EventGroup; import org.cell2d.Frac; import org.cell2d.GameState; import org.cell2d.SafeIterator; import org.cell2d.celick.Graphics; /** * <p>A SpaceState is a type of GameState that handles gameplay in a continuous * two-dimensional space. Space in a SpaceState is divided into rectangular * <i>cells</i> of equal width and equal height. A SpaceState automatically * creates more cells as SpaceObjects enter where they would be if they existed. * </p> * * <p>SpaceObjects may be assigned to one SpaceState each in much the same way * that SubThinkers are assigned to Thinkers. Similarly to SubThinkers, the * actual addition or removal of a SpaceObject to or from a SpaceState is * delayed until any and all current iterations over its SpaceThinkers, * SpaceObjects, or MobileObjects, such as the periods during which * MobileObjects move or SpaceThinkers take their time-dependent actions, have * been completed. Multiple delayed instructions may be successfully given to * SpaceStates regarding the same SpaceObject without having to wait until all * iterations have finished.</p> * * <p>SpaceStates use cells to organize SpaceObjects by location, improving the * efficiency of processes like MobileObject movement that are concerned only * with SpaceObjects in a small region of space. For maximum efficiency, cells * should be set to be large enough that SpaceObjects do not change which cells * they are in too frequently, but small enough that not too many SpaceObjects * are in each cell at any one time.</p> * * <p>Like the SpaceThinkers that it uses, a SpaceState has an EventGroup of * <i>before-movement Events</i> that it performs once each frame. A SpaceState * performs these Events at the beginning of its frameActions(). Immediately * afterward, the SpaceState moves each of its MobileObjects by the sum of its * velocity and step multiplied by its time factor, then resets its step to (0, * 0). This, along with manual calls to the MobileObject's doMovement() method, * is when the MobileObject interacts with the solid surfaces of SpaceObjects in * its path if it has Cell2D's standard collision mechanics enabled.</p> * * <p>Viewports may be assigned to one SpaceState each with an integer ID in * the context of that SpaceState. Only one Viewport may be assigned to a * given SpaceState with a given ID at once.</p> * * <p>HUDs may be assigned to a SpaceState to render visuals in front of the * SpaceState's own. Only one HUD may be assigned to a given SpaceState in this * capacity at once. A SpaceState's HUD uses the entire screen as its rendering * region.</p> * * <p>SpaceLayers may be assigned to a SpaceState with an integer ID in the * context of that SpaceState. Only one SpaceLayer may be assigned to a given * SpaceState with a given ID at once. SpaceLayers with higher IDs are rendered * in front of those with lower ones. SpaceLayers with positive IDs are rendered * in front of the SpaceState's SpaceObjects, and SpaceLayers with negative IDs * are rendered behind its SpaceObjects. SpaceLayers may not be assigned with an * ID of 0.</p> * @see SpaceThinker * @see SpaceObject * @see Viewport * @see HUD * @see SpaceLayer * @param <T> The type of CellGame that uses this SpaceState * @param <U> The type of SpaceState that this SpaceState is for SpaceThinker * interaction purposes * @param <V> The type of SpaceThinker that this SpaceState uses * @author Alex Heyman */ public abstract class SpaceState<T extends CellGame, U extends SpaceState<T,U,V>, V extends SpaceThinker<T,U,V>> extends GameState<T,U,V> { /** * <p>A DrawMode is a procedure by which a SpaceState determines the order * in which to draw SpaceObjects with the same draw priority over one * another.</p> * @see SpaceObject * @author Alex Heyman */ public static enum DrawMode { /** * SpaceObjects with the same draw priority are drawn in an arbitrary * order. This is the most efficient DrawMode when the plane of the * level is supposed to be perpendicular to the camera. */ FLAT, /** * SpaceObjects with the same draw priority are drawn with the ones with * higher y-coordinates in front. This creates the illusion that the * camera is looking diagonally down from over the plane of the level. */ OVER, /** * SpaceObjects with the same draw priority are drawn with the ones with * lower y-coordinates in front. This creates the illusion that the * camera is looking diagonally up from under the plane of the level. */ UNDER } private static final Comparator<MobileObject> movementPriorityComparator = (object1, object2) -> { int priorityDiff = object2.movementPriority - object1.movementPriority; return (priorityDiff == 0 ? System.identityHashCode(object1) - System.identityHashCode(object2) : priorityDiff); }; private static final Comparator<MoveEvent> moveComparator = (event1, event2) -> { long metricDiff = event1.metric - event2.metric; if (metricDiff == 0) { int typeDiff = event1.type - event2.type; return (typeDiff == 0 ? System.identityHashCode(event1) - System.identityHashCode(event2) : typeDiff); } return (int)Math.signum(metricDiff); }; private static final Comparator<Hitbox> drawPriorityComparator = (hitbox1, hitbox2) -> { int priorityDiff = hitbox1.drawPriority - hitbox2.drawPriority; return (priorityDiff == 0 ? System.identityHashCode(hitbox1) - System.identityHashCode(hitbox2) : priorityDiff); }; private static class HitboxIteratorData { private final Iterator<Hitbox> iterator; private Hitbox currentHitbox; private HitboxIteratorData(Iterator<Hitbox> iterator, Hitbox currentHitbox) { this.iterator = iterator; this.currentHitbox = currentHitbox; } } private static final Comparator<HitboxIteratorData> flatModeComparator = (data1, data2) -> { return drawPriorityComparator.compare(data1.currentHitbox, data2.currentHitbox); }; private static final Comparator<HitboxIteratorData> overModeComparator = (data1, data2) -> { Hitbox hitbox1 = data1.currentHitbox; Hitbox hitbox2 = data2.currentHitbox; int priorityDiff = hitbox1.drawPriority - hitbox2.drawPriority; if (priorityDiff == 0) { long yDiff = hitbox1.getAbsY() - hitbox2.getAbsY(); return (yDiff == 0 ? System.identityHashCode(hitbox1) - System.identityHashCode(hitbox2) : (int)Math.signum(yDiff)); } return priorityDiff; }; private static final Comparator<HitboxIteratorData> underModeComparator = (data1, data2) -> { Hitbox hitbox1 = data1.currentHitbox; Hitbox hitbox2 = data2.currentHitbox; int priorityDiff = hitbox1.drawPriority - hitbox2.drawPriority; if (priorityDiff == 0) { long yDiff = hitbox2.getAbsY() - hitbox1.getAbsY(); return (yDiff == 0 ? System.identityHashCode(hitbox1) - System.identityHashCode(hitbox2) : (int)Math.signum(yDiff)); } return priorityDiff; }; private final EventGroup<T,U> beforeMovementEvents = new EventGroup<>(); private final Set<SpaceObject> spaceObjects = new HashSet<>(); private int objectIterators = 0; private final Queue<ObjectChange> objectChanges = new LinkedList<>(); private boolean updatingObjects = false; private final SortedSet<MobileObject> mobileObjects = new TreeSet<>(movementPriorityComparator); private int mobileObjectIterators = 0; private final Queue<MobileObjectChange> mobileObjectChanges = new LinkedList<>(); private long cellWidth, cellHeight; private final Map<Point,Cell> cells = new HashMap<>(); private int cellLeft = 0; private int cellRight = 0; private int cellTop = 0; private int cellBottom = 0; private DrawMode drawMode; private Comparator<HitboxIteratorData> drawComparator; private final Map<Integer,Viewport<T,U>> viewports = new HashMap<>(); private HUD hud = null; private final SortedMap<Integer,SpaceLayer> spaceLayers = new TreeMap<>(); /** * Constructs a SpaceState of the specified CellGame with the specified ID. * @param gameClass The Class object representing the type of CellGame that * uses this SpaceState * @param stateClass The Class object representing the type of SpaceState * that this SpaceState is for SpaceThinker interaction purposes * @param subThinkerClass The Class object representing the type of * SpaceThinker that this SpaceState uses * @param game The CellGame to which this SpaceState belongs * @param id This SpaceState's ID * @param cellWidth The width of each of this SpaceState's cells * @param cellHeight The height of each of this SpaceState's cells * @param drawMode This SpaceState's DrawMode */ public SpaceState(Class<T> gameClass, Class<U> stateClass, Class<V> subThinkerClass, T game, int id, long cellWidth, long cellHeight, DrawMode drawMode) { super(gameClass, stateClass, subThinkerClass, game, id); setCellDimensions(cellWidth, cellHeight); setDrawMode(drawMode); } @Override public void addSubThinkerActions(T game, U state, V subThinker) { beforeMovementEvents.add(subThinker.beforeMovement, subThinker.getBeforeMovementPriority()); subThinker.superBeforeMovementEvents = beforeMovementEvents; } @Override public void removeSubThinkerActions(T game, U state, V subThinker) { beforeMovementEvents.remove(subThinker.beforeMovement, subThinker.getBeforeMovementPriority()); subThinker.superBeforeMovementEvents = null; } /** * Returns the EventGroup of this SpaceState's before-movement Events. * @return The EventGroup of this SpaceState's before-movement Events */ public final EventGroup<T,U> getBeforeMovementEvents() { return beforeMovementEvents; } private class Cell { private int x, y; private long left, right, top, bottom; private final Map<HitboxRole,Set<Hitbox>> hitboxes = new EnumMap<>(HitboxRole.class); private Cell(int x, int y) { this.x = x; this.y = y; left = x*cellWidth; right = left + cellWidth; top = y*cellHeight; bottom = top + cellHeight; hitboxes.put(HitboxRole.LOCATOR, new TreeSet<>(drawPriorityComparator)); for (HitboxRole role : EnumSet.complementOf(EnumSet.of(HitboxRole.LOCATOR))) { hitboxes.put(role, new HashSet<>()); } } } private int[] getCellRangeInclusive(long x1, long y1, long x2, long y2) { int[] cellRange = { Frac.intCeil(Frac.div(x1, cellWidth)) - 1, Frac.intCeil(Frac.div(y1, cellHeight)) - 1, Frac.intFloor(Frac.div(x2, cellWidth)), Frac.intFloor(Frac.div(y2, cellHeight))}; return cellRange; } private int[] getCellRangeInclusive(Hitbox hitbox) { return getCellRangeInclusive(hitbox.getLeftEdge(), hitbox.getTopEdge(), hitbox.getRightEdge(), hitbox.getBottomEdge()); } private int[] getCellRangeExclusive(long x1, long y1, long x2, long y2) { int[] cellRange = { Frac.intFloor(Frac.div(x1, cellWidth)), Frac.intFloor(Frac.div(y1, cellHeight)), Frac.intCeil(Frac.div(x2, cellWidth)) - 1, Frac.intCeil(Frac.div(y2, cellHeight)) - 1}; if (cellRange[0] == cellRange[2] + 1) { cellRange[0]--; } if (cellRange[1] == cellRange[3] + 1) { cellRange[1]--; } return cellRange; } private int[] getCellRangeExclusive(Hitbox hitbox) { return getCellRangeExclusive(hitbox.getLeftEdge(), hitbox.getTopEdge(), hitbox.getRightEdge(), hitbox.getBottomEdge()); } private void updateCellRange(Hitbox hitbox) { hitbox.cellRange = getCellRangeInclusive(hitbox); } private class ReadCellRangeIterator implements Iterator<Cell> { private final int left, right, top, bottom; private int xPos, yPos; private Cell nextCell; private ReadCellRangeIterator(int x1, int y1, int x2, int y2) { left = Math.max(x1, cellLeft); right = Math.min(x2, cellRight); top = Math.max(y1, cellTop); bottom = Math.min(y2, cellBottom); xPos = left; yPos = (left > right || top > bottom ? bottom + 1 : top); advance(); } private ReadCellRangeIterator(int[] cellRange) { this(cellRange[0], cellRange[1], cellRange[2], cellRange[3]); } private void advance() { nextCell = null; while (nextCell == null && yPos <= bottom) { nextCell = cells.get(new Point(xPos, yPos)); if (xPos == right) { xPos = left; yPos++; } else { xPos++; } } } @Override public final boolean hasNext() { return nextCell != null; } @Override public final Cell next() { Cell next = nextCell; advance(); return next; } } private class WriteCellRangeIterator implements Iterator<Cell> { private final int[] cellRange; private int xPos, yPos; private WriteCellRangeIterator(int[] cellRange) { this.cellRange = cellRange; xPos = cellRange[0]; yPos = cellRange[1]; } @Override public final boolean hasNext() { return yPos <= cellRange[3]; } @Override public final Cell next() { Point point = new Point(xPos, yPos); Cell next = cells.get(point); if (next == null) { //There needs to be a cell here, but there isn't, so it's time to make one if (cells.isEmpty()) { cellLeft = xPos; cellRight = xPos; cellTop = yPos; cellBottom = yPos; } else { if (xPos < cellLeft) { cellLeft = xPos; } else if (xPos > cellRight) { cellRight = xPos; } if (yPos < cellTop) { cellTop = yPos; } else if (yPos > cellBottom) { cellBottom = yPos; } } next = new Cell(xPos, yPos); cells.put(point, next); } if (xPos == cellRange[2]) { xPos = cellRange[0]; yPos++; } else { xPos++; } return next; } } private List<Cell> getCells(int[] cellRange) { List<Cell> cellList = new ArrayList<>( (cellRange[2] - cellRange[0] + 1)*(cellRange[3] - cellRange[1] + 1)); Iterator<Cell> iterator = new WriteCellRangeIterator(cellRange); while (iterator.hasNext()) { cellList.add(iterator.next()); } return cellList; } /** * Returns the width of each of this SpaceState's cells. * @return The width of each of this SpaceState's cells */ public final long getCellWidth() { return cellWidth; } /** * Returns the height of each of this SpaceState's cells. * @return The height of each of this SpaceState's cells */ public final long getCellHeight() { return cellHeight; } /** * Sets the dimensions of each of this SpaceState's cells to the specified * values. The more SpaceObjects are currently assigned to this SpaceState, * the longer this operation takes, as SpaceObjects need to be reorganized. * @param cellWidth The new width of each of this SpaceState's cells * @param cellHeight The new height of each of this SpaceState's cells */ public final void setCellDimensions(long cellWidth, long cellHeight) { if (cellWidth <= 0) { throw new RuntimeException("Attempted to give a SpaceState a non-positive cell width (about " + Frac.toDouble(cellWidth) + " fracunits)"); } if (cellHeight <= 0) { throw new RuntimeException("Attempted to give a SpaceState a non-positive cell height (about " + Frac.toDouble(cellHeight) + " fracunits)"); } cells.clear(); this.cellWidth = cellWidth; this.cellHeight = cellHeight; if (!spaceObjects.isEmpty()) { for (SpaceObject object : spaceObjects) { object.addCellData(); } } } /** * Removes any cells that no longer have SpaceObjects in them, freeing up * the memory that they occupied. The more cells this SpaceState has, the * longer this operation takes. */ public final void clearEmptyCells() { boolean firstCell = true; Iterator<Cell> iterator = cells.values().iterator(); while (iterator.hasNext()) { Cell cell = iterator.next(); boolean cellIsEmpty = true; for (HitboxRole role : HitboxRole.values()) { if (!cell.hitboxes.get(role).isEmpty()) { cellIsEmpty = false; break; } } if (cellIsEmpty) { iterator.remove(); } else if (firstCell) { firstCell = false; cellLeft = cell.x; cellRight = cell.x; cellTop = cell.y; cellBottom = cell.y; } else { if (cell.x < cellLeft) { cellLeft = cell.x; } else if (cell.x > cellRight) { cellRight = cell.x; } if (cell.y < cellTop) { cellTop = cell.y; } else if (cell.y > cellBottom) { cellBottom = cell.y; } } } } /** * Returns this SpaceState's DrawMode. * @return This SpaceState's DrawMode */ public final DrawMode getDrawMode() { return drawMode; } /** * Sets this SpaceState's DrawMode. * @param drawMode The new DrawMode */ public final void setDrawMode(DrawMode drawMode) { this.drawMode = drawMode; switch (drawMode) { case FLAT: drawComparator = flatModeComparator; break; case OVER: drawComparator = overModeComparator; break; case UNDER: drawComparator = underModeComparator; break; } } /** * Loads the specified Area about the specified origin point. * @param origin The origin point about which to load the Area * @param area The Area to load */ public final void loadArea(CellVector origin, Area<T,U> area) { loadArea(origin.getX(), origin.getY(), area); } /** * Loads the specified Area about the specified origin point. * @param originX The x-coordinate of the origin point about which to load * the Area * @param originY The y-coordinate of the origin point about which to load * the Area * @param area The Area to load */ public final void loadArea(long originX, long originY, Area<T,U> area) { for (SpaceObject object : area.load(getGame(), getThis())) { if (object.state == null && object.newState == null) { object.changePosition(originX, originY); object.newState = this; objectChanges.add(new ObjectChange(object, this)); } } updateObjects(); } final void updateCells(Hitbox hitbox) { int[] oldRange = hitbox.cellRange; updateCellRange(hitbox); int[] newRange = hitbox.cellRange; if (oldRange[0] != newRange[0] || oldRange[1] != newRange[1] || oldRange[2] != newRange[2] || oldRange[3] != newRange[3]) { Iterator<Cell> iterator = new WriteCellRangeIterator(oldRange); while (iterator.hasNext()) { Cell cell = iterator.next(); for (HitboxRole role : HitboxRole.values()) { if (hitbox.roles.contains(role)) { cell.hitboxes.get(role).remove(hitbox); } } } iterator = new WriteCellRangeIterator(newRange); while (iterator.hasNext()) { Cell cell = iterator.next(); for (HitboxRole role : HitboxRole.values()) { if (hitbox.roles.contains(role)) { cell.hitboxes.get(role).add(hitbox); } } } } } final void addHitbox(Hitbox hitbox, HitboxRole role) { if (hitbox.numCellRoles == 0) { updateCellRange(hitbox); } hitbox.numCellRoles++; Iterator<Cell> iterator = new WriteCellRangeIterator(hitbox.cellRange); while (iterator.hasNext()) { iterator.next().hitboxes.get(role).add(hitbox); } } final void removeHitbox(Hitbox hitbox, HitboxRole role) { Iterator<Cell> iterator = new WriteCellRangeIterator(hitbox.cellRange); while (iterator.hasNext()) { iterator.next().hitboxes.get(role).remove(hitbox); } hitbox.numCellRoles--; if (hitbox.numCellRoles == 0) { hitbox.cellRange = null; } } final void setLocatorHitboxDrawPriority(Hitbox hitbox, int drawPriority) { List<Cell> cellList = getCells(hitbox.cellRange); for (Cell cell : cellList) { cell.hitboxes.get(HitboxRole.LOCATOR).remove(hitbox); } hitbox.drawPriority = drawPriority; for (Cell cell : cellList) { cell.hitboxes.get(HitboxRole.LOCATOR).add(hitbox); } } /** * Returns the number of SpaceObjects that are assigned to this SpaceState. * @return The number of SpaceObjects that are assigned to this SpaceState */ public final int getNumObjects() { return spaceObjects.size(); } private class ObjectIterator implements SafeIterator<SpaceObject> { private boolean stopped = false; private final Iterator<SpaceObject> iterator = spaceObjects.iterator(); private SpaceObject lastObject = null; private ObjectIterator() { objectIterators++; } @Override public final boolean hasNext() { if (stopped) { return false; } boolean hasNext = iterator.hasNext(); if (!hasNext) { stop(); } return hasNext; } @Override public final SpaceObject next() { if (stopped) { throw new NoSuchElementException(); } lastObject = iterator.next(); return lastObject; } @Override public final void remove() { if (!stopped) { if (lastObject == null) { throw new IllegalStateException(); } removeObject(lastObject); lastObject = null; } } @Override public final void stop() { if (!stopped) { stopped = true; objectIterators--; updateObjects(); } } } /** * Returns whether any Iterators over this SpaceState's list of SpaceObjects * are in progress. * @return Whether any Iterators over this SpaceState's list of SpaceObjects * are in progress */ public final boolean iteratingThroughObjects() { return objectIterators > 0; } /** * Returns a new SafeIterator over this SpaceState's list of SpaceObjects. * @return A new SafeIterator over this SpaceState's list of SpaceObjects */ public final SafeIterator<SpaceObject> objectIterator() { return new ObjectIterator(); } private static class ObjectChange { private boolean made = false; private final SpaceObject object; private final SpaceState newState; private ObjectChange(SpaceObject object, SpaceState newState) { this.object = object; this.newState = newState; } } /** * Adds the specified SpaceObject to this SpaceState if it is not already * assigned to a SpaceState. * @param object The SpaceObject to be added * @return Whether the addition occurred */ public final boolean addObject(SpaceObject object) { if (object.newState == null) { addObjectChange(object, this); return true; } return false; } /** * Removes the specified SpaceObject from this SpaceState if it is currently * assigned to it. * @param object The SpaceObject to be removed * @return Whether the removal occurred */ public final boolean removeObject(SpaceObject object) { if (object.newState == this) { addObjectChange(object, null); return true; } return false; } /** * Removes from this SpaceState all of the SpaceObjects that are currently * assigned to it. */ public final void clearObjects() { for (SpaceObject object : spaceObjects) { if (object.newState == this) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * inside the specified rectangular region. Removed SpaceObjects may touch * the region's boundary, as long as no part of them lies outside it. * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge */ public final void removeRectangle(long x1, long y1, long x2, long y2) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(x1, y1, x2, y2)); while (iterator.hasNext()) { for (Hitbox locatorHitbox : iterator.next().hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && locatorHitbox.getLeftEdge() >= x1 && locatorHitbox.getRightEdge() <= x2 && locatorHitbox.getTopEdge() >= y1 && locatorHitbox.getBottomEdge() <= y2) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * outside the specified rectangular region. Removed SpaceObjects may touch * the region's boundary, as long as no part of them lies inside it. * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge */ public final void removeOutsideRectangle(long x1, long y1, long x2, long y2) { List<Hitbox> scanned = new ArrayList<>(); for (Cell cell : cells.values()) { if (cell.left < x1 || cell.right > x2 || cell.top < y1 || cell.bottom > y2) { for (Hitbox locatorHitbox : cell.hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && (locatorHitbox.getLeftEdge() >= x2 || locatorHitbox.getRightEdge() <= x1 || locatorHitbox.getTopEdge() >= y2 || locatorHitbox.getBottomEdge() <= y1)) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * to the left of the specified vertical line. Removed SpaceObjects may * touch the line, as long as no part of them lies to the right of it. * @param x The line's x-coordinate */ public final void removeLeftOfLine(long x) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator( cellLeft, cellTop, Frac.intCeil(Frac.div(x, cellWidth)) - 1, cellBottom); while (iterator.hasNext()) { for (Hitbox locatorHitbox : iterator.next().hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && locatorHitbox.getRightEdge() <= x) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * to the right of the specified vertical line. Removed SpaceObjects may * touch the line, as long as no part of them lies to the left of it. * @param x The line's x-coordinate */ public final void removeRightOfLine(long x) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator( Frac.intFloor(Frac.div(x, cellWidth)), cellTop, cellRight, cellBottom); while (iterator.hasNext()) { for (Hitbox locatorHitbox : iterator.next().hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && locatorHitbox.getLeftEdge() >= x) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * above the specified horizontal line. Removed SpaceObjects may touch the * line, as long as no part of them lies below it. * @param y The line's y-coordinate */ public final void removeAboveLine(long y) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator( cellLeft, cellTop, cellRight, Frac.intCeil(Frac.div(y, cellHeight)) - 1); while (iterator.hasNext()) { for (Hitbox locatorHitbox : iterator.next().hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && locatorHitbox.getBottomEdge() <= y) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } /** * Removes from this SpaceState all of its SpaceObjects that lie entirely * below the specified horizontal line. Removed SpaceObjects may touch the * line, as long as no part of them lies above it. * @param y The line's y-coordinate */ public final void removeBelowLine(long y) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator( cellLeft, Frac.intFloor(Frac.div(y, cellHeight)), cellRight, cellBottom); while (iterator.hasNext()) { for (Hitbox locatorHitbox : iterator.next().hitboxes.get(HitboxRole.LOCATOR)) { if (!locatorHitbox.scanned) { SpaceObject object = locatorHitbox.getObject(); if (object.newState == this && locatorHitbox.getTopEdge() >= y) { object.newState = null; objectChanges.add(new ObjectChange(object, null)); } locatorHitbox.scanned = true; } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } updateObjects(); } private void addObjectChange(SpaceObject object, SpaceState newState) { object.newState = newState; ObjectChange change = new ObjectChange(object, newState); if (object.state != null) { object.state.objectChanges.add(change); object.state.updateObjects(); } if (newState != null) { newState.objectChanges.add(change); newState.updateObjects(); } } private void add(SpaceObject object) { spaceObjects.add(object); object.game = getGame(); object.state = this; object.addCellData(); object.addNonCellData(); } private void remove(SpaceObject object) { object.removeData(); spaceObjects.remove(object); object.game = null; object.state = null; } private void updateObjects() { if (objectIterators == 0 && !updatingObjects) { updatingObjects = true; while (!objectChanges.isEmpty()) { ObjectChange change = objectChanges.remove(); if (!change.made) { change.made = true; if (change.object.state != null) { change.object.state.remove(change.object); } if (change.newState != null) { change.newState.add(change.object); } } } updatingObjects = false; } } /** * Returns the number of MobileObjects that are assigned to this SpaceState. * @return The number of MobileObjects that are assigned to this SpaceState */ public final int getNumMobileObjects() { return mobileObjects.size(); } private class MobileObjectIterator implements SafeIterator<MobileObject> { private boolean stopped = false; private final Iterator<MobileObject> iterator = mobileObjects.iterator(); private MobileObject lastObject = null; private MobileObjectIterator() { mobileObjectIterators++; } @Override public final boolean hasNext() { if (stopped) { return false; } boolean hasNext = iterator.hasNext(); if (!hasNext) { stop(); } return hasNext; } @Override public final MobileObject next() { if (stopped) { throw new NoSuchElementException(); } lastObject = iterator.next(); return lastObject; } @Override public final void remove() { if (!stopped) { if (lastObject == null) { throw new IllegalStateException(); } removeObject(lastObject); lastObject = null; } } @Override public final void stop() { if (!stopped) { stopped = true; mobileObjectIterators--; updateMobileObjects(); } } } /** * Returns whether any Iterators over this SpaceState's list of * MobileObjects are in progress. * @return Whether any Iterators over this SpaceState's list of * MobileObjects are in progress */ public final boolean iteratingThroughMobileObjects() { return mobileObjectIterators > 0; } /** * Returns a new SafeIterator over this SpaceState's list of MobileObjects. * @return A new SafeIterator over this SpaceState's list of MobileObjects */ public final SafeIterator<MobileObject> mobileObjectIterator() { return new MobileObjectIterator(); } private static class MobileObjectChange { private boolean made = false; private final boolean changePriority; private final MobileObject object; private final boolean add; private final int movementPriority; private MobileObjectChange(MobileObject object, boolean add) { changePriority = false; this.object = object; this.add = add; movementPriority = 0; } private MobileObjectChange(MobileObject object, int movementPriority) { changePriority = true; this.object = object; add = false; this.movementPriority = movementPriority; } } final void addMobileObject(MobileObject object) { mobileObjectChanges.add(new MobileObjectChange(object, true)); updateMobileObjects(); } final void removeMobileObject(MobileObject object) { mobileObjectChanges.add(new MobileObjectChange(object, false)); updateMobileObjects(); } final void changeMobileObjectMovementPriority(MobileObject object, int movementPriority) { mobileObjectChanges.add(new MobileObjectChange(object, movementPriority)); updateMobileObjects(); } private void updateMobileObjects() { if (mobileObjectIterators == 0) { while (!mobileObjectChanges.isEmpty()) { MobileObjectChange change = mobileObjectChanges.remove(); if (!change.made) { change.made = true; if (change.changePriority) { if (change.object.state == null) { change.object.movementPriority = change.movementPriority; } else { mobileObjects.remove(change.object); change.object.movementPriority = change.movementPriority; mobileObjects.add(change.object); } } else if (change.add) { mobileObjects.add(change.object); } else { mobileObjects.remove(change.object); } } } } } /** * Returns this SpaceState's SpaceObject of the specified class whose center * is nearest to the specified point, or null if this SpaceState has no * SpaceObjects of that class. * @param <O> The subclass of SpaceObject to search for * @param point The point to check distance to * @param cls The Class object that represents the SpaceObject subclass * @return The nearest SpaceObject of the specified class to the specified * point */ public final <O extends SpaceObject> O nearestObject(CellVector point, Class<O> cls) { return nearestObject(point.getX(), point.getY(), cls); } /** * Returns this SpaceState's SpaceObject of the specified class whose center * is nearest to the specified point, or null if this SpaceState has no * SpaceObjects of that class. * @param <O> The subclass of SpaceObject to search for * @param pointX The x-coordinate of the point to check the distance to * @param pointY The y-coordinate of the point to check the distance to * @param cls The Class object that represents the SpaceObject subclass * @return The nearest SpaceObject of the specified class to the specified * point */ public final <O extends SpaceObject> O nearestObject(long pointX, long pointY, Class<O> cls) { O nearest = null; long nearestDistance = -1; for (SpaceObject object : (MobileObject.class.isAssignableFrom(cls) ? mobileObjects : spaceObjects)) { if (cls.isAssignableFrom(object.getClass())) { long distance = CellVector.distanceBetween( pointX, pointY, object.getCenterX(), object.getCenterY()); if (nearestDistance < 0 || distance < nearestDistance) { nearest = cls.cast(object); nearestDistance = distance; } } } return nearest; } /** * Returns whether this SpaceState has any SpaceObjects of the specified * class with their centers within the specified rectangular region. * @param <O> The subclass of SpaceObject to search for * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @param cls The Class object that represents the SpaceObject subclass * @return Whether there are any SpaceObjects of the specified class within * the specified rectangular region */ public final <O extends SpaceObject> boolean objectIsWithinRectangle( long x1, long y1, long x2, long y2, Class<O> cls) { return objectWithinRectangle(x1, y1, x2, y2, cls) != null; } /** * Returns one of this SpaceState's SpaceObjects of the specified class with * its center within the specified rectangular region, or null if there is * none. * @param <O> The subclass of SpaceObject to search for * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @param cls The Class object that represents the SpaceObject subclass * @return A SpaceObject of the specified class within the specified * rectangular region */ public final <O extends SpaceObject> O objectWithinRectangle( long x1, long y1, long x2, long y2, Class<O> cls) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(x1, y1, x2, y2)); while (iterator.hasNext()) { for (Hitbox centerHitbox : iterator.next().hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { if (cls.isAssignableFrom(centerHitbox.getObject().getClass()) && centerHitbox.getAbsX() >= x1 && centerHitbox.getAbsY() >= y1 && centerHitbox.getAbsX() <= x2 && centerHitbox.getAbsY() <= y2) { for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return cls.cast(centerHitbox.getObject()); } centerHitbox.scanned = true; scanned.add(centerHitbox); } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return null; } /** * Returns all of this SpaceState's SpaceObjects of the specified class with * their centers within the specified rectangular region. * @param <O> The subclass of SpaceObject to search for * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class within the * specified rectangular region */ public final <O extends SpaceObject> List<O> objectsWithinRectangle( long x1, long y1, long x2, long y2, Class<O> cls) { List<O> within = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(x1, y1, x2, y2)); while (iterator.hasNext()) { for (Hitbox centerHitbox : iterator.next().hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { centerHitbox.scanned = true; scanned.add(centerHitbox); if (cls.isAssignableFrom(centerHitbox.getObject().getClass()) && centerHitbox.getAbsX() >= x1 && centerHitbox.getAbsY() >= y1 && centerHitbox.getAbsX() <= x2 && centerHitbox.getAbsY() <= y2) { within.add(cls.cast(centerHitbox.getObject())); } } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return within; } /** * Returns this SpaceState's SpaceObject of the specified class within the * specified rectangular region whose center is nearest to the specified * point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param point The point to check the distance to * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class within the specified * rectangular region that is nearest to the specified point */ public final <O extends SpaceObject> O nearestObjectWithinRectangle( CellVector point, long x1, long y1, long x2, long y2, Class<O> cls) { return nearestObjectWithinRectangle(point.getX(), point.getY(), x1, y1, x2, y2, cls); } /** * Returns this SpaceState's SpaceObject of the specified class within the * specified rectangular region whose center is nearest to the specified * point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param pointX The x-coordinate of the point to check the distance to * @param pointY The y-coordinate of the point to check the distance to * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class within the specified * rectangular region that is nearest to the specified point */ public final <O extends SpaceObject> O nearestObjectWithinRectangle( long pointX, long pointY, long x1, long y1, long x2, long y2, Class<O> cls) { O nearest = null; long nearestDistance = -1; List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(x1, y1, x2, y2)); while (iterator.hasNext()) { for (Hitbox centerHitbox : iterator.next().hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { centerHitbox.scanned = true; scanned.add(centerHitbox); SpaceObject object = centerHitbox.getObject(); if (cls.isAssignableFrom(object.getClass()) && centerHitbox.getAbsX() >= x1 && centerHitbox.getAbsY() >= y1 && centerHitbox.getAbsX() <= x2 && centerHitbox.getAbsY() <= y2) { long distance = CellVector.distanceBetween( pointX, pointY, centerHitbox.getAbsX(), centerHitbox.getAbsY()); if (nearestDistance < 0 || distance < nearestDistance) { nearest = cls.cast(object); nearestDistance = distance; } } } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return nearest; } private static boolean circleMeetsOrthogonalSeg( long cu, long cv, long radius, long u1, long u2, long v) { v -= cv; if (Math.abs(v) <= radius) { long rangeRadius = Frac.sqrt(Frac.mul(radius, radius) - Frac.mul(v, v)); return u1 <= cu + rangeRadius && u2 >= cu - rangeRadius; } return false; } private static boolean circleMeetsRectangle( long cx, long cy, long radius, long x1, long y1, long x2, long y2) { if (cx >= x1 && cx <= x2 && cy >= y1 && cy <= y2) { //Circle's center is in rectangle return true; } //Any of rectangle's edges meet circle return circleMeetsOrthogonalSeg(cx, cy, radius, x1, x2, y1) || circleMeetsOrthogonalSeg(cx, cy, radius, x1, x2, y2) || circleMeetsOrthogonalSeg(cy, cx, radius, y1, y2, x1) || circleMeetsOrthogonalSeg(cy, cx, radius, y1, y2, x2); } /** * Returns whether this SpaceState has any SpaceObjects of the specified * class with their centers within the specified circular region. * @param <O> The subclass of SpaceObject to search for * @param center The region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return Whether there are any SpaceObjects of the specified class within * the specified circular region */ public final <O extends SpaceObject> boolean objectIsWithinCircle( CellVector center, long radius, Class<O> cls) { return objectWithinCircle(center.getX(), center.getY(), radius, cls) != null; } /** * Returns whether this SpaceState has any SpaceObjects of the specified * class with their centers within the specified circular region. * @param <O> The subclass of SpaceObject to search for * @param centerX The x-coordinate of the region's center * @param centerY The y-coordinate of the region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return Whether there are any SpaceObjects of the specified class within * the specified circular region */ public final <O extends SpaceObject> boolean objectIsWithinCircle( long centerX, long centerY, long radius, Class<O> cls) { return objectWithinCircle(centerX, centerY, radius, cls) != null; } /** * Returns one of this SpaceState's SpaceObjects of the specified class with * its center within the specified circular region, or null if there is * none. * @param <O> The subclass of SpaceObject to search for * @param center The region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return A SpaceObject of the specified class within the specified * circular region */ public final <O extends SpaceObject> O objectWithinCircle( CellVector center, long radius, Class<O> cls) { return objectWithinCircle(center.getX(), center.getY(), radius, cls); } /** * Returns one of this SpaceState's SpaceObjects of the specified class with * its center within the specified circular region, or null if there is * none. * @param <O> The subclass of SpaceObject to search for * @param centerX The x-coordinate of the region's center * @param centerY The y-coordinate of the region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return A SpaceObject of the specified class within the specified * circular region */ public final <O extends SpaceObject> O objectWithinCircle( long centerX, long centerY, long radius, Class<O> cls) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(centerX - radius, centerY - radius, centerX + radius, centerY + radius)); while (iterator.hasNext()) { Cell cell = iterator.next(); if (circleMeetsRectangle(centerX, centerY, radius, cell.left, cell.top, cell.right, cell.bottom)) { for (Hitbox centerHitbox : cell.hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { if (cls.isAssignableFrom(centerHitbox.getObject().getClass()) && CellVector.distanceBetween(centerX, centerY, centerHitbox.getAbsX(), centerHitbox.getAbsY()) <= radius) { for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return cls.cast(centerHitbox.getObject()); } centerHitbox.scanned = true; scanned.add(centerHitbox); } } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return null; } /** * Returns all of this SpaceState's SpaceObjects of the specified class with * their centers within the specified circular region. * @param <O> The subclass of SpaceObject to search for * @param center The region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class within the * specified circular region */ public final <O extends SpaceObject> List<O> objectsWithinCircle( CellVector center, long radius, Class<O> cls) { return objectsWithinCircle(center.getX(), center.getY(), radius, cls); } /** * Returns all of this SpaceState's SpaceObjects of the specified class with * their centers within the specified circular region. * @param <O> The subclass of SpaceObject to search for * @param centerX The x-coordinate of the region's center * @param centerY The y-coordinate of the region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class within the * specified circular region */ public final <O extends SpaceObject> List<O> objectsWithinCircle( long centerX, long centerY, long radius, Class<O> cls) { List<O> within = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(centerX - radius, centerY - radius, centerX + radius, centerY + radius)); while (iterator.hasNext()) { Cell cell = iterator.next(); if (circleMeetsRectangle(centerX, centerY, radius, cell.left, cell.top, cell.right, cell.bottom)) { for (Hitbox centerHitbox : cell.hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { centerHitbox.scanned = true; scanned.add(centerHitbox); if (cls.isAssignableFrom(centerHitbox.getObject().getClass()) && CellVector.distanceBetween(centerX, centerY, centerHitbox.getAbsX(), centerHitbox.getAbsY()) <= radius) { within.add(cls.cast(centerHitbox.getObject())); } } } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return within; } /** * Returns this SpaceState's SpaceObject of the specified class within the * specified circular region whose center is nearest to the specified point, * or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param point The point to check the distance to * @param center The region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class within the specified * circular region that is nearest to the specified point */ public final <O extends SpaceObject> O nearestObjectWithinCircle( CellVector point, CellVector center, long radius, Class<O> cls) { return nearestObjectWithinCircle( point.getX(), point.getY(), center.getX(), center.getY(), radius, cls); } /** * Returns this SpaceState's SpaceObject of the specified class within the * specified circular region whose center is nearest to the specified point, * or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param pointX The x-coordinate of the point to check the distance to * @param pointY The y-coordinate of the point to check the distance to * @param centerX The x-coordinate of the region's center * @param centerY The y-coordinate of the region's center * @param radius The region's radius * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class within the specified * circular region that is nearest to the specified point */ public final <O extends SpaceObject> O nearestObjectWithinCircle( long pointX, long pointY, long centerX, long centerY, long radius, Class<O> cls) { O nearest = null; long nearestDistance = -1; List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(centerX - radius, centerY - radius, centerX + radius, centerY + radius)); while (iterator.hasNext()) { Cell cell = iterator.next(); if (circleMeetsRectangle(centerX, centerY, radius, cell.left, cell.top, cell.right, cell.bottom)) { for (Hitbox centerHitbox : cell.hitboxes.get(HitboxRole.CENTER)) { if (!centerHitbox.scanned) { centerHitbox.scanned = true; scanned.add(centerHitbox); SpaceObject object = centerHitbox.getObject(); if (cls.isAssignableFrom(object.getClass()) && CellVector.distanceBetween(centerX, centerY, centerHitbox.getAbsX(), centerHitbox.getAbsY()) <= radius) { long distance = CellVector.distanceBetween(pointX, pointY, centerHitbox.getAbsX(), centerHitbox.getAbsY()); if (nearestDistance < 0 || distance < nearestDistance) { nearest = cls.cast(object); nearestDistance = distance; } } } } } } for (Hitbox hitbox : scanned) { hitbox.scanned = false; } return nearest; } /** * Returns whether this SpaceState has any SpaceObjects of the specified * class that overlap the specified Hitbox. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return Whether there are any SpaceObjects of the specified class that * overlap the specified Hitbox */ public final <O extends SpaceObject> boolean isOverlappingObject(Hitbox hitbox, Class<O> cls) { return overlappingObject(hitbox, cls) != null; } /** * Returns one of this SpaceState's SpaceObjects of the specified class that * overlaps the specified Hitbox, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return A SpaceObject of the specified class that overlaps the specified * Hitbox */ public final <O extends SpaceObject> O overlappingObject(Hitbox hitbox, Class<O> cls) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox overlapHitbox : iterator.next().hitboxes.get(HitboxRole.OVERLAP)) { if (!overlapHitbox.scanned) { if (cls.isAssignableFrom(overlapHitbox.getObject().getClass()) && Hitbox.overlap(hitbox, overlapHitbox)) { for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return cls.cast(overlapHitbox.getObject()); } overlapHitbox.scanned = true; scanned.add(overlapHitbox); } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return null; } /** * Returns all of this SpaceState's SpaceObjects of the specified class that * overlap the specified Hitbox. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class that overlap the * specified Hitbox */ public final <O extends SpaceObject> List<O> overlappingObjects(Hitbox hitbox, Class<O> cls) { List<O> overlapping = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox overlapHitbox : iterator.next().hitboxes.get(HitboxRole.OVERLAP)) { if (!overlapHitbox.scanned) { overlapHitbox.scanned = true; scanned.add(overlapHitbox); if (cls.isAssignableFrom(overlapHitbox.getObject().getClass()) && Hitbox.overlap(hitbox, overlapHitbox)) { overlapping.add(cls.cast(overlapHitbox.getObject())); } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return overlapping; } /** * Returns this SpaceState's SpaceObject of the specified class that * overlaps the specified Hitbox whose center is nearest to the specified * point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param point The point to check the distance to * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class that overlaps the * specified Hitbox that is nearest to the specified point */ public final <O extends SpaceObject> O nearestOverlappingObject( CellVector point, Hitbox hitbox, Class<O> cls) { return nearestOverlappingObject(point.getX(), point.getY(), hitbox, cls); } /** * Returns this SpaceState's SpaceObject of the specified class that * overlaps the specified Hitbox whose center is nearest to the specified * point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param pointX The x-coordinate of the point to check the distance to * @param pointY The y-coordinate of the point to check the distance to * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class that overlaps the * specified Hitbox that is nearest to the specified point */ public final <O extends SpaceObject> O nearestOverlappingObject( long pointX, long pointY, Hitbox hitbox, Class<O> cls) { O nearest = null; long nearestDistance = -1; List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox overlapHitbox : iterator.next().hitboxes.get(HitboxRole.OVERLAP)) { if (!overlapHitbox.scanned) { overlapHitbox.scanned = true; scanned.add(overlapHitbox); SpaceObject object = overlapHitbox.getObject(); if (cls.isAssignableFrom(object.getClass()) && Hitbox.overlap(hitbox, overlapHitbox)) { long distance = CellVector.distanceBetween(pointX, pointY, object.getCenterX(), object.getCenterY()); if (nearestDistance < 0 || distance < nearestDistance) { nearest = cls.cast(object); nearestDistance = distance; } } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return nearest; } /** * Returns all of this SpaceState's SpaceObjects of the specified class * whose overlap Hitboxes' rectangular bounding boxes touch or intersect the * specified Hitbox's rectangular bounding box. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox whose bounding box to check * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class whose overlap * Hitboxes' bounding boxes meet the specified Hitbox's bounding box */ public final <O extends SpaceObject> List<O> boundingBoxesMeet(Hitbox hitbox, Class<O> cls) { List<O> meeting = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox overlapHitbox : iterator.next().hitboxes.get(HitboxRole.OVERLAP)) { if (!overlapHitbox.scanned) { overlapHitbox.scanned = true; scanned.add(overlapHitbox); if (cls.isAssignableFrom(overlapHitbox.getObject().getClass()) && hitbox.getLeftEdge() <= overlapHitbox.getRightEdge() && hitbox.getRightEdge() >= overlapHitbox.getLeftEdge() && hitbox.getTopEdge() <= overlapHitbox.getBottomEdge() && hitbox.getBottomEdge() >= overlapHitbox.getTopEdge()) { meeting.add(cls.cast(overlapHitbox.getObject())); } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return meeting; } /** * Returns whether this SpaceState has any SpaceObjects of the specified * class whose solid Hitboxes overlap the specified Hitbox. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return Whether there are any SpaceObjects of the specified class whose * solid Hitboxes overlap the specified Hitbox */ public final <O extends SpaceObject> boolean isIntersectingSolidObject(Hitbox hitbox, Class<O> cls) { return intersectingSolidObject(hitbox, cls) != null; } /** * Returns one of this SpaceState's SpaceObjects of the specified class * whose solid Hitbox overlaps the specified Hitbox, or null if there is * none. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return A SpaceObject of the specified class whose solid Hitbox overlaps * the specified Hitbox */ public final <O extends SpaceObject> O intersectingSolidObject(Hitbox hitbox, Class<O> cls) { List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox solidHitbox : iterator.next().hitboxes.get(HitboxRole.SOLID)) { if (!solidHitbox.scanned) { if (cls.isAssignableFrom(solidHitbox.getObject().getClass()) && Hitbox.overlap(hitbox, solidHitbox)) { for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return cls.cast(solidHitbox.getObject()); } solidHitbox.scanned = true; scanned.add(solidHitbox); } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return null; } /** * Returns all of this SpaceState's SpaceObjects of the specified class * whose solid Hitboxes overlap the specified Hitbox. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return All of the SpaceObjects of the specified class whose solid * Hitboxes overlap the specified Hitbox */ public final <O extends SpaceObject> List<O> intersectingSolidObjects(Hitbox hitbox, Class<O> cls) { List<O> intersecting = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox solidHitbox : iterator.next().hitboxes.get(HitboxRole.SOLID)) { if (!solidHitbox.scanned) { solidHitbox.scanned = true; scanned.add(solidHitbox); if (cls.isAssignableFrom(solidHitbox.getObject().getClass()) && Hitbox.overlap(hitbox, solidHitbox)) { intersecting.add(cls.cast(solidHitbox.getObject())); } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return intersecting; } /** * Returns this SpaceState's SpaceObject of the specified class whose solid * Hitbox overlaps the specified Hitbox whose center is nearest to the * specified point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param point The point to check the distance to * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class whose solid Hitbox * overlaps the specified Hitbox that is nearest to the specified point */ public final <O extends SpaceObject> O nearestIntersectingSolidObject( CellVector point, Hitbox hitbox, Class<O> cls) { return nearestIntersectingSolidObject(point.getX(), point.getY(), hitbox, cls); } /** * Returns this SpaceState's SpaceObject of the specified class whose solid * Hitbox overlaps the specified Hitbox whose center is nearest to the * specified point, or null if there is none. * @param <O> The subclass of SpaceObject to search for * @param pointX The x-coordinate of the point to check the distance to * @param pointY The y-coordinate of the point to check the distance to * @param hitbox The Hitbox to check for overlapping * @param cls The Class object that represents the SpaceObject subclass * @return The SpaceObject of the specified class whose solid Hitbox * overlaps the specified Hitbox that is nearest to the specified point */ public final <O extends SpaceObject> O nearestIntersectingSolidObject( long pointX, long pointY, Hitbox hitbox, Class<O> cls) { O nearest = null; long nearestDistance = -1; List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox solidHitbox : iterator.next().hitboxes.get(HitboxRole.SOLID)) { if (!solidHitbox.scanned) { solidHitbox.scanned = true; scanned.add(solidHitbox); SpaceObject object = solidHitbox.getObject(); if (cls.isAssignableFrom(object.getClass()) && Hitbox.overlap(hitbox, solidHitbox)) { long distance = CellVector.distanceBetween(pointX, pointY, object.getCenterX(), object.getCenterY()); if (nearestDistance < 0 || distance < nearestDistance) { nearest = cls.cast(object); nearestDistance = distance; } } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return nearest; } /** * Returns all of this SpaceState's solid SpaceObjects of the specified * class whose solid Hitboxes' rectangular bounding boxes touch or intersect * the specified Hitbox's rectangular bounding box. * @param <O> The subclass of SpaceObject to search for * @param hitbox The Hitbox whose bounding box to check * @param cls The Class object that represents the SpaceObject subclass * @return All of the solid SpaceObjects of the specified class whose solid * Hitboxes' bounding boxes meet the specified Hitbox's bounding box */ public final <O extends SpaceObject> List<O> solidBoundingBoxesMeet(Hitbox hitbox, Class<O> cls) { List<O> meeting = new ArrayList<>(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(hitbox)); while (iterator.hasNext()) { for (Hitbox solidHitbox : iterator.next().hitboxes.get(HitboxRole.SOLID)) { if (!solidHitbox.scanned) { solidHitbox.scanned = true; scanned.add(solidHitbox); if (cls.isAssignableFrom(solidHitbox.getObject().getClass()) && hitbox.getLeftEdge() <= solidHitbox.getRightEdge() && hitbox.getRightEdge() >= solidHitbox.getLeftEdge() && hitbox.getTopEdge() <= solidHitbox.getBottomEdge() && hitbox.getBottomEdge() >= solidHitbox.getTopEdge()) { meeting.add(cls.cast(solidHitbox.getObject())); } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } return meeting; } /** * Returns the number of Viewports that are assigned to this SpaceState. * @return The number of Viewports that are assigned to this SpaceState */ public final int getNumViewports() { return viewports.size(); } /** * Returns the Viewport that is assigned to this SpaceState with the * specified ID. * @param id The ID of the Viewport to be returned * @return The Viewport that is assigned to this SpaceState with the * specified ID */ public final Viewport<T,U> getViewport(int id) { return viewports.get(id); } /** * Sets the Viewport that is assigned to this SpaceState with the specified * ID to the specified Viewport, if it is not already assigned to a * SpaceState. If there is already a Viewport assigned with the specified * ID, it will be removed from this SpaceState. If the specified Viewport is * null, the Viewport with the specified ID will be removed if there is one, * but it will not be replaced with anything. * @param id The ID with which to assign the specified Viewport * @param viewport The Viewport to add with the specified ID * @return Whether the addition occurred */ public final boolean setViewport(int id, Viewport<T,U> viewport) { if (viewport == null) { Viewport<T,U> oldViewport = viewports.get(id); if (oldViewport != null) { oldViewport.setGameState(null); viewports.remove(id); return true; } return false; } if (viewport.getGameState() == null) { viewport.setGameState(getThis()); Viewport<T,U> oldViewport = viewports.get(id); if (oldViewport != null) { oldViewport.setGameState(null); } viewports.put(id, viewport); return true; } return false; } /** * Removes from this SpaceState all Viewports that are currently assigned to * it. */ public final void clearViewports() { for (Viewport<T,U> viewport : viewports.values()) { viewport.setGameState(null); } viewports.clear(); } /** * Returns the point in this SpaceState, as seen through one of its * Viewports, that corresponds to the specified point in pixels on the * screen. If the specified point is not in the rendering region of one of * this SpaceState's Viewports with its camera in this SpaceState, this * method will return null. * @param x The x-coordinate of the screen point * @param y The y-coordinate of the screen point * @return The SpaceState point that corresponds to the specified screen * point */ public final CellVector getSpacePoint(int x, int y) { for (Viewport viewport : viewports.values()) { if (viewport.getCamera() != null && viewport.getCamera().newState == this && x >= viewport.roundX1 && x < viewport.roundX2 && y >= viewport.roundY1 && y < viewport.roundY2) { return new CellVector(viewport.getLeftEdge() + ((long)(x - viewport.roundX1) << Frac.BITS), viewport.getTopEdge() + ((long)(y - viewport.roundY1) << Frac.BITS)); } } return null; } /** * Returns whether any part of the specified rectangular region of this * SpaceState's space is visible through any of its Viewports. * @param x1 The x-coordinate of the region's left edge * @param y1 The y-coordinate of the region's top edge * @param x2 The x-coordinate of the region's right edge * @param y2 The y-coordinate of the region's bottom edge * @return Whether the specified rectangular region of this SpaceState's * space is visible through any of its Viewports */ public final boolean rectangleIsVisible(long x1, long y1, long x2, long y2) { for (Viewport viewport : viewports.values()) { if (viewport.getCamera() != null && viewport.getCamera().newState == this) { long centerX = viewport.getCamera().getCenterX(); long centerY = viewport.getCamera().getCenterY(); if (Frac.intFloor(x1 - centerX) < viewport.getRight() && Frac.intCeil(x2 - centerX) > viewport.getLeft() && Frac.intFloor(y1 - centerY) < viewport.getBottom() && Frac.intCeil(y2 - centerY) > viewport.getTop()) { return true; } } } return false; } /** * Returns the HUD that is assigned to this SpaceState, or null if there is * none. * @return This SpaceState's HUD */ public final HUD getHUD() { return hud; } /** * Sets the HUD that is assigned to this SpaceState to the specified one. If * there is already an HUD assigned to this SpaceState, it will be removed. * If the specified HUD is null, the current HUD will be removed if there is * one, but it will not be replaced with anything. * @param hud The HUD to add */ public final void setHUD(HUD hud) { this.hud = hud; } /** * Returns the number of SpaceLayers that are assigned to this SpaceState. * @return The number of SpaceLayers that are assigned to this SpaceState */ public final int getNumLayers() { return spaceLayers.size(); } /** * Returns the SpaceLayer that is assigned to this SpaceState with the * specified ID. * @param id The ID of the SpaceLayer to be returned * @return The SpaceLayer that is assigned to this SpaceState with the * specified ID */ public final SpaceLayer getLayer(int id) { return spaceLayers.get(id); } /** * Sets the SpaceLayer that is assigned to this SpaceState with the * specified ID to the specified SpaceLayer. If there is already a * SpaceLayer assigned with the specified ID, it will be removed from this * SpaceState. If the specified SpaceLayer is null, the SpaceLayer with the * specified ID will be removed if there is one, but it will not be replaced * with anything. * @param id The ID with which to assign the specified SpaceLayer * @param layer The SpaceLayer to add with the specified ID */ public final void setLayer(int id, SpaceLayer layer) { if (id == 0) { throw new RuntimeException("Attempted to set a SpaceLayer with an ID of 0"); } if (layer == null) { spaceLayers.remove(id); } else { spaceLayers.put(id, layer); } } /** * Removes from this SpaceState all SpaceLayers that are currently assigned * to it. */ public final void clearLayers() { spaceLayers.clear(); } private boolean areRelated(MobileObject object1, MobileObject object2) { MobileObject ancestor = object1.effLeader; while (ancestor != null) { if (ancestor == object2) { return true; } ancestor = ancestor.effLeader; } ancestor = object2.effLeader; while (ancestor != null) { if (ancestor == object1) { return true; } ancestor = ancestor.effLeader; } return false; } private static class MoveEvent { /* * Type 0 = hitting the object's solid surface. * Type 1 = pressing against the object's solid surface as you move perpendicular to the surface. * Type 2 = the colliding object encountering your solid surface and you moving it along with you. * If multiple events happen after you travel the same distance, lower types cancel higher types * if the collisions are successful. */ private final int type; private final SpaceObject object; private final Direction direction; private final long metric; private final long diffX, diffY; private MoveEvent(int type, SpaceObject object, Direction direction, long metric, long diffX, long diffY) { this.type = type; this.object = object; this.direction = direction; this.metric = metric; this.diffX = diffX; this.diffY = diffY; } } private static class MoveData { private final MobileObject object; private final boolean moveX, moveY; private final long diffX, diffY; private MoveData(MobileObject object, boolean moveX, boolean moveY, long diffX, long diffY) { this.object = object; this.moveX = moveX; this.moveY = moveY; this.diffX = diffX; this.diffY = diffY; } } final CellVector move(MobileObject object, long changeX, long changeY) { if (changeX == 0 && changeY == 0) { //Object isn't changing position Double pressingAngle = object.getAbsPressingAngle(); if (object.hasCollision() && object.getCollisionHitbox() != null && pressingAngle != null) { //Object can collide and is pressing; check for solid objects that it's pressing against Hitbox collisionHitbox = object.getCollisionHitbox(); long leftEdge = collisionHitbox.getLeftEdge(); long rightEdge = collisionHitbox.getRightEdge(); long topEdge = collisionHitbox.getTopEdge(); long bottomEdge = collisionHitbox.getBottomEdge(); boolean pressingLeft = pressingAngle > 90 && pressingAngle < 270; boolean pressingRight = pressingAngle < 90 || pressingAngle > 270; boolean pressingUp = pressingAngle > 0 && pressingAngle < 180; boolean pressingDown = pressingAngle > 180; List<Hitbox> scanned = new ArrayList<>(); Map<SpaceObject,Direction> pressingAgainst = null; Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(leftEdge, topEdge, rightEdge, bottomEdge)); while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); if (pressingLeft && hitbox.surfaceIsSolid(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getBottomEdge() > topEdge && hitbox.getTopEdge() < bottomEdge) { if (!(hitbox.getObject() instanceof MobileObject && areRelated(object, (MobileObject)hitbox.getObject()))) { if (pressingAgainst == null) { pressingAgainst = new HashMap<>(); } pressingAgainst.put(hitbox.getObject(), Direction.LEFT); } } else if (pressingRight && hitbox.surfaceIsSolid(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getBottomEdge() > topEdge && hitbox.getTopEdge() < bottomEdge) { if (!(hitbox.getObject() instanceof MobileObject && areRelated(object, (MobileObject)hitbox.getObject()))) { if (pressingAgainst == null) { pressingAgainst = new HashMap<>(); } pressingAgainst.put(hitbox.getObject(), Direction.RIGHT); } } else if (pressingUp && hitbox.surfaceIsSolid(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getRightEdge() > leftEdge && hitbox.getLeftEdge() < rightEdge) { if (!(hitbox.getObject() instanceof MobileObject && areRelated(object, (MobileObject)hitbox.getObject()))) { if (pressingAgainst == null) { pressingAgainst = new HashMap<>(); } pressingAgainst.put(hitbox.getObject(), Direction.UP); } } else if (pressingDown && hitbox.surfaceIsSolid(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getRightEdge() > leftEdge && hitbox.getLeftEdge() < rightEdge) { if (!(hitbox.getObject() instanceof MobileObject && areRelated(object, (MobileObject)hitbox.getObject()))) { if (pressingAgainst == null) { pressingAgainst = new HashMap<>(); } pressingAgainst.put(hitbox.getObject(), Direction.DOWN); } } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } if (pressingAgainst != null) { //Object is pressing against things; make it collide with them EnumSet<Direction> slideDirections = EnumSet.noneOf(Direction.class); boolean stop = false; for (Map.Entry<SpaceObject,Direction> entry : pressingAgainst.entrySet()) { SpaceObject pressingObject = entry.getKey(); Direction direction = entry.getValue(); CollisionResponse response = object.collide(pressingObject, direction); if (response != CollisionResponse.NONE) { switch (response) { case SLIDE: slideDirections.add(direction); break; case STOP: stop = true; break; } object.addCollision(pressingObject, direction); } } //Change object's velocity appropriately based on its collisions if (stop) { object.setVelocity(0, 0); } else { if (object.getVelocityX() < 0) { if (slideDirections.contains(Direction.LEFT)) { object.setVelocityX(0); } } else if (object.getVelocityX() > 0) { if (slideDirections.contains(Direction.RIGHT)) { object.setVelocityX(0); } } if (object.getVelocityY() < 0) { if (slideDirections.contains(Direction.UP)) { object.setVelocityY(0); } } else if (object.getVelocityY() > 0) { if (slideDirections.contains(Direction.DOWN)) { object.setVelocityY(0); } } } } } return new CellVector(); //Object was not displaced } CellVector nextMovement = null; //Object might need to move again due to sliding or something long left, right, top, bottom; if (changeX > 0) { left = 0; right = changeX; } else { left = changeX; right = 0; } if (changeY > 0) { top = 0; bottom = changeY; } else { top = changeY; bottom = 0; } SortedSet<MoveEvent> moveEvents = new TreeSet<>(moveComparator); //Record encounters that object needs to have as it moves if (object.hasCollision() && object.getCollisionHitbox() != null) { //Object can collide; check for solid objects in the path of its movement Hitbox collisionHitbox = object.getCollisionHitbox(); long leftEdge = collisionHitbox.getLeftEdge(); long rightEdge = collisionHitbox.getRightEdge(); long topEdge = collisionHitbox.getTopEdge(); long bottomEdge = collisionHitbox.getBottomEdge(); boolean pressingLeft = false; boolean pressingRight = false; boolean pressingUp = false; boolean pressingDown = false; Double pressingAngle = object.getAbsPressingAngle(); if (pressingAngle != null) { pressingLeft = pressingAngle > 90 && pressingAngle < 270; pressingRight = pressingAngle < 90 || pressingAngle > 270; pressingUp = pressingAngle > 0 && pressingAngle < 180; pressingDown = pressingAngle > 180; } List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(leftEdge + left, topEdge + top, rightEdge + right, bottomEdge + bottom)); if (changeX > 0) { if (changeY > 0) { //Object is moving diagonally down-right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); long hitboxTop = hitbox.getTopEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxLeft - rightEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxTop - bottomEdge, changeX), changeY); if (hitbox.surfaceIsSolid(Direction.LEFT) && hitboxLeft >= rightEdge && hitbox.getTopEdge() <= bottomEdge + verticalDiff && hitbox.getBottomEdge() > topEdge + verticalDiff && hitboxLeft < rightEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.RIGHT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, verticalDiff)); } } else if (hitbox.surfaceIsSolid(Direction.UP) && hitboxTop >= bottomEdge && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff && hitboxTop < bottomEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.DOWN, horizontalDiff, horizontalDiff, hitboxTop - bottomEdge)); } } } } } } else if (changeY < 0) { //Object is moving diagonally up-right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); long hitboxBottom = hitbox.getBottomEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxLeft - rightEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxBottom - topEdge, changeX), changeY); if (hitbox.surfaceIsSolid(Direction.LEFT) && hitboxLeft >= rightEdge && hitbox.getTopEdge() < bottomEdge + verticalDiff && hitbox.getBottomEdge() >= topEdge + verticalDiff && hitboxLeft < rightEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.RIGHT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, verticalDiff)); } } else if (hitbox.surfaceIsSolid(Direction.DOWN) && hitboxBottom <= topEdge && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff && hitboxBottom > topEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.UP, horizontalDiff, horizontalDiff, hitboxBottom - topEdge)); } } } } } } else { //Object is moving right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); if (hitbox.surfaceIsSolid(Direction.LEFT) && hitboxLeft >= rightEdge && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge && (hitboxLeft < rightEdge + changeX || (pressingRight && hitboxLeft == rightEdge + changeX))) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.RIGHT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, 0)); } } else if (pressingUp && hitbox.surfaceIsSolid(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getRightEdge() > leftEdge && hitboxLeft < rightEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(hitboxLeft - rightEdge, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.UP, distance, distance, 0)); } } else if (pressingDown && hitbox.surfaceIsSolid(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getRightEdge() > leftEdge && hitboxLeft < rightEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(hitboxLeft - rightEdge, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.DOWN, distance, distance, 0)); } } } } } } } else if (changeX < 0) { if (changeY > 0) { //Object is moving diagonally down-left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); long hitboxTop = hitbox.getTopEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxRight - leftEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxTop - bottomEdge, changeX), changeY); if (hitbox.surfaceIsSolid(Direction.RIGHT) && hitboxRight <= leftEdge && hitbox.getTopEdge() <= bottomEdge + verticalDiff && hitbox.getBottomEdge() > topEdge + verticalDiff && hitboxRight > leftEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.LEFT, leftEdge - hitboxRight, hitboxRight - leftEdge, verticalDiff)); } } else if (hitbox.surfaceIsSolid(Direction.UP) && hitboxTop >= bottomEdge && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff && hitboxTop < bottomEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.DOWN, -horizontalDiff, horizontalDiff, hitboxTop - bottomEdge)); } } } } } } else if (changeY < 0) { //Object is moving diagonally up-left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); long hitboxBottom = hitbox.getBottomEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxRight - leftEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxBottom - topEdge, changeX), changeY); if (hitbox.surfaceIsSolid(Direction.RIGHT) && hitboxRight <= leftEdge && hitbox.getTopEdge() < bottomEdge + verticalDiff && hitbox.getBottomEdge() >= topEdge + verticalDiff && hitboxRight > leftEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.LEFT, leftEdge - hitboxRight, hitboxRight - leftEdge, verticalDiff)); } } else if (hitbox.surfaceIsSolid(Direction.DOWN) && hitboxBottom <= topEdge && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff && hitboxBottom > topEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.UP, -horizontalDiff, horizontalDiff, hitboxBottom - topEdge)); } } } } } } else { //Object is moving left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); if (hitbox.surfaceIsSolid(Direction.RIGHT) && hitboxRight <= leftEdge && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge && (hitboxRight > leftEdge + changeX || (pressingLeft && hitboxRight == leftEdge + changeX))) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.LEFT, leftEdge - hitboxRight, hitboxRight - leftEdge, 0)); } } else if (pressingUp && hitbox.surfaceIsSolid(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(leftEdge - hitboxRight, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.UP, distance, -distance, 0)); } } else if (pressingDown && hitbox.surfaceIsSolid(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge + changeX) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(leftEdge - hitboxRight, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.DOWN, distance, -distance, 0)); } } } } } } } else { if (changeY > 0) { //Object is moving down while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxTop = hitbox.getTopEdge(); if (hitbox.surfaceIsSolid(Direction.UP) && hitboxTop >= bottomEdge && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge && (hitboxTop < bottomEdge + changeY || (pressingDown && hitboxTop == bottomEdge + changeY))) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.DOWN, hitboxTop - bottomEdge, 0, hitboxTop - bottomEdge)); } } else if (pressingLeft && hitbox.surfaceIsSolid(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getBottomEdge() > topEdge && hitboxTop < bottomEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(hitboxTop - bottomEdge, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.LEFT, distance, 0, distance)); } } else if (pressingRight && hitbox.surfaceIsSolid(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getBottomEdge() > topEdge && hitboxTop < bottomEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(hitboxTop - bottomEdge, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.RIGHT, distance, 0, distance)); } } } } } } else { //Object is moving up while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.SOLID)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxBottom = hitbox.getBottomEdge(); if (hitbox.surfaceIsSolid(Direction.DOWN) && hitboxBottom <= topEdge && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge && (hitboxBottom > topEdge + changeY || (pressingUp && hitboxBottom == topEdge + changeY))) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; moveEvents.add(new MoveEvent(0, hitboxObject, Direction.UP, topEdge - hitboxBottom, 0, hitboxBottom - topEdge)); } } else if (pressingLeft && hitbox.surfaceIsSolid(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(topEdge - hitboxBottom, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.LEFT, distance, 0, -distance)); } } else if (pressingRight && hitbox.surfaceIsSolid(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge + changeY) { SpaceObject hitboxObject = hitbox.getObject(); if (!(hitboxObject instanceof MobileObject && areRelated(object, (MobileObject)hitboxObject))) { hitboxObject.solidEvent = true; long distance = Math.max(topEdge - hitboxBottom, -1); moveEvents.add(new MoveEvent(1, hitboxObject, Direction.RIGHT, distance, 0, -distance)); } } } } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } } if (object.isSolid()) { //Object has solid surfaces; check for colliding objects to move along with it Hitbox solidHitbox = object.getSolidHitbox(); boolean solidLeft = solidHitbox.surfaceIsSolid(Direction.LEFT); boolean solidRight = solidHitbox.surfaceIsSolid(Direction.RIGHT); boolean solidTop = solidHitbox.surfaceIsSolid(Direction.UP); boolean solidBottom = solidHitbox.surfaceIsSolid(Direction.DOWN); long leftEdge = solidHitbox.getLeftEdge(); long rightEdge = solidHitbox.getRightEdge(); long topEdge = solidHitbox.getTopEdge(); long bottomEdge = solidHitbox.getBottomEdge(); List<Hitbox> scanned = new ArrayList<>(); Iterator<Cell> iterator = new ReadCellRangeIterator(getCellRangeExclusive(leftEdge + left, topEdge + top, rightEdge + right, bottomEdge + bottom)); if (changeX > 0) { if (changeY > 0) { //Object is moving diagonally down-right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); long hitboxTop = hitbox.getTopEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxLeft - rightEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxTop - bottomEdge, changeX), changeY); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidRight && hitboxLeft >= rightEdge && hitboxLeft < rightEdge + changeX && hitbox.getTopEdge() <= bottomEdge + verticalDiff && hitbox.getBottomEdge() > topEdge + verticalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, verticalDiff)); } } else if (solidBottom && hitboxTop >= bottomEdge && hitboxTop < bottomEdge + changeY && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, horizontalDiff, horizontalDiff, hitboxTop - bottomEdge)); } } else if (solidLeft && hitboxObject.isPressingIn(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitboxTop < bottomEdge && hitbox.getBottomEdge() > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, 0, 0, 0)); } } else if (solidTop && hitboxObject.isPressingIn(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitboxLeft < rightEdge && hitbox.getRightEdge() > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, 0, 0, 0)); } } } } } } else if (changeY < 0) { //Object is moving diagonally up-right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); long hitboxBottom = hitbox.getBottomEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxLeft - rightEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxBottom - topEdge, changeX), changeY); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidRight && hitboxLeft >= rightEdge && hitboxLeft < rightEdge + changeX && hitbox.getTopEdge() < bottomEdge + verticalDiff && hitbox.getBottomEdge() >= topEdge + verticalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, verticalDiff)); } } else if (solidTop && hitboxBottom <= topEdge && hitboxBottom > topEdge + changeY && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, horizontalDiff, horizontalDiff, hitboxBottom - topEdge)); } } else if (solidLeft && hitboxObject.isPressingIn(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, 0, 0, 0)); } } else if (solidBottom && hitboxObject.isPressingIn(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitboxLeft < rightEdge && hitbox.getRightEdge() > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, 0, 0, 0)); } } } } } } else { //Object is moving right while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxLeft = hitbox.getLeftEdge(); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidRight && hitboxLeft >= rightEdge && hitboxLeft < rightEdge + changeX && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, hitboxLeft - rightEdge, hitboxLeft - rightEdge, 0)); } } else if (solidTop && hitboxObject.isPressingIn(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getRightEdge() > leftEdge && hitboxLeft < rightEdge + changeX && hitboxObject.getVelocityY() + hitboxObject.getStepY() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(hitboxLeft - rightEdge, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, distance, distance, 0)); } } else if (solidBottom && hitboxObject.isPressingIn(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getRightEdge() > leftEdge && hitboxLeft < rightEdge + changeX && hitboxObject.getVelocityY() + hitboxObject.getStepY() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(hitboxLeft - rightEdge, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, distance, distance, 0)); } } else if (solidLeft && hitboxObject.isPressingIn(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, 0, 0, 0)); } } } } } } } else if (changeX < 0) { if (changeY > 0) { //Object is moving diagonally down-left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); long hitboxTop = hitbox.getTopEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxRight - leftEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxTop - bottomEdge, changeX), changeY); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidLeft && hitboxRight <= leftEdge && hitboxRight > leftEdge + changeX && hitbox.getTopEdge() <= bottomEdge + verticalDiff && hitbox.getBottomEdge() > topEdge + verticalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, leftEdge - hitboxRight, hitboxRight - leftEdge, verticalDiff)); } } else if (solidBottom && hitboxTop >= bottomEdge && hitboxTop < bottomEdge + changeY && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, -horizontalDiff, horizontalDiff, hitboxTop - bottomEdge)); } } else if (solidRight && hitboxObject.isPressingIn(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitboxTop < bottomEdge && hitbox.getBottomEdge() > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, 0, 0, 0)); } } else if (solidTop && hitboxObject.isPressingIn(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, 0, 0, 0)); } } } } } } else if (changeY < 0) { //Object is moving diagonally up-left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); long hitboxBottom = hitbox.getBottomEdge(); long verticalDiff = Frac.div(Frac.mul(hitboxRight - leftEdge, changeY), changeX); long horizontalDiff = Frac.div(Frac.mul(hitboxBottom - topEdge, changeX), changeY); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidLeft && hitboxRight <= leftEdge && hitboxRight > leftEdge + changeX && hitbox.getTopEdge() < bottomEdge + verticalDiff && hitbox.getBottomEdge() >= topEdge + verticalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, leftEdge - hitboxRight, hitboxRight - leftEdge, verticalDiff)); } } else if (solidTop && hitboxBottom <= topEdge && hitboxBottom > topEdge + changeY && hitbox.getLeftEdge() < rightEdge + horizontalDiff && hitbox.getRightEdge() > leftEdge + horizontalDiff) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, -horizontalDiff, horizontalDiff, hitboxBottom - topEdge)); } } else if (solidRight && hitboxObject.isPressingIn(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, 0, 0, 0)); } } else if (solidBottom && hitboxObject.isPressingIn(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, 0, 0, 0)); } } } } } } else { //Object is moving left while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxRight = hitbox.getRightEdge(); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidLeft && hitboxRight <= leftEdge && hitboxRight > leftEdge + changeX && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, leftEdge - hitboxRight, hitboxRight - leftEdge, 0)); } } else if (solidTop && hitboxObject.isPressingIn(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge + changeX && hitboxObject.getVelocityY() + hitboxObject.getStepY() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(leftEdge - hitboxRight, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, distance, -distance, 0)); } } else if (solidBottom && hitboxObject.isPressingIn(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getLeftEdge() < rightEdge && hitboxRight > leftEdge + changeX && hitboxObject.getVelocityY() + hitboxObject.getStepY() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(leftEdge - hitboxRight, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, distance, -distance, 0)); } } else if (solidRight && hitboxObject.isPressingIn(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getTopEdge() < bottomEdge && hitbox.getBottomEdge() > topEdge && hitboxObject.getVelocityX() + hitboxObject.getStepX() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, 0, 0, 0)); } } } } } } } else { if (changeY > 0) { //Object is moving down while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxTop = hitbox.getTopEdge(); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidBottom && hitboxTop >= bottomEdge && hitboxTop < bottomEdge + changeY && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, hitboxTop - bottomEdge, 0, hitboxTop - bottomEdge)); } } else if (solidLeft && hitboxObject.isPressingIn(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getBottomEdge() > topEdge && hitboxTop < bottomEdge + changeY && hitboxObject.getVelocityX() + hitboxObject.getStepX() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(hitboxTop - bottomEdge, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, distance, distance, 0)); } } else if (solidRight && hitboxObject.isPressingIn(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getBottomEdge() > topEdge && hitboxTop < bottomEdge + changeY && hitboxObject.getVelocityX() + hitboxObject.getStepX() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(hitboxTop - bottomEdge, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, distance, distance, 0)); } } else if (solidTop && hitboxObject.isPressingIn(Direction.DOWN) && hitbox.getBottomEdge() == topEdge && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, 0, 0, 0)); } } } } } } else { //Object is moving up while (iterator.hasNext()) { Cell cell = iterator.next(); for (Hitbox hitbox : cell.hitboxes.get(HitboxRole.COLLISION)) { if (!hitbox.scanned) { hitbox.scanned = true; scanned.add(hitbox); long hitboxBottom = hitbox.getBottomEdge(); MobileObject hitboxObject = (MobileObject)hitbox.getObject(); if (solidTop && hitboxBottom <= topEdge && hitboxBottom > topEdge + changeY && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.DOWN, topEdge - hitboxBottom, 0, hitboxBottom - topEdge)); } } else if (solidLeft && hitboxObject.isPressingIn(Direction.RIGHT) && hitbox.getRightEdge() == leftEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge + changeY && hitboxObject.getVelocityX() + hitboxObject.getStepX() >= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(topEdge - hitboxBottom, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.RIGHT, distance, -distance, 0)); } } else if (solidRight && hitboxObject.isPressingIn(Direction.LEFT) && hitbox.getLeftEdge() == rightEdge && hitbox.getTopEdge() < bottomEdge && hitboxBottom > topEdge + changeY && hitboxObject.getVelocityX() + hitboxObject.getStepX() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { long distance = Math.max(topEdge - hitboxBottom, -1); moveEvents.add(new MoveEvent(2, hitboxObject, Direction.LEFT, distance, -distance, 0)); } } else if (solidBottom && hitboxObject.isPressingIn(Direction.UP) && hitbox.getTopEdge() == bottomEdge && hitbox.getLeftEdge() < rightEdge && hitbox.getRightEdge() > leftEdge && hitboxObject.getVelocityY() + hitboxObject.getStepY() <= 0) { if (!areRelated(object, hitboxObject) && (!hitboxObject.solidEvent || movementPriorityComparator.compare(object, hitboxObject) > 0)) { moveEvents.add(new MoveEvent(2, hitboxObject, Direction.UP, 0, 0, 0)); } } } } } } } for (Hitbox scannedHitbox : scanned) { scannedHitbox.scanned = false; } } List<MoveData> moveData = null; //Record objects that need to move along with this object if (!moveEvents.isEmpty()) { //Does object need to collide with anything? boolean blocked = false; long blockedMetric = 0; int blockedType = 0; long realChangeX = 0; long realChangeY = 0; EnumSet<Direction> slideDirections = EnumSet.noneOf(Direction.class); boolean stop = false; //Make object collide with things for (MoveEvent event : moveEvents) { if (blocked && (event.metric > blockedMetric || event.type > blockedType)) { break; } Direction direction = event.direction; if (event.type == 2) { //Colliding object that will collide with this object MobileObject objectToMove = (MobileObject)event.object; CollisionResponse response = objectToMove.collide(object, direction); if (response != CollisionResponse.NONE) { switch (response) { case SLIDE: switch (direction) { case LEFT: if (objectToMove.getVelocityX() < 0) { objectToMove.setVelocityX(0); } break; case RIGHT: if (objectToMove.getVelocityX() > 0) { objectToMove.setVelocityX(0); } break; case UP: if (objectToMove.getVelocityY() < 0) { objectToMove.setVelocityY(0); } break; case DOWN: if (objectToMove.getVelocityY() > 0) { objectToMove.setVelocityY(0); } break; } break; case STOP: objectToMove.setVelocity(0, 0); break; } objectToMove.addCollision(object, direction); objectToMove.moved = true; objectToMove.effLeader = object; if (moveData == null) { moveData = new ArrayList<>(); } boolean objectPressing = objectToMove.isPressingIn(direction); moveData.add(new MoveData(objectToMove, objectPressing || direction == Direction.LEFT || direction == Direction.RIGHT, objectPressing || direction == Direction.UP || direction == Direction.DOWN, event.diffX, event.diffY)); } } else { //Solid object that this object will collide with SpaceObject solidObject = event.object; if (solidObject.moved) { continue; } CollisionResponse response = object.collide(solidObject, direction); if (response != CollisionResponse.NONE) { switch (response) { case SLIDE: slideDirections.add(direction); break; case STOP: stop = true; break; } object.addCollision(solidObject, direction); if (!blocked && (event.type == 0 || stop)) { blocked = true; blockedMetric = event.metric; blockedType = event.type; realChangeX = event.diffX; realChangeY = event.diffY; } } } } //Change object's velocity appropriately based on its collisions if (blocked) { if (stop) { object.setVelocity(0, 0); } else { nextMovement = new CellVector(changeX - realChangeX, changeY - realChangeY); if (slideDirections.contains(Direction.LEFT)) { if (object.getVelocityX() < 0) { object.setVelocityX(0); } nextMovement.setX(0); } else if (slideDirections.contains(Direction.RIGHT)) { if (object.getVelocityX() > 0) { object.setVelocityX(0); } nextMovement.setX(0); } if (slideDirections.contains(Direction.UP)) { if (object.getVelocityY() < 0) { object.setVelocityY(0); } nextMovement.setY(0); } else if (slideDirections.contains(Direction.DOWN)) { if (object.getVelocityY() > 0) { object.setVelocityY(0); } nextMovement.setY(0); } } changeX = realChangeX; changeY = realChangeY; } for (MoveEvent event : moveEvents) { event.object.solidEvent = false; event.object.moved = false; } } CellVector displacement = new CellVector(changeX, changeY); //How far was object displaced in total? object.setPosition(object.getX() + changeX, object.getY() + changeY); //Move object if (!object.followers.isEmpty()) { //Object has followers; move them along with it for (MobileObject follower : object.followers) { move(follower, changeX, changeY); } } if (moveData != null) { //Object needs to move certain colliding objects along with it; do so for (MoveData data : moveData) { move(data.object, (data.moveX ? changeX - data.diffX : 0), (data.moveY ? changeY - data.diffY : 0)); } for (MoveData data : moveData) { data.object.effLeader = data.object.getLeader(); } } if (nextMovement != null && (nextMovement.getX() != 0 || nextMovement.getY() != 0)) { //Object needs to move again immediately; do so displacement.add(move(object, nextMovement.getX(), nextMovement.getY())); } return displacement; } @Override public void frameActions(T game, U state) { beforeMovementEvents.perform(state); for (MobileObject object : mobileObjects) { object.collisions.clear(); object.collisionDirections.clear(); object.displacement.clear(); } Iterator<MobileObject> iterator = mobileObjectIterator(); while (iterator.hasNext()) { MobileObject object = iterator.next(); long objectTimeFactor = object.getEffectiveTimeFactor(); long changeX = Frac.mul(objectTimeFactor, object.getVelocityX() + object.getStepX()); long changeY = Frac.mul(objectTimeFactor, object.getVelocityY() + object.getStepY()); object.displacement.setCoordinates(move(object, changeX, changeY)); object.setStep(0, 0); } } @Override public void renderActions(T game, Graphics g, int x1, int y1, int x2, int y2) { g.clearWorldClip(); for (Viewport viewport : viewports.values()) { if (viewport.roundX1 != viewport.roundX2 && viewport.roundY1 != viewport.roundY2) { int vx1 = x1 + viewport.roundX1; int vy1 = y1 + viewport.roundY1; int vx2 = x1 + viewport.roundX2; int vy2 = y1 + viewport.roundY2; int sx1 = Math.max(vx1, x1); int sy1 = Math.max(vy1, y1); int sx2 = Math.min(vx2, x2); int sy2 = Math.min(vy2, y2); g.setWorldClip(sx1, sy1, sx2 - sx1, sy2 - sy1); if (viewport.getCamera() != null && viewport.getCamera().newState == this) { long cx = viewport.getCamera().getCenterX(); long cy = viewport.getCamera().getCenterY(); long leftEdge = viewport.getLeftEdge(); long rightEdge = viewport.getRightEdge(); long topEdge = viewport.getTopEdge(); long bottomEdge = viewport.getBottomEdge(); int scx = vx1 + Frac.intRound(cx - leftEdge); int scy = vy1 + Frac.intRound(cy - topEdge); for (SpaceLayer layer : spaceLayers.headMap(0).values()) { layer.renderActions(g, cx, cy, scx, scy, vx1, vy1, vx2, vy2); } int[] cellRange = getCellRangeExclusive(leftEdge, topEdge, rightEdge, bottomEdge); if (drawMode == DrawMode.FLAT && cellRange[0] == cellRange[2] && cellRange[1] == cellRange[3]) { Cell cell = cells.get(new Point(cellRange[0], cellRange[1])); if (cell != null) { for (Hitbox locatorHitbox : cell.hitboxes.get(HitboxRole.LOCATOR)) { if (locatorHitbox.getLeftEdge() < rightEdge && locatorHitbox.getRightEdge() > leftEdge && locatorHitbox.getTopEdge() < bottomEdge && locatorHitbox.getBottomEdge() > topEdge) { locatorHitbox.getObject().draw(g, scx + Frac.intRound(locatorHitbox.getAbsX() - cx), scy + Frac.intRound(locatorHitbox.getAbsY() - cy)); } } } } else { List<Set<Hitbox>> hitboxesList = new ArrayList<>((cellRange[2] - cellRange[0] + 1)*(cellRange[3] - cellRange[1] + 1)); Iterator<Cell> iterator = new ReadCellRangeIterator(cellRange); while (iterator.hasNext()) { hitboxesList.add(iterator.next().hitboxes.get(HitboxRole.LOCATOR)); } PriorityQueue<HitboxIteratorData> queue = new PriorityQueue<>(drawComparator); for (Set<Hitbox> locatorHitboxes : hitboxesList) { if (!locatorHitboxes.isEmpty()) { Iterator<Hitbox> hitboxIterator = locatorHitboxes.iterator(); queue.add(new HitboxIteratorData(hitboxIterator, hitboxIterator.next())); } } Hitbox lastHitbox = null; while (!queue.isEmpty()) { HitboxIteratorData data = queue.poll(); Hitbox locatorHitbox = data.currentHitbox; if (locatorHitbox != lastHitbox) { if (locatorHitbox.getLeftEdge() < rightEdge && locatorHitbox.getRightEdge() > leftEdge && locatorHitbox.getTopEdge() < bottomEdge && locatorHitbox.getBottomEdge() > topEdge) { locatorHitbox.getObject().draw(g, scx + Frac.intRound(locatorHitbox.getAbsX() - cx), scy + Frac.intRound(locatorHitbox.getAbsY() - cy)); } lastHitbox = locatorHitbox; } if (data.iterator.hasNext()) { data.currentHitbox = data.iterator.next(); queue.add(data); } } } for (SpaceLayer layer : spaceLayers.tailMap(0).values()) { layer.renderActions(g, cx, cy, scx, scy, vx1, vy1, vx2, vy2); } } if (viewport.getHUD() != null) { viewport.getHUD().renderActions(g, vx1, vy1, vx2, vy2); } g.clearWorldClip(); } } g.setWorldClip(x1, y1, x2 - x1, y2 - y1); if (hud != null) { hud.renderActions(g, x1, y1, x2, y2); } } }
742mph/Ironclad2D
src/org/cell2d/space/SpaceState.java
Java
gpl-3.0
167,865
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Automatically generated strings for Moodle installer * * Do not edit this file manually! It contains just a subset of strings * needed during the very first steps of installation. This file was * generated automatically by export-installer.php (which is part of AMOS * {@link http://docs.moodle.org/dev/Languages/AMOS}) using the * list of strings defined in /install/stringnames.txt. * * @package installer * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['admindirname'] = 'Administratora direktorijs'; $string['availablelangs'] = 'Pieejamās valodu pakotnes'; $string['chooselanguagehead'] = 'Valodas izvēle'; $string['chooselanguagesub'] = 'Lūdzu izvēlieties šīs instalācijas valodu. Izvēlētā valoda tiks izmantota arī kā noklusētā šīs vietnes valoda, lai gan tā var tikt nomainīta vēlāk.'; $string['databasetypehead'] = 'Izvēlēties datubāzes draiveru'; $string['dataroot'] = 'Datu direktorijs'; $string['dbprefix'] = 'Tabulu prefikss'; $string['dirroot'] = 'Moodle direktorijs'; $string['environmenthead'] = 'Vides pārbaude...'; $string['installation'] = 'Instalēšana'; $string['langdownloaderror'] = '“{$a}” valodas pakotne diemžēl netika instalēta. Instalēšana tiks turpināta angļu valodā.'; $string['memorylimithelp'] = '<p>Pašlaik iestatītais PHP atmiņas apjoma ierobežojums jūsu serverī ir {$a}.</p> <p>Sistēmā Moodle tas vēlāk var izraisīt atmiņas izmantošanas problēmas, it īpaši tad, ja būsit iespējojis lielu skaitu moduļu un/vai lietotāju.</p> <p>Ja iespējams, ieteicams konfigurēt PHP ar lielāku maksimālās atmiņas apjomu, piemēram, 40 MB. Ir vairāki veidi, kā to var izdarīt, piemēram:</p> <ol> <li>Ja iespējams, atkārtoti kompilējiet PHP, izmantojot <i>--enable-memory-limit</i>. Šādā gadījumā sistēma Moodle atmiņas apjoma ierobežojumu varēs iestatīt automātiski.</li> <li>Ja jums ir piekļuve php.ini failam, varat mainīt tajā esošo parametra <b>memory_limit</b> iestatījumu, piemēram, uz 40 MB. Ja jums nav piekļuves šim failam, palūdziet to izdarīt administratoram.</li> <li>Dažos PHP serveros Moodle direktorijā var izveidot failu .htaccess, kurā ir šāda rinda: <p><blockquote>php_value memory_limit 40M</blockquote></p> <p>Tomēr dažos serveros tas neļaus darboties <b>nevienai</b> PHP lapai (atverot šīs lapas, tiks parādīti kļūdas ziņojumi), un fails .htaccess būs jānoņem.</p></li> </ol>'; $string['phpversion'] = 'PHP versija'; $string['phpversionhelp'] = '<p>Sistēmā Moodle jāizmanto PHP, kuras versija ir vismaz 4.3.0 vai 5.1.0 (versijai 5.0.x piemīt vairākas zināmas problēmas).</p> <p>Jūs pašlaik lietojat versiju {$a}</p> <p>Ir jājaunina PHP vai jāpāriet uz resursdatoru, kurā tiek izmantota jaunāka PHP versija.</p> (Ja PHP versija ir 5.0.x, var arī atkāpties uz versiju 4.4.x)</p>'; $string['welcomep10'] = '{$a->installername} ({$a->installerversion})'; $string['welcomep20'] = 'Jūs redzat šo lapu, jo esat veiksmīgi instalējis un palaidis savā datorā pakotni <strong>{$a->packname} {$a->packversion}</strong>. Apsveicam!'; $string['welcomep30'] = 'Šajā <strong>{$a->installername}</strong> laidienā ir iekļautas lietojumprogrammas, kas paredzētas, lai izveidotu vidi, kurā darbosies sistēma <strong>Moodle</strong>, proti:'; $string['welcomep40'] = 'Pakotnē ir iekļauta arī sistēma <strong>Moodle {$a->moodlerelease} ({$a->moodleversion})</strong>.'; $string['welcomep50'] = 'Visu šīs pakotnes lietojumprogrammu izmantošanu regulē attiecīgo licenču nosacījumi. Visā <strong>{$a->installername}</strong> pakotnē ir iekļauts <a href="http://www.opensource.org/docs/definition_plain.html">atklātais pirmkods</a>, un tā tiek izplatīta saskaņā ar <a href="http://www.gnu.org/copyleft/gpl.html">GPL</a> licences nosacījumiem.'; $string['welcomep60'] = 'Nākamajās lapās tiks sniegti vienkārši norādījumi par to, kā datorā konfigurēt un iestatīt sistēmu <strong>Moodle</strong>. Varat akceptēt noklusējuma iestatījumus vai varat tos mainīt, lai pielāgotu savām vajadzībām.'; $string['welcomep70'] = 'Noklikšķiniet uz pogas Tālāk, lai turpinātu sistēmas <strong>Moodle</strong> instalēšanu.'; $string['wwwroot'] = 'Tīmekļa adrese';
Dermoodle/fpelearning
install/lang/lv/install.php
PHP
gpl-3.0
5,151
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import pyomo.environ as pyomo from .... import core class Light(core.component.Component): """ a class implementing an on/off light """ default_config = { 'type': '', 'power': '', 'zone': '', } linked_states = { 'value': { 'default_config': {}, 'fixed_config': {}, }, } core.components.register(Light) class Dimminglight(Light): """ a class implementing an dimmable light """ linked_states = { 'value': { 'default_config': {}, 'fixed_config': {}, }, 'value_status': { 'default_config': {}, 'fixed_config': {}, }, } core.components.register(Dimminglight)
BrechtBa/homeconn
homecon/plugins/building/components/light.py
Python
gpl-3.0
827
/* Copyright information is at end of file */ /* Implementation note: The printf format specifiers we use appear to be entirely standard, except for the "long long" one, which is %I64 on Windows and %lld everywhere else. We could use the C99 standard macro PRId64 for that, but on at least one 64-bit-long GNU compiler, PRId64 is "ld", which is considered to be incompatible with long long. So we have XMLRPC_PRId64. */ #include "xmlrpc_config.h" #include <assert.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <float.h> #include "int.h" #include "xmlrpc-c/base.h" #include "xmlrpc-c/base_int.h" #include "xmlrpc-c/string_int.h" #include "double.h" #define CRLF "\015\012" #define XML_PROLOGUE "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"CRLF #define APACHE_URL "http://ws.apache.org/xmlrpc/namespaces/extensions" #define XMLNS_APACHE "xmlns:ex=\"" APACHE_URL "\"" static void addString(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, const char * const string) { XMLRPC_MEMBLOCK_APPEND(char, envP, outputP, string, strlen(string)); } static void formatOut(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, const char * const formatString, ...) { /*---------------------------------------------------------------------------- A lightweight print routine for use with various serialization functions. Use this routine only for printing small objects -- it uses a fixed-size internal buffer and returns an error on overflow. In particular, do NOT use this routine to print XML-RPC string values! -----------------------------------------------------------------------------*/ va_list args; char buffer[128]; int rc; XMLRPC_ASSERT_ENV_OK(envP); va_start(args, formatString); rc = XMLRPC_VSNPRINTF(buffer, sizeof(buffer), formatString, args); /* Old vsnprintf() (and Windows) fails with return value -1 if the full string doesn't fit in the buffer. New vsnprintf() puts whatever will fit in the buffer, and returns the length of the full string regardless. For us, this truncation is a failure. */ if (rc < 0) xmlrpc_faultf(envP, "formatOut() overflowed internal buffer"); else { unsigned int const formattedLen = rc; if (formattedLen + 1 >= (sizeof(buffer))) xmlrpc_faultf(envP, "formatOut() overflowed internal buffer"); else XMLRPC_MEMBLOCK_APPEND(char, envP, outputP, buffer, formattedLen); } va_end(args); } static void assertValidUtf8(const char * const str ATTR_UNUSED, size_t const len ATTR_UNUSED) { /*---------------------------------------------------------------------------- Assert that the string 'str' of length 'len' is valid UTF-8. -----------------------------------------------------------------------------*/ #if !defined NDEBUG /* Check the assertion; if it's false, issue a message to Standard Error, but otherwise ignore it. */ xmlrpc_env env; xmlrpc_env_init(&env); xmlrpc_validate_utf8(&env, str, len); if (env.fault_occurred) fprintf(stderr, "*** xmlrpc-c WARNING ***: %s (%s)\n", "Xmlrpc-c sending corrupted UTF-8 data to network", env.fault_string); xmlrpc_env_clean(&env); #endif } static size_t escapedSize(const char * const chars, size_t const len) { size_t size; size_t i; size = 0; for (i = 0; i < len; ++i) { if (chars[i] == '<') size += 4; /* &lt; */ else if (chars[i] == '>') size += 4; /* &gt; */ else if (chars[i] == '&') size += 5; /* &amp; */ else if (chars[i] == '\r') size += 6; /* &#x0d; */ else size += 1; } return size; } static void escapeForXml(xmlrpc_env * const envP, const char * const chars, size_t const len, xmlrpc_mem_block ** const outputPP) { /*---------------------------------------------------------------------------- Escape & and < in a UTF-8 string so as to make it suitable for the content of an XML element. I.e. turn them into entity references &amp; and &lt;. Also change > to &gt;, even though not required for XML, for symmetry. &lt; etc. are known in XML as "entity references." Also Escape CR as &#x0d; . While raw CR _is_ allowed in the content of an XML element, it has a special meaning -- it means line ending. Our input uses LF for for line endings. Since it also means line ending in XML, we just pass it through to our output like it were a regular character. &#x0d; is known in XML as a "character reference." We assume chars[] is is ASCII. That isn't right -- we should handle all valid UTF-8. Someday, we must do something more complex and copy over multibyte characters verbatim. (The code here could erroneously find that e.g. the 2nd byte of a UTF-8 character is a CR). -----------------------------------------------------------------------------*/ xmlrpc_mem_block * outputP; size_t outputSize; XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(chars != NULL); assertValidUtf8(chars, len); /* Note that in UTF-8, any byte that has high bit of zero is a character all by itself (every byte of a multi-byte UTF-8 character has the high bit set). Also, the Unicode code points < 128 are identical to the ASCII ones. */ outputSize = escapedSize(chars, len); outputP = XMLRPC_MEMBLOCK_NEW(char, envP, outputSize); if (!envP->fault_occurred) { char * p; size_t i; p = XMLRPC_MEMBLOCK_CONTENTS(char, outputP); /* Start at beginning */ for (i = 0; i < len; i++) { if (chars[i] == '<') { memcpy(p, "&lt;", 4); p += 4; } else if (chars[i] == '>') { memcpy(p, "&gt;", 4); p += 4; } else if (chars[i] == '&') { memcpy(p, "&amp;", 5); p += 5; } else if (chars[i] == '\r') { memcpy(p, "&#x0d;", 6); p += 6; } else { /* Either a plain character or a LF line delimiter */ *p = chars[i]; p += 1; } } *outputPP = outputP; assert(p == XMLRPC_MEMBLOCK_CONTENTS(char, outputP) + outputSize); if (envP->fault_occurred) XMLRPC_MEMBLOCK_FREE(char, outputP); } } static void serializeUtf8MemBlock(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_mem_block * const inputP) { /*---------------------------------------------------------------------------- Append the characters in *inputP to the XML stream in *outputP. *inputP contains Unicode characters in UTF-8. We assume *inputP ends with a NUL character that marks end of string, and we ignore that. (There might also be NUL characters inside the string, though). -----------------------------------------------------------------------------*/ xmlrpc_mem_block * escapedP; XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT(inputP != NULL); escapeForXml(envP, XMLRPC_MEMBLOCK_CONTENTS(const char, inputP), XMLRPC_MEMBLOCK_SIZE(const char, inputP) - 1, /* -1 is for the terminating NUL */ &escapedP); if (!envP->fault_occurred) { const char * const contents = XMLRPC_MEMBLOCK_CONTENTS(const char, escapedP); size_t const size = XMLRPC_MEMBLOCK_SIZE(char, escapedP); XMLRPC_MEMBLOCK_APPEND(char, envP, outputP, contents, size); XMLRPC_MEMBLOCK_FREE(const char, escapedP); } } static void xmlrpc_serialize_base64_data(xmlrpc_env * const envP, xmlrpc_mem_block * const output, unsigned char * const data, size_t const len) { /*---------------------------------------------------------------------------- Encode the 'len' bytes at 'data' in base64 ASCII and append the result to 'output'. -----------------------------------------------------------------------------*/ xmlrpc_mem_block * encoded; encoded = xmlrpc_base64_encode(envP, data, len); if (!envP->fault_occurred) { unsigned char * const contents = XMLRPC_MEMBLOCK_CONTENTS(unsigned char, encoded); size_t const size = XMLRPC_MEMBLOCK_SIZE(unsigned char, encoded); XMLRPC_MEMBLOCK_APPEND(char, envP, output, contents, size); XMLRPC_MEMBLOCK_FREE(char, encoded); } } static void serializeDatetime(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP) { /*---------------------------------------------------------------------------- Add to *outputP the content of a <value> element to represent the datetime value *valueP. I.e. "<dateTime.iso8601> ... </dateTime.iso8601>". -----------------------------------------------------------------------------*/ addString(envP, outputP, "<dateTime.iso8601>"); if (!envP->fault_occurred) { char dtString[64]; snprintf(dtString, sizeof(dtString), "%u%02u%02uT%02u:%02u:%02u", valueP->_value.dt.Y, valueP->_value.dt.M, valueP->_value.dt.D, valueP->_value.dt.h, valueP->_value.dt.m, valueP->_value.dt.s); if (valueP->_value.dt.u != 0) { char usecString[64]; assert(valueP->_value.dt.u < 1000000); snprintf(usecString, sizeof(usecString), ".%06u", valueP->_value.dt.u); STRSCAT(dtString, usecString); } addString(envP, outputP, dtString); if (!envP->fault_occurred) { addString(envP, outputP, "</dateTime.iso8601>"); } } } static void serializeStructMember(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const memberKeyP, xmlrpc_value * const memberValueP, xmlrpc_dialect const dialect) { addString(envP, outputP, "<member><name>"); if (!envP->fault_occurred) { serializeUtf8MemBlock(envP, outputP, &memberKeyP->_block); if (!envP->fault_occurred) { addString(envP, outputP, "</name>"CRLF); if (!envP->fault_occurred) { xmlrpc_serialize_value2(envP, outputP, memberValueP, dialect); if (!envP->fault_occurred) { addString(envP, outputP, "</member>"CRLF); } } } } } static void serializeStruct(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const structP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Add to *outputP the content of a <value> element to represent the structure value *valueP. I.e. "<struct> ... </struct>". -----------------------------------------------------------------------------*/ addString(envP, outputP, "<struct>"CRLF); if (!envP->fault_occurred) { unsigned int const size = xmlrpc_struct_size(envP, structP); if (!envP->fault_occurred) { unsigned int i; for (i = 0; i < size && !envP->fault_occurred; ++i) { xmlrpc_value * memberKeyP; xmlrpc_value * memberValueP; xmlrpc_struct_get_key_and_value(envP, structP, i, &memberKeyP, &memberValueP); if (!envP->fault_occurred) { serializeStructMember(envP, outputP, memberKeyP, memberValueP, dialect); } } if (!envP->fault_occurred) addString(envP, outputP, "</struct>"); } } } static void serializeArray(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Add to *outputP the content of a <value> element to represent the array value *valueP. I.e. "<array> ... </array>". -----------------------------------------------------------------------------*/ int const size = xmlrpc_array_size(envP, valueP); if (!envP->fault_occurred) { addString(envP, outputP, "<array><data>"CRLF); if (!envP->fault_occurred) { int i; /* Serialize each item. */ for (i = 0; i < size && !envP->fault_occurred; ++i) { xmlrpc_value * const itemP = xmlrpc_array_get_item(envP, valueP, i); if (!envP->fault_occurred) { xmlrpc_serialize_value2(envP, outputP, itemP, dialect); if (!envP->fault_occurred) addString(envP, outputP, CRLF); } } } } if (!envP->fault_occurred) addString(envP, outputP, "</data></array>"); } static void formatValueContent(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Add to *outputP the content of a <value> element to represent value *valueP. E.g. "<int>42</int>" -----------------------------------------------------------------------------*/ XMLRPC_ASSERT_ENV_OK(envP); switch (valueP->_type) { case XMLRPC_TYPE_INT: formatOut(envP, outputP, "<i4>%d</i4>", valueP->_value.i); break; case XMLRPC_TYPE_I8: { const char * const elemName = dialect == xmlrpc_dialect_apache ? "ex:i8" : "i8"; formatOut(envP, outputP, "<%s>%" PRId64 "</%s>", elemName, valueP->_value.i8, elemName); } break; case XMLRPC_TYPE_BOOL: formatOut(envP, outputP, "<boolean>%s</boolean>", valueP->_value.b ? "1" : "0"); break; case XMLRPC_TYPE_DOUBLE: { const char * serializedValue; xmlrpc_formatFloat(envP, valueP->_value.d, &serializedValue); if (!envP->fault_occurred) { addString(envP, outputP, "<double>"); if (!envP->fault_occurred) { addString(envP, outputP, serializedValue); if (!envP->fault_occurred) addString(envP, outputP, "</double>"); } xmlrpc_strfree(serializedValue); } } break; case XMLRPC_TYPE_DATETIME: serializeDatetime(envP, outputP, valueP); break; case XMLRPC_TYPE_STRING: addString(envP, outputP, "<string>"); if (!envP->fault_occurred) { serializeUtf8MemBlock(envP, outputP, &valueP->_block); if (!envP->fault_occurred) addString(envP, outputP, "</string>"); } break; case XMLRPC_TYPE_BASE64: { unsigned char * const contents = XMLRPC_MEMBLOCK_CONTENTS(unsigned char, &valueP->_block); size_t const size = XMLRPC_MEMBLOCK_SIZE(unsigned char, &valueP->_block); addString(envP, outputP, "<base64>"CRLF); if (!envP->fault_occurred) { xmlrpc_serialize_base64_data(envP, outputP, contents, size); if (!envP->fault_occurred) addString(envP, outputP, "</base64>"); } } break; case XMLRPC_TYPE_ARRAY: serializeArray(envP, outputP, valueP, dialect); break; case XMLRPC_TYPE_STRUCT: serializeStruct(envP, outputP, valueP, dialect); break; case XMLRPC_TYPE_C_PTR: xmlrpc_faultf(envP, "Tried to serialize a C pointer value."); break; case XMLRPC_TYPE_NIL: { const char * const elemName = dialect == xmlrpc_dialect_apache ? "ex:nil" : "nil"; formatOut(envP, outputP, "<%s/>", elemName); } break; case XMLRPC_TYPE_DEAD: xmlrpc_faultf(envP, "Tried to serialize a dead value."); break; default: xmlrpc_faultf(envP, "Invalid xmlrpc_value type: %d", valueP->_type); } } void xmlrpc_serialize_value2(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Generate the XML to represent XML-RPC value 'valueP' in XML-RPC. Add it to *outputP. -----------------------------------------------------------------------------*/ XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT_VALUE_OK(valueP); addString(envP, outputP, "<value>"); if (!envP->fault_occurred) { formatValueContent(envP, outputP, valueP, dialect); if (!envP->fault_occurred) addString(envP, outputP, "</value>"); } } void xmlrpc_serialize_value(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP) { xmlrpc_serialize_value2(envP, outputP, valueP, xmlrpc_dialect_i8); } void xmlrpc_serialize_params2(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const paramArrayP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Serialize the parameter list of an XML-RPC call. -----------------------------------------------------------------------------*/ XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT_VALUE_OK(paramArrayP); addString(envP, outputP, "<params>"CRLF); if (!envP->fault_occurred) { /* Serialize each parameter. */ int const paramCount = xmlrpc_array_size(envP, paramArrayP); if (!envP->fault_occurred) { int paramSeq; for (paramSeq = 0; paramSeq < paramCount && !envP->fault_occurred; ++paramSeq) { addString(envP, outputP, "<param>"); if (!envP->fault_occurred) { xmlrpc_value * const itemP = xmlrpc_array_get_item(envP, paramArrayP, paramSeq); if (!envP->fault_occurred) { xmlrpc_serialize_value2(envP, outputP, itemP, dialect); if (!envP->fault_occurred) addString(envP, outputP, "</param>"CRLF); } } } } } if (!envP->fault_occurred) addString(envP, outputP, "</params>"CRLF); } void xmlrpc_serialize_params(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const paramArrayP) { /*---------------------------------------------------------------------------- Serialize the parameter list of an XML-RPC call in the original "i8" dialect. -----------------------------------------------------------------------------*/ xmlrpc_serialize_params2(envP, outputP, paramArrayP, xmlrpc_dialect_i8); } /*========================================================================= ** xmlrpc_serialize_call **========================================================================= ** Serialize an XML-RPC call. */ void xmlrpc_serialize_call2(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, const char * const methodName, xmlrpc_value * const paramArrayP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Serialize an XML-RPC call of method named 'methodName' with parameter list *paramArrayP. Use XML-RPC dialect 'dialect'. Append the call XML ot *outputP. -----------------------------------------------------------------------------*/ XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT(methodName != NULL); XMLRPC_ASSERT_VALUE_OK(paramArrayP); addString(envP, outputP, XML_PROLOGUE); if (!envP->fault_occurred) { const char * const xmlns = dialect == xmlrpc_dialect_apache ? " " XMLNS_APACHE : ""; formatOut(envP, outputP, "<methodCall%s>"CRLF"<methodName>", xmlns); if (!envP->fault_occurred) { xmlrpc_mem_block * encodedP; escapeForXml(envP, methodName, strlen(methodName), &encodedP); if (!envP->fault_occurred) { const char * const contents = XMLRPC_MEMBLOCK_CONTENTS(char, encodedP); size_t const size = XMLRPC_MEMBLOCK_SIZE(char, encodedP); XMLRPC_MEMBLOCK_APPEND(char, envP, outputP, contents, size); if (!envP->fault_occurred) { addString(envP, outputP, "</methodName>"CRLF); if (!envP->fault_occurred) { xmlrpc_serialize_params2(envP, outputP, paramArrayP, dialect); if (!envP->fault_occurred) addString(envP, outputP, "</methodCall>"CRLF); } } XMLRPC_MEMBLOCK_FREE(char, encodedP); } } } } void xmlrpc_serialize_call(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, const char * const methodName, xmlrpc_value * const paramArrayP) { xmlrpc_serialize_call2(envP, outputP, methodName, paramArrayP, xmlrpc_dialect_i8); } void xmlrpc_serialize_response2(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP, xmlrpc_dialect const dialect) { /*---------------------------------------------------------------------------- Serialize a result response to an XML-RPC call. The result is 'valueP'. Add the response XML to *outputP. -----------------------------------------------------------------------------*/ XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT_VALUE_OK(valueP); addString(envP, outputP, XML_PROLOGUE); if (!envP->fault_occurred) { const char * const xmlns = dialect == xmlrpc_dialect_apache ? " " XMLNS_APACHE : ""; formatOut(envP, outputP, "<methodResponse%s>"CRLF"<params>"CRLF"<param>", xmlns); if (!envP->fault_occurred) { xmlrpc_serialize_value2(envP, outputP, valueP, dialect); if (!envP->fault_occurred) { addString(envP, outputP, "</param>"CRLF"</params>"CRLF "</methodResponse>"CRLF); } } } } void xmlrpc_serialize_response(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, xmlrpc_value * const valueP) { xmlrpc_serialize_response2(envP, outputP, valueP, xmlrpc_dialect_i8); } void xmlrpc_serialize_fault(xmlrpc_env * const envP, xmlrpc_mem_block * const outputP, const xmlrpc_env * const faultP) { /*---------------------------------------------------------------------------- Serialize a fault response to an XML-RPC call. 'faultP' is the fault. Add the response XML to *outputP. -----------------------------------------------------------------------------*/ xmlrpc_value * faultStructP; XMLRPC_ASSERT_ENV_OK(envP); XMLRPC_ASSERT(outputP != NULL); XMLRPC_ASSERT(faultP != NULL); XMLRPC_ASSERT(faultP->fault_occurred); faultStructP = xmlrpc_build_value(envP, "{s:i,s:s}", "faultCode", (xmlrpc_int32) faultP->fault_code, "faultString", faultP->fault_string); if (!envP->fault_occurred) { addString(envP, outputP, XML_PROLOGUE); if (!envP->fault_occurred) { addString(envP, outputP, "<methodResponse>"CRLF"<fault>"CRLF); if (!envP->fault_occurred) { xmlrpc_serialize_value(envP, outputP, faultStructP); if (!envP->fault_occurred) { addString(envP, outputP, CRLF"</fault>"CRLF"</methodResponse>"CRLF); } } } xmlrpc_DECREF(faultStructP); } } /* Copyright (C) 2001 by First Peer, Inc. All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ** ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF ** SUCH DAMAGE. */
JMSDOnline/QuickBox
xmlrpc-c_1-33-12/src/xmlrpc_serialize.c
C
gpl-3.0
27,268
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef _PRIORITYQUEUE_H_ #define _PRIORITYQUEUE_H_ #include <algorithm> namespace vcg { /** Implements a bounded-size max priority queue using a heap */ template <typename Index, typename Weight> class HeapMaxPriorityQueue { struct Element { Weight weight; Index index; }; struct { bool operator()(const Element& a, const Element& b) const { return a.weight < b.weight; } } lessElement; struct { bool operator()(const Element& a, const Element& b) const { return a.weight > b.weight; } } greaterElement; public: HeapMaxPriorityQueue(void) { mElements = 0; mMaxSize = 0; } ~HeapMaxPriorityQueue() { if (mElements) delete[] mElements; } inline void setMaxSize(int maxSize) { if (mMaxSize!=maxSize) { mMaxSize = maxSize; delete[] mElements; mElements = new Element[mMaxSize]; mpOffsetedElements = (mElements-1); } init(); } inline void init() { mCount = 0; } inline bool isFull() const { return mCount == mMaxSize; } /** returns number of elements inserted in queue */ inline int getNofElements() const { return mCount; } inline Weight getWeight(int i) const { return mElements[i].weight; } inline Index getIndex(int i) const { return mElements[i].index; } inline Weight getTopWeight() const { return mElements[0].weight; } inline void insert(Index index, Weight weight) { if (mCount==mMaxSize) { if (weight<mElements[0].weight) { int j, k; j = 1; k = 2; while (k <= mMaxSize) { Element* z = &(mpOffsetedElements[k]); if ((k < mMaxSize) && (z->weight < mpOffsetedElements[k+1].weight)) z = &(mpOffsetedElements[++k]); if(weight >= z->weight) break; mpOffsetedElements[j] = *z; j = k; k = 2 * j; } mpOffsetedElements[j].weight = weight; mpOffsetedElements[j].index = index; } } else { int i, j; i = ++mCount; while (i >= 2) { j = i >> 1; Element& y = mpOffsetedElements[j]; if(weight <= y.weight) break; mpOffsetedElements[i] = y; i = j; } mpOffsetedElements[i].index = index; mpOffsetedElements[i].weight = weight; } } inline void sort(bool ascending = true) { if (ascending) std::sort(mElements, mElements + mCount, lessElement); else std::sort(mElements, mElements + mCount, greaterElement); } protected: int mCount; int mMaxSize; Element* mElements; Element* mpOffsetedElements; }; } #endif
cnr-isti-vclab/vcglib
vcg/space/index/kdtree/priorityqueue.h
C
gpl-3.0
4,630
/* * ProFTPD - mod_sftp RFC4716 keystore * Copyright (c) 2008-2011 TJ Saunders * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. * * As a special exemption, TJ Saunders and other respective copyright holders * give permission to link this program with OpenSSL, and distribute the * resulting executable, without including the source code for OpenSSL in the * source distribution. * * $Id: rfc4716.c,v 1.15 2011/05/23 21:03:12 castaglia Exp $ */ #include "mod_sftp.h" #include "keys.h" #include "keystore.h" #include "crypto.h" #include "rfc4716.h" /* File-based keystore implementation */ struct filestore_key { /* Supported headers. We don't really care about the Comment header * at the moment. */ const char *subject; /* Key data */ char *key_data; uint32_t key_datalen; }; struct filestore_data { pr_fh_t *fh; const char *path; unsigned int lineno; }; static const char *trace_channel = "ssh2"; /* This getline() function is quite similar to pr_fsio_getline(), except * that it a) enforces the 72-byte max line length from RFC4716, and * properly handles lines ending with CR, LF, or CRLF. * * Technically it allows one more byte than necessary, since the worst case * is 74 bytes (72 + CRLF); this also means 73 + CR or 73 + LF. The extra * byte is for the terminating NUL. */ static char *filestore_getline(sftp_keystore_t *store, pool *p) { char linebuf[75], *line = "", *res; struct filestore_data *store_data = store->keystore_data; while (TRUE) { size_t linelen; pr_signals_handle(); memset(&linebuf, '\0', sizeof(linebuf)); res = pr_fsio_gets(linebuf, sizeof(linebuf) - 1, store_data->fh); if (res == NULL) { if (errno == EINTR) { continue; } pr_trace_msg(trace_channel, 10, "reached end of '%s', no matching " "key found", store_data->path); errno = EOF; return NULL; } linelen = strlen(linebuf); if (linelen >= 1) { if (linebuf[linelen - 1] == '\r' || linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else if (linelen >= 2 && linebuf[linelen - 2] == '\r' && linebuf[linelen - 1] == '\n') { char *tmp; unsigned int header_taglen, header_valuelen; int have_line_continuation = FALSE; store_data->lineno++; linebuf[linelen - 2] = '\0'; linebuf[linelen - 1] = '\0'; line = pstrcat(p, line, linebuf, NULL); if (line[strlen(line) - 1] == '\\') { have_line_continuation = TRUE; line[strlen(line) - 1] = '\0'; } tmp = strchr(line, ':'); if (tmp == NULL) { return line; } /* We have a header. Make sure the header tag is not longer than * the specified length of 64 bytes, and that the header value is * not longer than 1024 bytes. */ header_taglen = tmp - line; if (header_taglen > 64) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header tag too long (%u) on line %u of '%s'", header_taglen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } /* Header value starts at 2 after the ':' (one for the mandatory * space character. */ header_valuelen = strlen(line) - (header_taglen + 2); if (header_valuelen > 1024) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "header value too long (%u) on line %u of '%s'", header_valuelen, store_data->lineno, store_data->path); errno = EINVAL; return NULL; } if (!have_line_continuation) { return line; } continue; } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "line too long (%lu) on line %u of '%s'", (unsigned long) linelen, store_data->lineno, store_data->path); (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "Make sure that '%s' is a RFC4716 formatted key", store_data->path); errno = EINVAL; return NULL; } } } /* Should not be reached. */ return NULL; } static struct filestore_key *filestore_get_key(sftp_keystore_t *store, pool *p) { char *line; BIO *bio = NULL; struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; size_t begin_markerlen = 0, end_markerlen = 0; line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } begin_markerlen = strlen(SFTP_SSH2_PUBKEY_BEGIN_MARKER); end_markerlen = strlen(SFTP_SSH2_PUBKEY_END_MARKER); while (line) { pr_signals_handle(); if (key == NULL && strncmp(line, SFTP_SSH2_PUBKEY_BEGIN_MARKER, begin_markerlen + 1) == 0) { key = pcalloc(p, sizeof(struct filestore_key)); bio = BIO_new(BIO_s_mem()); } else if (key != NULL && strncmp(line, SFTP_SSH2_PUBKEY_END_MARKER, end_markerlen + 1) == 0) { if (bio) { BIO *b64 = NULL, *bmem = NULL; char chunk[1024], *data = NULL; int chunklen; long datalen = 0; /* Add a base64 filter BIO, and read the data out, thus base64-decoding * the key. Write the decoded data into another memory BIO. */ b64 = BIO_new(BIO_f_base64()); BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); bio = BIO_push(b64, bio); bmem = BIO_new(BIO_s_mem()); memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); if (chunklen < 0 && !BIO_should_retry(bio)) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "unable to base64-decode data in '%s': %s", store_data->path, sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } while (chunklen > 0) { pr_signals_handle(); if (BIO_write(bmem, chunk, chunklen) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error writing to memory BIO: %s", sftp_crypto_get_errors()); BIO_free_all(bio); BIO_free_all(bmem); errno = EPERM; return NULL; } memset(chunk, '\0', sizeof(chunk)); chunklen = BIO_read(bio, chunk, sizeof(chunk)); } datalen = BIO_get_mem_data(bmem, &data); if (data != NULL && datalen > 0) { key->key_data = pcalloc(p, datalen + 1); key->key_datalen = datalen; memcpy(key->key_data, data, datalen); } else { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error base64-decoding key data in '%s'", store_data->path); } BIO_free_all(bio); bio = NULL; BIO_free_all(bmem); } break; } else { if (key) { if (strstr(line, ": ") != NULL) { if (strncasecmp(line, "Subject: ", 9) == 0) { key->subject = pstrdup(p, line + 9); } } else { if (BIO_write(bio, line, strlen(line)) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error buffering base64 data"); } } } } line = filestore_getline(store, p); while (line == NULL && errno == EINVAL) { line = filestore_getline(store, p); } } return key; } static int filestore_verify_host_key(sftp_keystore_t *store, pool *p, const char *user, const char *host_fqdn, const char *host_user, char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } } else { /* XXX Verify that the user and the host_user match?? */ res = 0; break; } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for host '%s' " "in '%s'", host_fqdn, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_verify_user_key(sftp_keystore_t *store, pool *p, const char *user, char *key_data, uint32_t key_len) { struct filestore_key *key = NULL; struct filestore_data *store_data = store->keystore_data; int res = -1; if (!store_data->path) { errno = EPERM; return -1; } /* XXX Note that this will scan the file from the beginning, each time. * There's room for improvement; perhaps mmap() the file into memory? */ key = filestore_get_key(store, p); while (key) { int ok; pr_signals_handle(); ok = sftp_keys_compare_keys(p, key_data, key_len, key->key_data, key->key_datalen); if (ok != TRUE) { if (ok == -1) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error comparing keys from '%s': %s", store_data->path, strerror(errno)); } } else { /* If we are configured to check for Subject headers, and If the file key * has a Subject header, and that header value does not match the * logging in user, then continue looking. */ if ((sftp_opts & SFTP_OPT_MATCH_KEY_SUBJECT) && key->subject != NULL) { if (strcmp(key->subject, user) != 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "found matching key for user '%s' in '%s', but Subject " "header ('%s') does not match, skipping key", user, store_data->path, key->subject); } else { res = 0; break; } } else { res = 0; break; } } key = filestore_get_key(store, p); } if (res == 0) { pr_trace_msg(trace_channel, 10, "found matching public key for user '%s' " "in '%s'", user, store_data->path); } if (pr_fsio_lseek(store_data->fh, 0, SEEK_SET) < 0) { (void) pr_log_writefile(sftp_logfd, MOD_SFTP_VERSION, "error seeking to start of '%s': %s", store_data->path, strerror(errno)); return -1; } store_data->lineno = 0; return res; } static int filestore_close(sftp_keystore_t *store) { struct filestore_data *store_data = store->keystore_data; pr_fsio_close(store_data->fh); return 0; } static sftp_keystore_t *filestore_open(pool *parent_pool, int requested_key_type, const char *store_info, const char *user) { int xerrno; sftp_keystore_t *store; pool *filestore_pool; struct filestore_data *store_data; pr_fh_t *fh; char buf[PR_TUNABLE_PATH_MAX+1], *path; struct stat st; filestore_pool = make_sub_pool(parent_pool); pr_pool_tag(filestore_pool, "SFTP File-based Keystore Pool"); store = pcalloc(filestore_pool, sizeof(sftp_keystore_t)); store->keystore_pool = filestore_pool; /* Open the file. The given path (store_info) may need to be * interpolated. */ session.user = (char *) user; memset(buf, '\0', sizeof(buf)); switch (pr_fs_interpolate(store_info, buf, sizeof(buf)-1)) { case 1: /* Interpolate occurred; make a copy of the interpolated path. */ path = pstrdup(filestore_pool, buf); break; default: /* Otherwise, use the path as is. */ path = pstrdup(filestore_pool, store_info); break; } session.user = NULL; PRIVS_ROOT fh = pr_fsio_open(path, O_RDONLY|O_NONBLOCK); xerrno = errno; PRIVS_RELINQUISH if (fh == NULL) { destroy_pool(filestore_pool); errno = xerrno; return NULL; } pr_fsio_set_block(fh); /* Stat the opened file to determine the optimal buffer size for IO. */ memset(&st, 0, sizeof(st)); pr_fsio_fstat(fh, &st); fh->fh_iosz = st.st_blksize; store_data = pcalloc(filestore_pool, sizeof(struct filestore_data)); store->keystore_data = store_data; store_data->path = path; store_data->fh = fh; store_data->lineno = 0; store->store_ktypes = requested_key_type; switch (requested_key_type) { case SFTP_SSH2_HOST_KEY_STORE: store->verify_host_key = filestore_verify_host_key; break; case SFTP_SSH2_USER_KEY_STORE: store->verify_user_key = filestore_verify_user_key; break; } store->store_close = filestore_close; return store; } int sftp_rfc4716_init(void) { sftp_keystore_register_store("file", filestore_open, SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; } int sftp_rfc4716_free(void) { sftp_keystore_unregister_store("file", SFTP_SSH2_HOST_KEY_STORE|SFTP_SSH2_USER_KEY_STORE); return 0; }
xichy/proftpd_optimize_xferlog
proftpd-1.3.4a/contrib/mod_sftp/rfc4716.c
C
gpl-3.0
15,746
#include "booksim.hpp" #include <map> #include <stdlib.h> #include "traffic.hpp" #include "network.hpp" #include "random_utils.hpp" #include "misc_utils.hpp" map<string, tTrafficFunction> gTrafficFunctionMap; int gResetTraffic = 0; int gStepTraffic = 0; void src_dest_bin( int source, int dest, int lg ) { int b, t; cout << "from: "; t = source; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << " to "; t = dest; for ( b = 0; b < lg; ++b ) { cout << ( ( t >> ( lg - b - 1 ) ) & 0x1 ); } cout << endl; } //============================================================= int uniform( int source, int total_nodes ) { return RandomInt( total_nodes - 1 ); } //============================================================= int bitcomp( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask = total_nodes - 1; int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitcomp' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ~source ) & mask; return dest; } //============================================================= int transpose( int source, int total_nodes ) { int lg = log_two( total_nodes ); int mask_lo = (1 << (lg/2)) - 1; int mask_hi = mask_lo << (lg/2); int dest; if ( ( ( 1 << lg ) != total_nodes ) || ( lg & 0x1 ) ) { cout << "Error: The 'transpose' traffic pattern requires the number of" << " nodes to be an even power of two!" << endl; exit(-1); } dest = ( ( source >> (lg/2) ) & mask_lo ) | ( ( source << (lg/2) ) & mask_hi ); return dest; } //============================================================= int bitrev( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'bitrev' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } // If you were fancy you could do this in O(log log total_nodes) // instructions, but I'm not dest = 0; for ( int b = 0; b < lg; ++b ) { dest |= ( ( source >> b ) & 0x1 ) << ( lg - b - 1 ); } return dest; } //============================================================= int shuffle( int source, int total_nodes ) { int lg = log_two( total_nodes ); int dest; if ( ( 1 << lg ) != total_nodes ) { cout << "Error: The 'shuffle' traffic pattern requires the number of" << " nodes to be a power of two!" << endl; exit(-1); } dest = ( ( source << 1 ) & ( total_nodes - 1 ) ) | ( ( source >> ( lg - 1 ) ) & 0x1 ); return dest; } //============================================================= int tornado( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < gN; ++n ) { dest += offset * ( ( ( source / offset ) % gK + ( gK/2 - 1 ) ) % gK ); offset *= gK; } return dest; } //============================================================= int neighbor( int source, int total_nodes ) { int offset = 1; int dest = 0; for ( int n = 0; n < gN; ++n ) { dest += offset * ( ( ( source / offset ) % gK + 1 ) % gK ); offset *= gK; } return dest; } //============================================================= int *gPerm = 0; int gPermSeed; void GenerateRandomPerm( int total_nodes ) { int ind; int i,j; int cnt; unsigned long prev_rand; prev_rand = RandomIntLong( ); RandomSeed( gPermSeed ); if ( !gPerm ) { gPerm = new int [total_nodes]; } for ( i = 0; i < total_nodes; ++i ) { gPerm[i] = -1; } for ( i = 0; i < total_nodes; ++i ) { ind = RandomInt( total_nodes - 1 - i ); j = 0; cnt = 0; while ( ( cnt < ind ) || ( gPerm[j] != -1 ) ) { if ( gPerm[j] == -1 ) { ++cnt; } ++j; if ( j >= total_nodes ) { cout << "ERROR: GenerateRandomPerm( ) internal error" << endl; exit(-1); } } gPerm[j] = i; } RandomSeed( prev_rand ); } int randperm( int source, int total_nodes ) { if ( gResetTraffic || !gPerm ) { GenerateRandomPerm( total_nodes ); gResetTraffic = 0; } return gPerm[source]; } //============================================================= int diagonal( int source, int total_nodes ) { int t = RandomInt( 2 ); int d; // 2/3 of traffic goes from source->source // 1/3 of traffic goes from source->(source+1)%total_nodes if ( t == 0 ) { d = ( source + 1 ) % total_nodes; } else { d = source; } return d; } //============================================================= int asymmetric( int source, int total_nodes ) { int d; int half = total_nodes / 2; d = ( source % half ) + RandomInt( 1 ) * half; return d; } //============================================================= void InitializeTrafficMap( ) { /* Register Traffic functions here */ gTrafficFunctionMap["uniform"] = &uniform; // "Bit" patterns gTrafficFunctionMap["bitcomp"] = &bitcomp; gTrafficFunctionMap["bitrev"] = &bitrev; gTrafficFunctionMap["transpose"] = &transpose; gTrafficFunctionMap["shuffle"] = &shuffle; // "Digit" patterns gTrafficFunctionMap["tornado"] = &tornado; gTrafficFunctionMap["neighbor"] = &neighbor; // Other patterns gTrafficFunctionMap["randperm"] = &randperm; gTrafficFunctionMap["diagonal"] = &diagonal; gTrafficFunctionMap["asymmetric"] = &asymmetric; } void ResetTrafficFunction( ) { gResetTraffic++; } void StepTrafficFunction( ) { gStepTraffic++; } tTrafficFunction GetTrafficFunction( const Configuration& config ) { map<string, tTrafficFunction>::const_iterator match; tTrafficFunction tf; string fn; config.GetStr( "traffic", fn, "none" ); match = gTrafficFunctionMap.find( fn ); if ( match != gTrafficFunctionMap.end( ) ) { tf = match->second; } else { cout << "Error: Undefined traffic pattern '" << fn << "'." << endl; exit(-1); } gPermSeed = config.GetInt( "perm_seed" ); return tf; }
ray-chu/gpgpu-sim-test
v3.x/src/intersim/traffic.cpp
C++
gpl-3.0
6,664
// Copyright (c) 2009, Yves Goergen, http://unclassified.software/source/progressspinner // // Copying and distribution of this file, with or without modification, are permitted provided the // copyright notice and this notice are preserved. This file is offered as-is, without any warranty. using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Unclassified.UI { public class ProgressSpinner : Control { #region Designer code private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion Designer code private Timer timer; private int progress; private int minimum = 0; private int maximum = 100; private float angle = 270; private bool ensureVisible = true; private float speed; private bool backwards; /// <summary> /// Gets or sets a value indicating whether the progress spinner is spinning. /// </summary> [DefaultValue(false)] [Description("Specifies whether the progress spinner is spinning.")] [Category("Behavior")] public bool Spinning { get { return timer.Enabled; } set { timer.Enabled = value; } } /// <summary> /// Gets or sets the current progress value. Set -1 to indicate that the current progress is unknown. /// </summary> [DefaultValue(0)] [Description("The current progress value. Set -1 to indicate that the current progress is unknown.")] [Category("Appearance")] public int Value { get { return progress; } set { if (value != -1 && (value < minimum || value > maximum)) throw new ArgumentOutOfRangeException("Progress value must be -1 or between Minimum and Maximum.", (Exception)null); progress = value; Refresh(); } } /// <summary> /// Gets or sets the minimum progress value. /// </summary> [DefaultValue(0)] [Description("The minimum progress value.")] [Category("Appearance")] public int Minimum { get { return minimum; } set { if (value < 0) throw new ArgumentOutOfRangeException("Minimum value must be >= 0.", (Exception)null); if (value >= maximum) throw new ArgumentOutOfRangeException("Minimum value must be < Maximum.", (Exception)null); minimum = value; if (progress != -1 && progress < minimum) progress = minimum; Refresh(); } } /// <summary> /// Gets or sets the maximum progress value. /// </summary> [DefaultValue(0)] [Description("The maximum progress value.")] [Category("Appearance")] public int Maximum { get { return maximum; } set { if (value <= minimum) throw new ArgumentOutOfRangeException("Maximum value must be > Minimum.", (Exception)null); maximum = value; if (progress > maximum) progress = maximum; Refresh(); } } /// <summary> /// Gets or sets a value indicating whether the progress spinner should be visible at all progress values. /// </summary> [DefaultValue(true)] [Description("Specifies whether the progress spinner should be visible at all progress values.")] [Category("Appearance")] public bool EnsureVisible { get { return ensureVisible; } set { ensureVisible = value; Refresh(); } } /// <summary> /// Gets or sets the speed factor. 1 is the original speed, less is slower, greater is faster. /// </summary> [DefaultValue(1f)] [Description("The speed factor. 1 is the original speed, less is slower, greater is faster.")] [Category("Behavior")] public float Speed { get { return speed; } set { if (value <= 0 || value > 10) throw new ArgumentOutOfRangeException("Speed value must be > 0 and <= 10.", (Exception)null); speed = value; } } /// <summary> /// Gets or sets a value indicating whether the progress spinner should spin anti-clockwise. /// </summary> [DefaultValue(false)] [Description("Specifies whether the progress spinner should spin anti-clockwise.")] [Category("Behavior")] public bool Backwards { get { return backwards; } set { backwards = value; Refresh(); } } #region Hidden properties [Browsable(false)] public override Font Font { get { return base.Font; } set { base.Font = value; } } [Browsable(false)] public override string Text { get { return base.Text; } set { base.Text = value; } } [Browsable(false)] public new int TabIndex { get { return 0; } set { } } [Browsable(false)] public new bool TabStop { get { return false; } set { } } #endregion Hidden properties public ProgressSpinner() { InitializeComponent(); timer = new Timer(); timer.Interval = 20; timer.Tick += timer_Tick; Width = 16; Height = 16; speed = 1; DoubleBuffered = true; ForeColor = SystemColors.Highlight; } /// <summary> /// Resets the progress spinner's status. /// </summary> public void Reset() { progress = minimum; angle = 270; Refresh(); } private void timer_Tick(object sender, EventArgs args) { angle += 6f * speed * (backwards ? -1 : 1); Refresh(); } protected override void OnPaint(PaintEventArgs pe) { Pen forePen = new Pen(ForeColor, (float)Width / 5); int padding = (int)Math.Ceiling((float)Width / 10); pe.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; // Draw spinner pie if (progress != -1) { // We have a progress value, draw a solid arc line // angle is the back end of the line. // angle +/- progress is the front end of the line float sweepAngle; float progFrac = (float)(progress - minimum) / (float)(maximum - minimum); if (ensureVisible) sweepAngle = 30 + 300f * progFrac; else sweepAngle = 360f * progFrac; if (backwards) sweepAngle = -sweepAngle; pe.Graphics.DrawArc( forePen, padding, padding, Width - 2 * padding - 1, Height - 2 * padding - 1, angle, sweepAngle); } else { // No progress value, draw a gradient arc line // angle is the opaque front end of the line // angle +/- 180° is the transparent tail end of the line const int maxOffset = 180; for (int offset = 0; offset <= maxOffset; offset += 15) { int alpha = 290 - (offset * 290 / maxOffset); if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; Color col = Color.FromArgb(alpha, forePen.Color); Pen gradPen = new Pen(col, forePen.Width); float startAngle = angle + (offset - (ensureVisible ? 30 : 0)) * (backwards ? 1 : -1); float sweepAngle = 15 * (backwards ? 1 : -1); // draw in reverse direction pe.Graphics.DrawArc( gradPen, padding, padding, Width - 2 * padding - 1, Height - 2 * padding - 1, startAngle, sweepAngle); gradPen.Dispose(); } } forePen.Dispose(); } } }
modulexcite/FieldLog
LogSubmit/Unclassified/UI/ProgressSpinner.cs
C#
gpl-3.0
7,386
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Pysolar.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Pysolar.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Pysolar" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Pysolar" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
pingswept/pysolar
doc/Makefile
Makefile
gpl-3.0
6,766
/* * Software License Agreement (BSD License) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ /* * LinearPipeline.hpp * * @date 13.11.2015 * @author Tristan Igelbrink ([email protected]) */ #ifndef LINEAR_PIPELINE_HPP__ #define LINEAR_PIPELINE_HPP__ #include "BlockingQueue.hpp" #include "AbstractStage.hpp" #include <boost/bind.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> // A class that represents a pipeline that holds numerous stages, and // each stage can be executed concurrently. template<typename WorkTypeA, typename WorkTypeB> class LinearPipeline { public: // Add a stage to the pipeline. The stages are inserted in order, such // that the first added stage will be the first stage, and so on. The // work queues for each stage will be updated automatically. void AddStage(boost::shared_ptr<AbstractStage > stage) { // add a stage m_stages.push_back(stage); size_t numStage = m_stages.size(); // resize the queue accordingly m_queues.resize(numStage+1); // special case for the first stage, where queue[0] needs to // be allocated. if(m_queues[numStage-1] == 0) { m_queues[numStage-1] = boost::shared_ptr<BlockingQueue >( new BlockingQueue() ); } // allocate a queue for the new stage m_queues[numStage] = boost::shared_ptr<BlockingQueue >( new BlockingQueue() ); // initialize the stage with the in and out queue m_stages[numStage-1]->InitQueues( m_queues[numStage-1], m_queues[numStage] ); } // Add work to the first queue, which is the in-queue for the first // stage. void AddWork(WorkTypeA work) { m_queues[0]->Add(work); } // Extract the result from the out-queue of the last stage WorkTypeB GetResult() { return boost::any_cast<WorkTypeB>(m_queues[m_queues.size()-1]->Take()); } // Start all stages by spinning up one thread per stage. void Start() { for(size_t i=0; i<m_stages.size(); ++i) { m_threads.push_back( boost::shared_ptr<boost::thread>(new boost::thread( boost::bind(&LinearPipeline<WorkTypeA, WorkTypeB>::StartStage, this, i) ))); } } // join all stages void join() { for(size_t i=0; i<m_stages.size(); ++i) { m_threads[i]->join(); } } private: void StartStage(size_t index) { m_stages[index]->Run(); } std::vector< boost::shared_ptr<AbstractStage > > m_stages; std::vector< boost::shared_ptr<BlockingQueue > > m_queues; std::vector< boost::shared_ptr<boost::thread> > m_threads; }; #endif // LinearPipeline_h__
spuetz/Las-Vegas-Reconstruction
ext/kintinuous/kfusion/include/kfusion/LinearPipeline.hpp
C++
gpl-3.0
4,173
//CFLAGS:-O0 -c -m32 -mmmx //This is the testcase of bug #514 //This testcase is from gcc regression testsuit #define static #define __inline #include <mmintrin.h>
uhhpctools/openuh-openacc
osprey/testsuite/cases/single_src_cases/misc/mmx_bug_514.c
C
gpl-3.0
164
package bcache import ( "net/http" "github.com/uol/gobol" "github.com/uol/mycenae/lib/tserr" ) func errBasic(f, s string, e error) gobol.Error { if e != nil { return tserr.New( e, s, http.StatusInternalServerError, map[string]interface{}{ "package": "bcache/persistence", "func": f, }, ) } return nil } func errPersist(f string, e error) gobol.Error { return errBasic(f, e.Error(), e) }
lucasdss/mycenae
lib/bcache/errors.go
GO
gpl-3.0
429
<?php /** * Copyright © OXID eSales AG. All rights reserved. * See LICENSE file for license details. */ namespace OxidEsales\EshopCommunity\Tests\Unit\Application\Controller\Admin; /** * Tests for GenImport class */ class GenImportTest extends \OxidTestCase { /** * GenImport::Render() test case * * @return null */ public function testRender() { // testing.. $oView = oxNew('GenImport'); $this->assertEquals('genimport_main.tpl', $oView->render()); } }
michaelkeiluweit/oxideshop_ce
tests/Unit/Application/Controller/Admin/GenImportTest.php
PHP
gpl-3.0
524
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QtQuick/qquickitem.h> #include <QtQuick/qquickview.h> #include <QtGui/qopenglcontext.h> #include <QtGui/qopenglfunctions.h> #include <QtGui/qscreen.h> #include <private/qsgrendernode_p.h> #include "../../shared/util.h" class tst_rendernode: public QQmlDataTest { Q_OBJECT public: tst_rendernode(); QImage runTest(const QString &fileName) { QQuickView view(&outerWindow); view.setResizeMode(QQuickView::SizeViewToRootObject); view.setSource(testFileUrl(fileName)); view.setVisible(true); QTest::qWaitForWindowExposed(&view); return view.grabWindow(); } //It is important for platforms that only are able to show fullscreen windows //to have a container for the window that is painted on. QQuickWindow outerWindow; private slots: void renderOrder(); void messUpState(); void matrix(); }; class ClearNode : public QSGRenderNode { public: StateFlags changedStates() const override { return ColorState; } void render(const RenderState *) override { // If clip has been set, scissoring will make sure the right area is cleared. QOpenGLContext::currentContext()->functions()->glClearColor(color.redF(), color.greenF(), color.blueF(), 1.0f); QOpenGLContext::currentContext()->functions()->glClear(GL_COLOR_BUFFER_BIT); } QColor color; }; class ClearItem : public QQuickItem { Q_OBJECT Q_PROPERTY(QColor color READ color WRITE setColor NOTIFY colorChanged) public: ClearItem() : m_color(Qt::black) { setFlag(ItemHasContents, true); } QColor color() const { return m_color; } void setColor(const QColor &color) { if (color == m_color) return; m_color = color; emit colorChanged(); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { ClearNode *node = static_cast<ClearNode *>(oldNode); if (!node) node = new ClearNode; node->color = m_color; return node; } Q_SIGNALS: void colorChanged(); private: QColor m_color; }; class MessUpNode : public QSGRenderNode, protected QOpenGLFunctions { public: MessUpNode() : initialized(false) { } StateFlags changedStates() const override { return StateFlags(DepthState) | StencilState | ScissorState | ColorState | BlendState | CullState | ViewportState | RenderTargetState; } void render(const RenderState *) override { if (!initialized) { initializeOpenGLFunctions(); initialized = true; } // Don't draw anything, just mess up the state glViewport(10, 10, 10, 10); glDisable(GL_SCISSOR_TEST); glDepthMask(true); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_EQUAL); glClearDepthf(1); glClearStencil(42); glClearColor(1.0f, 0.5f, 1.0f, 0.0f); glClear(GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glEnable(GL_SCISSOR_TEST); glScissor(190, 190, 10, 10); glStencilFunc(GL_EQUAL, 28, 0xff); glBlendFunc(GL_ZERO, GL_ZERO); GLint frontFace; glGetIntegerv(GL_FRONT_FACE, &frontFace); glFrontFace(frontFace == GL_CW ? GL_CCW : GL_CW); glEnable(GL_CULL_FACE); GLuint fbo; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); } bool initialized; }; class MessUpItem : public QQuickItem { Q_OBJECT public: MessUpItem() { setFlag(ItemHasContents, true); } protected: virtual QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { MessUpNode *node = static_cast<MessUpNode *>(oldNode); if (!node) node = new MessUpNode; return node; } }; tst_rendernode::tst_rendernode() { qmlRegisterType<ClearItem>("Test", 1, 0, "ClearItem"); qmlRegisterType<MessUpItem>("Test", 1, 0, "MessUpItem"); outerWindow.showNormal(); outerWindow.setGeometry(0,0,400,400); } static bool fuzzyCompareColor(QRgb x, QRgb y, QByteArray *errorMessage) { enum { fuzz = 4 }; if (qAbs(qRed(x) - qRed(y)) >= fuzz || qAbs(qGreen(x) - qGreen(y)) >= fuzz || qAbs(qBlue(x) - qBlue(y)) >= fuzz) { QString s; QDebug(&s).nospace() << hex << "Color mismatch 0x" << x << " 0x" << y << dec << " (fuzz=" << fuzz << ")."; *errorMessage = s.toLocal8Bit(); return false; } return true; } static inline QByteArray msgColorMismatchAt(const QByteArray &colorMsg, int x, int y) { return colorMsg + QByteArrayLiteral(" at ") + QByteArray::number(x) +',' + QByteArray::number(y); } /* The test draws four rects, each 100x100 and verifies * that a rendernode which calls glClear() is stacked * correctly. The red rectangles come under the white * and are obscured. */ void tst_rendernode::renderOrder() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("RenderOrder.qml"); const qreal scaleFactor = QGuiApplication::primaryScreen()->devicePixelRatio(); QCOMPARE(fb.width(), qRound(200 * scaleFactor)); QCOMPARE(fb.height(), qRound(200 * scaleFactor)); QCOMPARE(fb.pixel(50 * scaleFactor, 50 * scaleFactor), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(50 * scaleFactor, 150 * scaleFactor), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(150 * scaleFactor, 50 * scaleFactor), qRgb(0x00, 0x00, 0xff)); QByteArray errorMessage; const qreal coordinate = 150 * scaleFactor; QVERIFY2(fuzzyCompareColor(fb.pixel(coordinate, coordinate), qRgb(0x7f, 0x7f, 0xff), &errorMessage), msgColorMismatchAt(errorMessage, coordinate, coordinate).constData()); } /* The test uses a number of nested rectangles with clipping * and rotation to verify that using a render node which messes * with the state does not break rendering that comes after it. */ void tst_rendernode::messUpState() { if (QGuiApplication::primaryScreen()->depth() < 24) QSKIP("This test does not work at display depths < 24"); QImage fb = runTest("MessUpState.qml"); int x1 = 0; int x2 = fb.width() / 2; int x3 = fb.width() - 1; int y1 = 0; int y2 = fb.height() * 3 / 16; int y3 = fb.height() / 2; int y4 = fb.height() * 13 / 16; int y5 = fb.height() - 1; QCOMPARE(fb.pixel(x1, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x3, y3), qRgb(0xff, 0xff, 0xff)); QCOMPARE(fb.pixel(x2, y1), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y2), qRgb(0x00, 0x00, 0x00)); QByteArray errorMessage; QVERIFY2(fuzzyCompareColor(fb.pixel(x2, y3), qRgb(0x7f, 0x00, 0x7f), &errorMessage), msgColorMismatchAt(errorMessage, x2, y3).constData()); QCOMPARE(fb.pixel(x2, y4), qRgb(0x00, 0x00, 0x00)); QCOMPARE(fb.pixel(x2, y5), qRgb(0x00, 0x00, 0x00)); } class StateRecordingRenderNode : public QSGRenderNode { public: StateFlags changedStates() const override { return StateFlags(-1); } void render(const RenderState *) override { matrices[name] = *matrix(); } QString name; static QHash<QString, QMatrix4x4> matrices; }; QHash<QString, QMatrix4x4> StateRecordingRenderNode::matrices; class StateRecordingRenderNodeItem : public QQuickItem { Q_OBJECT public: StateRecordingRenderNodeItem() { setFlag(ItemHasContents, true); } QSGNode *updatePaintNode(QSGNode *r, UpdatePaintNodeData *) { if (r) return r; StateRecordingRenderNode *rn = new StateRecordingRenderNode(); rn->name = objectName(); return rn; } }; void tst_rendernode::matrix() { qmlRegisterType<StateRecordingRenderNodeItem>("RenderNode", 1, 0, "StateRecorder"); StateRecordingRenderNode::matrices.clear(); runTest("matrix.qml"); QMatrix4x4 noRotateOffset; noRotateOffset.translate(20, 20); { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("no-clip; no-rotation")); QCOMPARE(result, noRotateOffset); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("parent-clip; no-rotation")); QCOMPARE(result, noRotateOffset); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("self-clip; no-rotation")); QCOMPARE(result, noRotateOffset); } QMatrix4x4 parentRotation; parentRotation.translate(10, 10); // parent at x/y: 10 parentRotation.translate(5, 5); // rotate 90 around center (width/height: 10) parentRotation.rotate(90, 0, 0, 1); parentRotation.translate(-5, -5); parentRotation.translate(10, 10); // StateRecorder at: x/y: 10 { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("no-clip; parent-rotation")); QCOMPARE(result, parentRotation); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("parent-clip; parent-rotation")); QCOMPARE(result, parentRotation); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("self-clip; parent-rotation")); QCOMPARE(result, parentRotation); } QMatrix4x4 selfRotation; selfRotation.translate(10, 10); // parent at x/y: 10 selfRotation.translate(10, 10); // StateRecorder at: x/y: 10 selfRotation.rotate(90, 0, 0, 1); // rotate 90, width/height: 0 { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("no-clip; self-rotation")); QCOMPARE(result, selfRotation); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("parent-clip; self-rotation")); QCOMPARE(result, selfRotation); } { QMatrix4x4 result = StateRecordingRenderNode::matrices.value(QStringLiteral("self-clip; self-rotation")); QCOMPARE(result, selfRotation); } } QTEST_MAIN(tst_rendernode) #include "tst_rendernode.moc"
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/quick/rendernode/tst_rendernode.cpp
C++
gpl-3.0
11,357
# Helpers Helpers are small utility functions, accessible through the `Atomik` object. They are loaded on demand. ## Creating helpers Helpers in Atomik are stored in *app/helpers*. For example, a `format_date()` helper would be stored in *app/helpers/format\_date.php*. The helpers directory can be changed using *atomik.dirs.helpers*. You can then define your helper in two ways: as a function or as a class. If you're using a function, just create one with the same name as the helper. function format_date($date) { // do the formating return $date; } You can also use a class which can be pretty useful for more complex cases. The class name is a camel case version (ie. without any underscores or spaces, all words starting with an upper case) of the helper name suffixed with *Helper*. In our example, it would be `FormatDateHelper`. This class also needs to have a method named like the helper name but in camel case and starting with a lower case. In this case, it would be `formatDate()`. class FormatDateHelper { public function formatDate($date) { // do the formating return $date; } } ## Using helpers Helpers are callable from any action or view file. They are accessible as methods of `$this`. <span class="date"><?php echo $this->format_date('01-01-2009') ?></span> ## Registering helpers You can also registers helper using the `Atomik::registerHelper()` function: Atomik::registerHelper('say_hello', function() { echo 'hello'; });
OlivierB/Network-Display-On-Pi
www/admin/vendor/atomik/atomik/docs/helpers.md
Markdown
gpl-3.0
1,577
require 'pathname' Puppet::Type.newtype(:dsc_xinternetexplorerhomepage) do require Pathname.new(__FILE__).dirname + '../../' + 'puppet/type/base_dsc' require Pathname.new(__FILE__).dirname + '../../puppet_x/puppetlabs/dsc_type_helpers' @doc = %q{ The DSC xInternetExplorerHomePage resource type. Automatically generated from 'xInternetExplorerHomePage/DSCResources/xInternetExplorerHomePage/xInternetExplorerHomePage.schema.mof' To learn more about PowerShell Desired State Configuration, please visit https://technet.microsoft.com/en-us/library/dn249912.aspx. For more information about built-in DSC Resources, please visit https://technet.microsoft.com/en-us/library/dn249921.aspx. For more information about xDsc Resources, please visit https://github.com/PowerShell/DscResources. } validate do fail('dsc_startpage is a required attribute') if self[:dsc_startpage].nil? end def dscmeta_resource_friendly_name; 'xInternetExplorerHomePage' end def dscmeta_resource_name; 'xInternetExplorerHomePage' end def dscmeta_module_name; 'xInternetExplorerHomePage' end def dscmeta_module_version; '1.0.0' end newparam(:name, :namevar => true ) do end ensurable do newvalue(:exists?) { provider.exists? } newvalue(:present) { provider.create } newvalue(:absent) { provider.destroy } defaultto { :present } end # Name: PsDscRunAsCredential # Type: MSFT_Credential # IsMandatory: False # Values: None newparam(:dsc_psdscrunascredential) do def mof_type; 'MSFT_Credential' end def mof_is_embedded?; true end desc "PsDscRunAsCredential" validate do |value| unless value.kind_of?(Hash) fail("Invalid value '#{value}'. Should be a hash") end PuppetX::Dsc::TypeHelpers.validate_MSFT_Credential("Credential", value) end end # Name: StartPage # Type: string # IsMandatory: True # Values: None newparam(:dsc_startpage) do def mof_type; 'string' end def mof_is_embedded?; false end desc "StartPage - Specifies the URL for the home page of Internet Explorer." isrequired validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end # Name: SecondaryStartPages # Type: string # IsMandatory: False # Values: None newparam(:dsc_secondarystartpages) do def mof_type; 'string' end def mof_is_embedded?; false end desc "SecondaryStartPages - Specifies the URL for the secondary home pages of Internet Explorer." validate do |value| unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end end end # Name: Ensure # Type: string # IsMandatory: False # Values: ["Present", "Absent"] newparam(:dsc_ensure) do def mof_type; 'string' end def mof_is_embedded?; false end desc "Ensure - Should the IE home page is configured or unconfigured. Valid values are Present, Absent." validate do |value| resource[:ensure] = value.downcase unless value.kind_of?(String) fail("Invalid value '#{value}'. Should be a string") end unless ['Present', 'present', 'Absent', 'absent'].include?(value) fail("Invalid value '#{value}'. Valid values are Present, Absent") end end end def builddepends pending_relations = super() PuppetX::Dsc::TypeHelpers.ensure_reboot_relationship(self, pending_relations) end end Puppet::Type.type(:dsc_xinternetexplorerhomepage).provide :powershell, :parent => Puppet::Type.type(:base_dsc).provider(:powershell) do confine :true => (Gem::Version.new(Facter.value(:powershell_version)) >= Gem::Version.new('5.0.10586.117')) defaultfor :operatingsystem => :windows mk_resource_methods end
nauskis/Puppet-for-dummies
windowsia/puppet/modules/dsc/lib/puppet/type/dsc_xinternetexplorerhomepage.rb
Ruby
gpl-3.0
3,913
#include <complex.h> #include <pfft.h> /* This program tests the over-/under-sampled PFFT. * We first compute an oversampled forward PFFT and second * revert it with an undersampled backward PFFT. * This should give back the initial input values * (up to the typical scaling factor) */ int main(int argc, char **argv) { int np[2]; ptrdiff_t n[4], ni[4], no[4]; ptrdiff_t alloc_local_forw, alloc_local_back, alloc_local, howmany; ptrdiff_t local_ni[4], local_i_start[4]; ptrdiff_t local_n[4], local_start[4]; ptrdiff_t local_no[4], local_o_start[4]; double err; double *planned_in, *executed_in; pfft_complex *planned_out, *executed_out; pfft_plan plan_forw=NULL, plan_back=NULL; MPI_Comm comm_cart_2d; /* Set size of FFT and process mesh */ ni[0] = ni[1] = ni[2] = ni[3] = 8; n[0] = 13; n[1] = 14; n[2] = 15; n[3] = 17; for(int t=0; t<4; t++) no[t] = ni[t]; np[0] = 2; np[1] = 2; howmany = 1; /* Initialize MPI and PFFT */ MPI_Init(&argc, &argv); pfft_init(); /* Create two-dimensional process grid of size np[0] x np[1], if possible */ if( pfft_create_procmesh_2d(MPI_COMM_WORLD, np[0], np[1], &comm_cart_2d) ){ pfft_fprintf(MPI_COMM_WORLD, stderr, "Error: This test file only works with %d processes.\n", np[0]*np[1]); MPI_Finalize(); return 1; } /* Get parameters of data distribution */ alloc_local_forw = pfft_local_size_many_dft_r2c(4, n, ni, n, howmany, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, comm_cart_2d, PFFT_TRANSPOSED_NONE, local_ni, local_i_start, local_n, local_start); alloc_local_back = pfft_local_size_many_dft_c2r(4, n, n, no, howmany, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, comm_cart_2d, PFFT_TRANSPOSED_NONE, local_n, local_start, local_no, local_o_start); /* Allocate enough memory for both trafos */ alloc_local = (alloc_local_forw > alloc_local_back) ? alloc_local_forw : alloc_local_back; planned_in = pfft_alloc_real(2 * alloc_local); planned_out = pfft_alloc_complex(alloc_local); /* Plan parallel forward FFT */ plan_forw = pfft_plan_many_dft_r2c( 4, n, ni, n, howmany, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, planned_in, planned_out, comm_cart_2d, PFFT_FORWARD, PFFT_TRANSPOSED_NONE| PFFT_MEASURE| PFFT_DESTROY_INPUT); /* Plan parallel backward FFT */ plan_back = pfft_plan_many_dft_c2r( 4, n, n, no, howmany, PFFT_DEFAULT_BLOCKS, PFFT_DEFAULT_BLOCKS, planned_out, planned_in, comm_cart_2d, PFFT_BACKWARD, PFFT_TRANSPOSED_NONE| PFFT_MEASURE| PFFT_DESTROY_INPUT); /* Free planning arrays since we use other arrays for execution */ pfft_free(planned_in); pfft_free(planned_out); /* Allocate memory for execution */ executed_in = pfft_alloc_real(2 * alloc_local); executed_out = pfft_alloc_complex(alloc_local); /* Initialize input with random numbers */ pfft_init_input_real(4, n, local_ni, local_i_start, executed_in); /* execute parallel forward FFT */ pfft_execute_dft_r2c(plan_forw, executed_in, executed_out); /* clear the old input */ pfft_clear_input_real(4, n, local_ni, local_i_start, executed_in); /* execute parallel backward FFT */ pfft_execute_dft_c2r(plan_back, executed_out, executed_in); /* Scale data */ for(ptrdiff_t l=0; l < local_no[0] * local_no[1] * local_no[2] * local_no[3]; l++) executed_in[l] /= (n[0]*n[1]*n[2]*n[3]); /* Print error of back transformed data */ MPI_Barrier(MPI_COMM_WORLD); err = pfft_check_output_real(4, n, local_no, local_o_start, executed_in, comm_cart_2d); pfft_printf(comm_cart_2d, "Error after one forward and backward trafo of size n=(%td, %td, %td, %td):\n", n[0], n[1], n[2], n[3]); pfft_printf(comm_cart_2d, "maxerror = %6.2e;\n", err); /* free mem and finalize */ pfft_destroy_plan(plan_forw); pfft_destroy_plan(plan_back); MPI_Comm_free(&comm_cart_2d); pfft_free(executed_in); pfft_free(executed_out); MPI_Finalize(); return 0; }
rainwoodman/pfft
tests/simple_check_ousam_r2c_4d_newarray.c
C
gpl-3.0
3,976
using Chemistry; using System; using System.Collections.Generic; using System.IO; using System.Linq; using UsefulProteomicsDatabases; namespace ProteoformSuiteInternal { //Types of comparisons, aka ProteoformFamily edges public enum ProteoformComparison { ExperimentalTheoretical, //Experiment-Theoretical comparisons ExperimentalDecoy, //Experiment-Decoy comparisons ExperimentalExperimental, //Experiment-Experiment comparisons ExperimentalFalse, //Experiment-Experiment comparisons using unequal lysine counts } //I have not used MassDifference objects in the logic, since it is better to cast the comparisons immediately as //ProteoformRelation objects. However, I believe this hierarchy clarifies that ProteoformRelations are in fact //containers of mass differences, grouped nearby mass differences. Simply having only ProteoformRelation makes this distinction vague. //Calling ProteoformRelation "MassDifference" isn't appropriate, since it contains groups of mass differences. //That said, I like calling the grouped ProteoformRelations a peak, since a peak is often comprised of multiple observations: //of light in spectroscopy, of ions in mass spectrometry, and since the peak is a pileup on the mass difference axis, I've called it //DeltaMassPeak. I debated MassDifferencePeak, but I wanted to distance this class from MassDifference and draw the imagination //closer to the picture of the graph, in which we often say "deltaM" colloquially, whereas we tend to say "mass difference" when we're //referring to an individual value. public class ProteoformRelation : IMassDifference { #region Fields private static int instanceCounter = 0; public Proteoform[] connected_proteoforms = new Proteoform[2]; public PtmSet candidate_ptmset = null; public PtmSet represented_ptmset = null; private static ChemicalFormula CH2 = null; private static ChemicalFormula HPO3 = null; #endregion Fields #region Public Properties public int InstanceId { get; set; } public double DeltaMass { get; set; } public DeltaMassPeak peak { get; set; } public List<ProteoformRelation> nearby_relations { get; set; } // cleared after accepting peaks public int nearby_relations_count { get; set; } // count is the "running sum"; relations are not saved public bool outside_no_mans_land { get; set; } public int lysine_count { get; set; } public ProteoformComparison RelationType { get; set; } public bool Identification { get; set; } = false; /// <summary> /// Is this relation in an accepted peak? /// ProteoformRelation.accepted may not be the same as DeltaMassPeak.peak_accepted, which denotes whether the peak is accepted. /// </summary> public bool Accepted { get; set; } #endregion Public Properties #region Public Constructors public ProteoformRelation(Proteoform pf1, Proteoform pf2, ProteoformComparison relation_type, double delta_mass, string current_directory) { connected_proteoforms[0] = pf1; connected_proteoforms[1] = pf2; RelationType = relation_type; DeltaMass = delta_mass; InstanceId = instanceCounter; lock (Sweet.lollipop) instanceCounter += 1; //Not thread safe if (CH2 == null || HPO3 == null) { CH2 = ChemicalFormula.ParseFormula("C1 H2"); HPO3 = ChemicalFormula.ParseFormula("H1 O3 P1"); } if (Sweet.lollipop.neucode_labeled) { lysine_count = pf1.lysine_count; } List<PtmSet> candidate_sets = new List<PtmSet>(); if (Sweet.lollipop.et_use_notch && (relation_type == ProteoformComparison.ExperimentalTheoretical || relation_type == ProteoformComparison.ExperimentalDecoy)) { if (Sweet.lollipop.et_use_notch && !Sweet.lollipop.et_notch_ppm) { double mass = delta_mass - Sweet.lollipop.notch_tolerance_et; while (mass <= delta_mass + Sweet.lollipop.notch_tolerance_et) { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary_notches.TryGetValue( Math.Round(mass, 1), out List<PtmSet> candidates); if (candidates != null) { candidate_sets.AddRange(candidates); } mass += 0.1; } candidate_sets = candidate_sets.Distinct().ToList(); } else { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary_notches.TryGetValue(Math.Round(delta_mass, 1), out candidate_sets); } if (candidate_sets != null) { candidate_sets = candidate_sets.Where(s => Sweet.lollipop.et_notch_ppm ? Math.Abs(s.mass - delta_mass) * 1e6 / pf1.modified_mass < Sweet.lollipop.notch_tolerance_et : Math.Abs(s.mass - delta_mass) < Sweet.lollipop.notch_tolerance_et).ToList(); candidate_ptmset = candidate_sets.OrderBy(s => s.ptm_rank_sum).FirstOrDefault(); } } else if (Sweet.lollipop.ee_use_notch && (relation_type == ProteoformComparison.ExperimentalExperimental || relation_type == ProteoformComparison.ExperimentalFalse)) { if (Sweet.lollipop.ee_use_notch && !Sweet.lollipop.ee_notch_ppm) { double mass = delta_mass - Sweet.lollipop.notch_tolerance_ee; while (mass <= delta_mass + Sweet.lollipop.notch_tolerance_ee) { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary_notches.TryGetValue( Math.Round(mass, 1), out List<PtmSet> candidates); if (candidates != null) { candidate_sets.AddRange(candidates); } mass += 0.1; } candidate_sets = candidate_sets.Distinct().ToList(); } else { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary_notches.TryGetValue(Math.Round(delta_mass, 1), out candidate_sets); } if (candidate_sets != null) { candidate_sets = candidate_sets.Where(s => Sweet.lollipop.ee_notch_ppm ? Math.Abs(s.mass - delta_mass) * 1e6 / pf1.modified_mass < Sweet.lollipop.notch_tolerance_ee : Math.Abs(s.mass - delta_mass) < Sweet.lollipop.notch_tolerance_ee).ToList(); candidate_ptmset = candidate_sets.OrderBy(s => s.ptm_rank_sum).FirstOrDefault(); } } else if (relation_type == ProteoformComparison.ExperimentalTheoretical || relation_type == ProteoformComparison.ExperimentalDecoy) { if (Sweet.lollipop.peak_width_base_et > 0.09) { double mass = delta_mass - Sweet.lollipop.peak_width_base_et; while (mass <= delta_mass + Sweet.lollipop.peak_width_base_et) { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary.TryGetValue( Math.Round(mass, 1), out List<PtmSet> candidates); if (candidates != null) { candidate_sets.AddRange(candidates); } mass += 0.1; } candidate_sets = candidate_sets.Distinct().ToList(); } else { Sweet.lollipop.theoretical_database.possible_ptmset_dictionary.TryGetValue( Math.Round(delta_mass, 1), out candidate_sets); } if (pf2 as TheoreticalProteoform != null && candidate_sets != null && candidate_sets.Count > 0) { List<PtmSet> narrower_range_of_candidates = new List<PtmSet>(); if (Sweet.lollipop.et_use_notch) { narrower_range_of_candidates = candidate_sets; } else { narrower_range_of_candidates = candidate_sets .Where(s => Math.Abs(s.mass - delta_mass) < Sweet.lollipop.peak_width_base_et).ToList(); } TheoreticalProteoform t = pf2 as TheoreticalProteoform; candidate_ptmset = Proteoform.generate_possible_added_ptmsets(narrower_range_of_candidates, Sweet.lollipop.theoretical_database.all_mods_with_mass, t, pf2.begin, pf2.end, pf2.ptm_set, Sweet.lollipop.mod_rank_first_quartile, false).OrderBy(x => x.ptm_rank_sum + Math.Abs(Math.Abs(x.mass) - Math.Abs(delta_mass)) * 10E-6) // major score: delta rank; tie breaker: deltaM, where it's always less than 1 .FirstOrDefault(); } } // Start the model (0 Da) at the mass defect of CH2 or HPO3 itself, allowing the peak width tolerance on either side double half_peak_width = RelationType == ProteoformComparison.ExperimentalTheoretical || RelationType == ProteoformComparison.ExperimentalDecoy ? Sweet.lollipop.peak_width_base_et / 2 : Sweet.lollipop.peak_width_base_ee / 2; double low_decimal_bound = half_peak_width + ((CH2.MonoisotopicMass - Math.Truncate(CH2.MonoisotopicMass)) / CH2.MonoisotopicMass) * (Math.Abs(delta_mass) <= CH2.MonoisotopicMass ? CH2.MonoisotopicMass : Math.Abs(delta_mass)); double high_decimal_bound = 1 - half_peak_width + ((HPO3.MonoisotopicMass - Math.Ceiling(HPO3.MonoisotopicMass)) / HPO3.MonoisotopicMass) * (Math.Abs(delta_mass) <= HPO3.MonoisotopicMass ? HPO3.MonoisotopicMass : Math.Abs(delta_mass)); double delta_mass_decimal = Math.Abs(delta_mass - Math.Truncate(delta_mass)); outside_no_mans_land = delta_mass_decimal <= low_decimal_bound || delta_mass_decimal >= high_decimal_bound || high_decimal_bound <= low_decimal_bound; if (Sweet.lollipop.et_use_notch && (relation_type == ProteoformComparison.ExperimentalTheoretical || relation_type == ProteoformComparison.ExperimentalDecoy)) outside_no_mans_land = true; if (Sweet.lollipop.ee_use_notch && (relation_type == ProteoformComparison.ExperimentalExperimental || relation_type == ProteoformComparison.ExperimentalFalse)) outside_no_mans_land = true; } #endregion Public Constructors #region Public Methods public List<ProteoformRelation> set_nearby_group(List<ProteoformRelation> all_ordered_relations, List<int> ordered_relation_ids) { double peak_width_base = typeof(TheoreticalProteoform).IsAssignableFrom(all_ordered_relations[0].connected_proteoforms[1].GetType()) ? Sweet.lollipop.peak_width_base_et : Sweet.lollipop.peak_width_base_ee; double lower_limit_of_peak_width = DeltaMass - peak_width_base / 2; double upper_limit_of_peak_width = DeltaMass + peak_width_base / 2; int idx = ordered_relation_ids.IndexOf(InstanceId); List<ProteoformRelation> within_range = new List<ProteoformRelation> { this }; int curr_idx = idx - 1; while (curr_idx >= 0 && lower_limit_of_peak_width <= all_ordered_relations[curr_idx].DeltaMass) { within_range.Add(all_ordered_relations[curr_idx]); curr_idx--; } curr_idx = idx + 1; while (curr_idx < all_ordered_relations.Count && all_ordered_relations[curr_idx].DeltaMass <= upper_limit_of_peak_width) { within_range.Add(all_ordered_relations[curr_idx]); curr_idx++; } lock (this) { nearby_relations = within_range; nearby_relations_count = within_range.Count; } return nearby_relations; } public void generate_peak() { new DeltaMassPeak(this, Sweet.lollipop.target_proteoform_community.remaining_relations_outside_no_mans); //setting the peak takes place elsewhere, but this constructs it if (connected_proteoforms[1] as TheoreticalProteoform != null && Sweet.lollipop.ed_relations.Count > 0) lock (peak) peak.calculate_fdr(Sweet.lollipop.ed_relations); else if (connected_proteoforms[1] as ExperimentalProteoform != null && Sweet.lollipop.ef_relations.Count > 0) lock (peak) peak.calculate_fdr(Sweet.lollipop.ef_relations); } public override bool Equals(object obj) { ProteoformRelation r2 = obj as ProteoformRelation; return r2 != null && (InstanceId == r2.InstanceId) || (connected_proteoforms[0] == r2.connected_proteoforms[1] && connected_proteoforms[1] == r2.connected_proteoforms[0]) || (connected_proteoforms[0] == r2.connected_proteoforms[0] && connected_proteoforms[1] == r2.connected_proteoforms[1]); } public override int GetHashCode() { return connected_proteoforms[0].GetHashCode() ^ connected_proteoforms[1].GetHashCode(); } #endregion Public Methods } }
lschaffer2/ProteoformSuite
ProteoformSuiteInternal/ProteoformRelation.cs
C#
gpl-3.0
14,379
/* * RAW muxers * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2005 Alex Beregszaszi * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/intreadwrite.h" #include "avformat.h" #include "rawenc.h" #include "internal.h" int ff_raw_write_packet(AVFormatContext *s, AVPacket *pkt) { avio_write(s->pb, pkt->data, pkt->size); return 0; } static int force_one_stream(AVFormatContext *s) { if (s->nb_streams != 1) { av_log(s, AV_LOG_ERROR, "%s files have exactly one stream\n", s->oformat->name); return AVERROR(EINVAL); } return 0; } /* Note: Do not forget to add new entries to the Makefile as well. */ #if CONFIG_AC3_MUXER AVOutputFormat ff_ac3_muxer = { .name = "ac3", .long_name = NULL_IF_CONFIG_SMALL("raw AC-3"), .mime_type = "audio/x-ac3", .extensions = "ac3", .audio_codec = AV_CODEC_ID_AC3, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_ADX_MUXER static int adx_write_trailer(AVFormatContext *s) { AVIOContext *pb = s->pb; AVCodecParameters *par = s->streams[0]->codecpar; if (pb->seekable & AVIO_SEEKABLE_NORMAL) { int64_t file_size = avio_tell(pb); uint64_t sample_count = (file_size - 36) / par->channels / 18 * 32; if (sample_count <= UINT32_MAX) { avio_seek(pb, 12, SEEK_SET); avio_wb32(pb, sample_count); avio_seek(pb, file_size, SEEK_SET); } } return 0; } AVOutputFormat ff_adx_muxer = { .name = "adx", .long_name = NULL_IF_CONFIG_SMALL("CRI ADX"), .extensions = "adx", .audio_codec = AV_CODEC_ID_ADPCM_ADX, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .write_trailer = adx_write_trailer, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_CAVSVIDEO_MUXER AVOutputFormat ff_cavsvideo_muxer = { .name = "cavsvideo", .long_name = NULL_IF_CONFIG_SMALL("raw Chinese AVS (Audio Video Standard) video"), .extensions = "cavs", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_CAVS, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_DATA_MUXER AVOutputFormat ff_data_muxer = { .name = "data", .long_name = NULL_IF_CONFIG_SMALL("raw data"), .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_DIRAC_MUXER AVOutputFormat ff_dirac_muxer = { .name = "dirac", .long_name = NULL_IF_CONFIG_SMALL("raw Dirac"), .extensions = "drc,vc2", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_DIRAC, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_DNXHD_MUXER AVOutputFormat ff_dnxhd_muxer = { .name = "dnxhd", .long_name = NULL_IF_CONFIG_SMALL("raw DNxHD (SMPTE VC-3)"), .extensions = "dnxhd,dnxhr", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_DNXHD, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_DTS_MUXER AVOutputFormat ff_dts_muxer = { .name = "dts", .long_name = NULL_IF_CONFIG_SMALL("raw DTS"), .mime_type = "audio/x-dca", .extensions = "dts", .audio_codec = AV_CODEC_ID_DTS, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_EAC3_MUXER AVOutputFormat ff_eac3_muxer = { .name = "eac3", .long_name = NULL_IF_CONFIG_SMALL("raw E-AC-3"), .mime_type = "audio/x-eac3", .extensions = "eac3", .audio_codec = AV_CODEC_ID_EAC3, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_G722_MUXER AVOutputFormat ff_g722_muxer = { .name = "g722", .long_name = NULL_IF_CONFIG_SMALL("raw G.722"), .mime_type = "audio/G722", .extensions = "g722", .audio_codec = AV_CODEC_ID_ADPCM_G722, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_G723_1_MUXER AVOutputFormat ff_g723_1_muxer = { .name = "g723_1", .long_name = NULL_IF_CONFIG_SMALL("raw G.723.1"), .mime_type = "audio/g723", .extensions = "tco,rco", .audio_codec = AV_CODEC_ID_G723_1, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_GSM_MUXER AVOutputFormat ff_gsm_muxer = { .name = "gsm", .long_name = NULL_IF_CONFIG_SMALL("raw GSM"), .mime_type = "audio/x-gsm", .extensions = "gsm", .audio_codec = AV_CODEC_ID_GSM, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_H261_MUXER AVOutputFormat ff_h261_muxer = { .name = "h261", .long_name = NULL_IF_CONFIG_SMALL("raw H.261"), .mime_type = "video/x-h261", .extensions = "h261", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_H261, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_H263_MUXER AVOutputFormat ff_h263_muxer = { .name = "h263", .long_name = NULL_IF_CONFIG_SMALL("raw H.263"), .mime_type = "video/x-h263", .extensions = "h263", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_H263, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_H264_MUXER static int h264_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { AVStream *st = s->streams[0]; if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) return ff_stream_add_bitstream_filter(st, "h264_mp4toannexb", NULL); return 1; } AVOutputFormat ff_h264_muxer = { .name = "h264", .long_name = NULL_IF_CONFIG_SMALL("raw H.264 video"), .extensions = "h264,264", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_H264, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .check_bitstream = h264_check_bitstream, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_HEVC_MUXER static int hevc_check_bitstream(struct AVFormatContext *s, const AVPacket *pkt) { AVStream *st = s->streams[0]; if (pkt->size >= 5 && AV_RB32(pkt->data) != 0x0000001 && AV_RB24(pkt->data) != 0x000001) return ff_stream_add_bitstream_filter(st, "hevc_mp4toannexb", NULL); return 1; } AVOutputFormat ff_hevc_muxer = { .name = "hevc", .long_name = NULL_IF_CONFIG_SMALL("raw HEVC video"), .extensions = "hevc,h265,265", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_HEVC, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .check_bitstream = hevc_check_bitstream, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_M4V_MUXER AVOutputFormat ff_m4v_muxer = { .name = "m4v", .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-4 video"), .extensions = "m4v", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_MPEG4, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_MJPEG_MUXER AVOutputFormat ff_mjpeg_muxer = { .name = "mjpeg", .long_name = NULL_IF_CONFIG_SMALL("raw MJPEG video"), .mime_type = "video/x-mjpeg", .extensions = "mjpg,mjpeg", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_MJPEG, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_SINGLEJPEG_MUXER AVOutputFormat ff_singlejpeg_muxer = { .name = "singlejpeg", .long_name = NULL_IF_CONFIG_SMALL("JPEG single image"), .mime_type = "image/jpeg", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_MJPEG, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, .write_header = force_one_stream, }; #endif #if CONFIG_MLP_MUXER AVOutputFormat ff_mlp_muxer = { .name = "mlp", .long_name = NULL_IF_CONFIG_SMALL("raw MLP"), .extensions = "mlp", .audio_codec = AV_CODEC_ID_MLP, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_MP2_MUXER AVOutputFormat ff_mp2_muxer = { .name = "mp2", .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"), .mime_type = "audio/mpeg", .extensions = "mp2,m2a,mpa", .audio_codec = AV_CODEC_ID_MP2, .video_codec = AV_CODEC_ID_NONE, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_MPEG1VIDEO_MUXER AVOutputFormat ff_mpeg1video_muxer = { .name = "mpeg1video", .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-1 video"), .mime_type = "video/mpeg", .extensions = "mpg,mpeg,m1v", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_MPEG1VIDEO, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_MPEG2VIDEO_MUXER AVOutputFormat ff_mpeg2video_muxer = { .name = "mpeg2video", .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-2 video"), .extensions = "m2v", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_MPEG2VIDEO, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_RAWVIDEO_MUXER AVOutputFormat ff_rawvideo_muxer = { .name = "rawvideo", .long_name = NULL_IF_CONFIG_SMALL("raw video"), .extensions = "yuv,rgb", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_RAWVIDEO, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_TRUEHD_MUXER AVOutputFormat ff_truehd_muxer = { .name = "truehd", .long_name = NULL_IF_CONFIG_SMALL("raw TrueHD"), .extensions = "thd", .audio_codec = AV_CODEC_ID_TRUEHD, .video_codec = AV_CODEC_ID_NONE, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_VC1_MUXER AVOutputFormat ff_vc1_muxer = { .name = "vc1", .long_name = NULL_IF_CONFIG_SMALL("raw VC-1 video"), .extensions = "vc1", .audio_codec = AV_CODEC_ID_NONE, .video_codec = AV_CODEC_ID_VC1, .write_header = force_one_stream, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif
OshinKaramian/jsmc
server/ffmpeg/linux/libavformat/rawenc.c
C
gpl-3.0
13,495
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Author: echel0n <[email protected]> # URL: http://www.github.com/sickragetv/sickrage/ # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals # Dynamic patch system # function naming scheme: targetmodule_targetfunction import os import sys import stat import shutil import inspect def shutil_copyfile(src, dst): """Copy data from src to dst""" if shutil._samefile(src, dst): raise shutil.Error("`%s` and `%s` are the same file" % (src, dst)) elif not os.path.exists(src) or os.path.isdir(src): return for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist pass else: # XXX What about other special files? (sockets, devices...) if stat.S_ISFIFO(st.st_mode): try: raise shutil.SpecialFileError("`%s` is a named pipe" % fn) except NameError: raise shutil.Error("`%s` is a named pipe" % fn) try: with open(src, "rb") as fin, open(dst, "wb") as fout: for x in iter(lambda: fin.read(128 * 1024), ""): fout.write(x) except Exception: raise # auto_apply patches for name, patch in inspect.getmembers(sys.modules[__name__], inspect.isfunction): try: mod, func = name.split("_", 1) if not hasattr(sys.modules, mod): sys.modules[mod] = __import__(mod) sys.modules[mod].__dict__[func] = patch except: continue
coderbone/SickRage
sickrage/patches.py
Python
gpl-3.0
2,234
{% for post in site.posts %} {% assign post_date = post.date | date: "%s" %} {% assign post_expiry_date = site.last_published | date: "%s" %} {% if post_date > post_expiry_date %} {% if post.priority and post.priority < 7 %} {% case post.priority %} {% when 1 %} {%assign item1 = post %} {% when 2 %} {%assign item2 = post %} {% when 3 %} {%assign item3 = post %} {% when 4 %} {%assign item4 = post %} {% when 5 %} {%assign item5 = post %} {% when 6 %} {%assign item6 = post %} {% endcase %} {% endif %} {% endif %} {% endfor %} <div class="row new_posts"> <div class="col-xs-12 col-sm-6 col-md-6 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item1.url }}"> <div class="col-xs-12 col-sm-12 col-md-6"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item1.image }}" alt="..."> </div> <div> <h4 class="hindi title"><strong>{{ item1.section }}: {{ item1.title }}</strong></h4> </div> </div> <div class="col-xs-12 col-sm-12 col-md-6"> <h4 class="hindi item-description justify"><i>{{ item1.excerpt }}</i></h4> </div> </a> </div> </div> <div class="col-xs-12 col-sm-6 col-md-6 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item2.url }}"> <div class="col-xs-12 col-sm-12 col-md-6"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item2.image }}" alt="..."> </div> <div> <h4 class="hindi title"><strong>{{ item2.section }}: {{ item2.title }}</strong></h4> </div> </div> <div class="col-xs-12 col-sm-12 col-md-6"> <h4 class="hindi item-description justify"><i>{{ item2.excerpt }}</i></h4> </div> </a> </div> </div> <div class="col-xs-12 col-sm-6 col-md-3 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item3.url }}"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item3.image }}" alt="..."> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <h4 class="hindi title"><strong>{{ item3.section }}: {{ item3.title }}</strong></h4> </div> </a> </div> </div> <div class="col-xs-12 col-sm-6 col-md-3 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item4.url }}"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item4.image }}" alt="..."> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <h4 class="hindi title"><strong>{{ item4.section }}: {{ item4.title }}</strong></h4> </div> </a> </div> </div> <div class="col-xs-12 col-sm-6 col-md-3 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item5.url }}"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item5.image }}" alt="..."> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <h4 class="hindi title"><strong>{{ item5.section }}: {{ item5.title }}</strong></h4> </div> </a> </div> </div> <div class="col-xs-12 col-sm-6 col-md-3 new-item"> <div class="row"> <a class="link-no-decoration" href="{{ site.url }}{{ site.baseurl }}{{ item6.url }}"> <div class="col-xs-12 col-sm-12 col-md-12"> <div class="thumbnail"> <img src="{{ site.url }}{{ site.baseurl }}/static/news_images/{{ item6.image }}" alt="..."> </div> </div> <div class="col-xs-12 col-sm-12 col-md-12"> <h4 class="hindi title"><strong>{{ item6.section }}: {{ item6.title }}</strong></h4> </div> </a> </div> </div> </div>
sjohaar/mypage
_includes/new_items_09172017.html
HTML
gpl-3.0
4,944
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>ns-3 PLC model: ns3::PLC_ErrorRatePhy Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">ns-3 PLC model </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Enumerations</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><b>ns3</b> </li> <li class="navelem"><a class="el" href="classns3_1_1PLC__ErrorRatePhy.html">PLC_ErrorRatePhy</a> </li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pub-static-methods">Static Public Member Functions</a> </div> <div class="headertitle"> <div class="title">ns3::PLC_ErrorRatePhy Class Reference</div> </div> </div><!--header--> <div class="contents"> <!-- doxytag: class="ns3::PLC_ErrorRatePhy" --><!-- doxytag: inherits="ns3::PLC_HalfDuplexOfdmPhy" --> <p><code>#include &lt;<a class="el" href="plc-phy_8h_source.html">plc-phy.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for ns3::PLC_ErrorRatePhy:</div> <div class="dyncontent"> <div class="center"> <img src="classns3_1_1PLC__ErrorRatePhy.png" usemap="#ns3::PLC_ErrorRatePhy_map" alt=""/> <map id="ns3::PLC_ErrorRatePhy_map" name="ns3::PLC_ErrorRatePhy_map"> <area href="classns3_1_1PLC__HalfDuplexOfdmPhy.html" title="Base class for half duplex OFDM PHY devices." alt="ns3::PLC_HalfDuplexOfdmPhy" shape="rect" coords="0,56,183,80"/> <area href="classns3_1_1PLC__Phy.html" alt="ns3::PLC_Phy" shape="rect" coords="0,0,183,24"/> </map> </div></div> <p><a href="classns3_1_1PLC__ErrorRatePhy-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classns3_1_1PLC__ErrorRatePhy.html#a108a0f187ead3c1a8aa90d03f95bd653">SetModulationAndCodingScheme</a> (ModulationAndCodingType mcs)</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a158678f9689b9111992c3137f6a0ed57"></a><!-- doxytag: member="ns3::PLC_ErrorRatePhy::GetModulationAndCodingScheme" ref="a158678f9689b9111992c3137f6a0ed57" args="(void)" --> ModulationAndCodingType&#160;</td><td class="memItemRight" valign="bottom"><b>GetModulationAndCodingScheme</b> (void)</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab7bdbe350667587e50ce06413ae2df7b"></a><!-- doxytag: member="ns3::PLC_ErrorRatePhy::PreambleDetectionSuccessful" ref="ab7bdbe350667587e50ce06413ae2df7b" args="(Ptr&lt; const Packet &gt; p, uint32_t txId, Ptr&lt; SpectrumValue &gt; &amp;rxPsd, Time duration, Ptr&lt; const PLC_TrxMetaInfo &gt; metaInfo)" --> virtual void&#160;</td><td class="memItemRight" valign="bottom"><b>PreambleDetectionSuccessful</b> (Ptr&lt; const Packet &gt; p, uint32_t txId, Ptr&lt; SpectrumValue &gt; &amp;rxPsd, Time duration, Ptr&lt; const <a class="el" href="classns3_1_1PLC__TrxMetaInfo.html">PLC_TrxMetaInfo</a> &gt; metaInfo)</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a1441d74fc6df47217973c0d9411333f5"></a><!-- doxytag: member="ns3::PLC_ErrorRatePhy::EndRx" ref="a1441d74fc6df47217973c0d9411333f5" args="(uint32_t txId)" --> virtual void&#160;</td><td class="memItemRight" valign="bottom"><b>EndRx</b> (uint32_t txId)</td></tr> <tr><td colspan="2"><h2><a name="pub-static-methods"></a> Static Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ade327ba03915e38532f318ea2ed9b0e0"></a><!-- doxytag: member="ns3::PLC_ErrorRatePhy::GetTypeId" ref="ade327ba03915e38532f318ea2ed9b0e0" args="(void)" --> static TypeId&#160;</td><td class="memItemRight" valign="bottom"><b>GetTypeId</b> (void)</td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>Simple implementation of a half duplex phy using the error rate model </p> </div><hr/><h2>Member Function Documentation</h2> <a class="anchor" id="a108a0f187ead3c1a8aa90d03f95bd653"></a><!-- doxytag: member="ns3::PLC_ErrorRatePhy::SetModulationAndCodingScheme" ref="a108a0f187ead3c1a8aa90d03f95bd653" args="(ModulationAndCodingType mcs)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void <a class="el" href="classns3_1_1PLC__ErrorRatePhy.html#a108a0f187ead3c1a8aa90d03f95bd653">ns3::PLC_ErrorRatePhy::SetModulationAndCodingScheme</a> </td> <td>(</td> <td class="paramtype">ModulationAndCodingType&#160;</td> <td class="paramname"><em>mcs</em></td><td>)</td> <td><code> [virtual]</code></td> </tr> </table> </div> <div class="memdoc"> <p>Define the Modulation and Coding Scheme to be used </p> <dl class="params"><dt><b>Parameters:</b></dt><dd> <table class="params"> <tr><td class="paramname">mcs</td><td></td></tr> </table> </dd> </dl> </div> </div> <hr/>The documentation for this class was generated from the following files:<ul> <li>model/<a class="el" href="plc-phy_8h_source.html">plc-phy.h</a></li> <li>model/plc-phy.cc</li> </ul> </div><!-- contents --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Enumerations</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small> Generated on Sat Mar 30 2013 21:36:41 for ns-3 PLC model by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
daniel-brettschneider/SiENA
ns-3.26/src/plc/doc/html/classns3_1_1PLC__ErrorRatePhy.html
HTML
gpl-3.0
10,357
using System; using System.Collections.Generic; using System.Text; using System.Drawing; namespace Emgu.CV.Structure { /// <summary> /// OpenCV's KeyPoint class /// </summary> public struct MKeyPoint { /// <summary> /// The location of the keypoint /// </summary> public PointF Point; /// <summary> /// Size of the keypoint /// </summary> public float Size; /// <summary> /// Orientation of the keypoint /// </summary> public float Angle; /// <summary> /// Response of the keypoint /// </summary> public float Response; /// <summary> /// octave /// </summary> public int Octave; /// <summary> /// class id /// </summary> public int ClassId; } }
samuto/UnityOpenCV
Emgu.CV/PInvoke/CvType/MKeyPoint.cs
C#
gpl-3.0
846
/* * H.265 video codec. * Copyright (c) 2013-2014 struktur AG, Dirk Farin <[email protected]> * * This file is part of libde265. * * libde265 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. * * libde265 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 libde265. If not, see <http://www.gnu.org/licenses/>. */ #ifndef DE265_INTRAPRED_H #define DE265_INTRAPRED_H #include "libde265/decctx.h" extern const int intraPredAngle_table[1+34]; void decode_intra_block(decoder_context* ctx, thread_context* tctx, int cIdx, int xB0,int yB0, // position of TU in frame (chroma adapted) int x0,int y0, // position of CU in frame (chroma adapted) int log2TrafoSize, int trafoDepth, enum IntraPredMode intraPredMode, bool transform_skip_flag); void fill_border_samples(decoder_context* ctx, int xB,int yB, int nT, int cIdx, uint8_t* out_border); void decode_intra_prediction(de265_image* img, int xB0,int yB0, enum IntraPredMode intraPredMode, int nT, int cIdx); #endif
ShevaXu/libde265-hack
libde265/intrapred.h
C
gpl-3.0
1,730
// This file is not compiled to a separate object file. It is // included in pathsearch.cc. /* Look up a filename in a path. Copyright (C) 1993, 94, 95, 96, 97, 98 Karl Berry. Copyright (C) 1993, 94, 95, 96, 97 Karl Berry & O. Weber. Copyright (C) 1992, 93, 94, 95, 96, 97 Free Software Foundation, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #if defined (HAVE_CONFIG_H) #include <config.h> #endif #include <map> #include <string> /* System defines are for non-Unix systems only. (Testing for all Unix variations should be done in configure.) Presently the defines used are: DOS OS2 WIN32. I do not use any of these systems myself; if you do, I'd be grateful for any changes. [email protected] */ /* If we have either DOS or OS2, we are DOSISH. */ #if defined (DOS) || defined (OS2) || defined (WIN32) || defined(__MSDOS__) #define DOSISH #endif #if defined (DOSISH) #define MONOCASE_FILENAMES /* case-insensitive filename comparisons */ #endif extern "C" { #if defined(__MINGW32__) #include <windows.h> #include <fcntl.h> #include <dirent.h> #elif defined(WIN32) #define __STDC__ 1 #ifndef _MSC_VER #include "win32lib.h" #endif #endif /* not WIN32 */ #ifdef __DJGPP__ #include <fcntl.h> /* for long filenames' stuff */ #include <dir.h> /* for `getdisk' */ #include <io.h> /* for `setmode' */ #endif } /* Some drivers have partially integrated kpathsea changes. */ #ifndef KPATHSEA #define KPATHSEA 32 #endif /* System dependencies that are figured out by `configure'. If we are compiling standalone, we get our c-auto.h. Otherwise, the package containing us must provide this (unless it can somehow generate ours from c-auto.in). We use <...> instead of "..." so that the current cpp directory (i.e., kpathsea/) won't be searched. */ /* If you want to find subdirectories in a directory with non-Unix semantics (specifically, if a directory with no subdirectories does not have exactly two links), define this. */ #if defined(__DJGPP__) || ! defined (DOSISH) /* Surprise! DJGPP returns st_nlink exactly like on Unix. */ #define ST_NLINK_TRICK #endif /* either not DOSISH or __DJGPP__ */ #ifdef OS2 #define access ln_access #define fopen ln_fopen #define rename ln_rename #define stat ln_stat #endif /* OS2 */ #include "kpse-xfns.h" #include "lo-error.h" #include "oct-env.h" #include "oct-passwd.h" #include "str-vec.h" /* Header files that essentially all of our sources need, and that all implementations have. We include these first, to help with NULL being defined multiple times. */ #include <cstdio> #include <cstdarg> #include <cstdlib> #include <climits> #include <cerrno> #include <cassert> #ifdef HAVE_UNISTD_H #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #include <unistd.h> #endif #include "sysdir.h" #include "statdefs.h" /* define NAME_MAX, the maximum length of a single component in a filename. No such limit may exist, or may vary depending on the filesystem. */ /* Most likely the system will truncate filenames if it is not POSIX, and so we can use the BSD value here. */ #ifndef _POSIX_NAME_MAX #define _POSIX_NAME_MAX 255 #endif #ifndef NAME_MAX #define NAME_MAX _POSIX_NAME_MAX #endif #include <cctype> /* What separates elements in environment variable path lists? */ #ifndef ENV_SEP #if defined (SEPCHAR) && defined (SEPCHAR_STR) #define ENV_SEP SEPCHAR #define ENV_SEP_STRING SEPCHAR_STR #elif defined (DOSISH) #define ENV_SEP ';' #define ENV_SEP_STRING ";" #else #define ENV_SEP ':' #define ENV_SEP_STRING ":" #endif /* not DOS */ #endif /* not ENV_SEP */ #ifndef IS_ENV_SEP #define IS_ENV_SEP(ch) ((ch) == ENV_SEP) #endif /* define PATH_MAX, the maximum length of a filename. Since no such limit may exist, it's preferable to dynamically grow filenames as needed. */ /* Cheat and define this as a manifest constant no matter what, instead of using pathconf. I forget why we want to do this. */ #ifndef _POSIX_PATH_MAX #define _POSIX_PATH_MAX 255 #endif #ifndef PATH_MAX #ifdef MAXPATHLEN #define PATH_MAX MAXPATHLEN #else #define PATH_MAX _POSIX_PATH_MAX #endif #endif /* not PATH_MAX */ /* If NO_DEBUG is defined (not recommended), skip all this. */ #ifndef NO_DEBUG /* OK, we'll have tracing support. */ #define KPSE_DEBUG /* Test if a bit is on. */ #define KPSE_DEBUG_P(bit) (kpathsea_debug & (1 << (bit))) #define KPSE_DEBUG_STAT 0 /* stat calls */ #define KPSE_DEBUG_HASH 1 /* hash lookups */ #define KPSE_DEBUG_FOPEN 2 /* fopen/fclose calls */ #define KPSE_DEBUG_PATHS 3 /* search path initializations */ #define KPSE_DEBUG_EXPAND 4 /* path element expansion */ #define KPSE_DEBUG_SEARCH 5 /* searches */ #define KPSE_DEBUG_VARS 6 /* variable values */ #define KPSE_LAST_DEBUG KPSE_DEBUG_VARS /* A printf for the debugging. */ #define DEBUGF_START() do { fputs ("kdebug:", stderr) #define DEBUGF_END() fflush (stderr); } while (0) #define DEBUGF(str) \ DEBUGF_START (); fputs (str, stderr); DEBUGF_END () #define DEBUGF1(str, e1) \ DEBUGF_START (); fprintf (stderr, str, e1); DEBUGF_END () #define DEBUGF2(str, e1, e2) \ DEBUGF_START (); fprintf (stderr, str, e1, e2); DEBUGF_END () #define DEBUGF3(str, e1, e2, e3) \ DEBUGF_START (); fprintf (stderr, str, e1, e2, e3); DEBUGF_END () #define DEBUGF4(str, e1, e2, e3, e4) \ DEBUGF_START (); fprintf (stderr, str, e1, e2, e3, e4); DEBUGF_END () #undef fopen #define fopen kpse_fopen_trace static FILE *fopen (const char *filename, const char *mode); #endif /* not NO_DEBUG */ #ifdef KPSE_DEBUG static unsigned int kpathsea_debug = 0; #endif #if defined (WIN32) && !defined (__MINGW32__) /* System description file for Windows NT. */ /* * Define symbols to identify the version of Unix this is. * Define all the symbols that apply correctly. */ #ifndef DOSISH #define DOSISH #endif #ifndef MAXPATHLEN #define MAXPATHLEN _MAX_PATH #endif /* These have to be defined because our compilers treat __STDC__ as being defined (most of them anyway). */ #define access _access #define stat _stat #define strdup _strdup #define S_IFMT _S_IFMT #define S_IFDIR _S_IFDIR /* Define this so that winsock.h definitions don't get included when windows.h is... For this to have proper effect, config.h must always be included before windows.h. */ #define _WINSOCKAPI_ 1 #include <windows.h> /* For proper declaration of environ. */ #include <io.h> #include <fcntl.h> #include <process.h> /* ============================================================ */ #endif /* WIN32 */ /* Define common sorts of messages. */ /* This should be called only after a system call fails. Don't exit with status `errno', because that might be 256, which would mean success (exit statuses are truncated to eight bits). */ #define FATAL_PERROR(str) \ do \ { \ fputs ("pathsearch: ", stderr); \ perror (str); exit (EXIT_FAILURE); \ } \ while (0) #define FATAL(str) \ do \ { \ fputs ("pathsearch: fatal: ", stderr); \ fputs (str, stderr); \ fputs (".\n", stderr); \ exit (1); \ } \ while (0) #ifndef WIN32 static void xclosedir (DIR *d); #endif /* It's a little bizarre to be using the same type for the list and the elements of the list, but no reason not to in this case, I think -- we never need a NULL string in the middle of the list, and an extra NULL/NULL element always at the end is inconsequential. */ struct str_llist_elt { std::string str; int moved; struct str_llist_elt *next; }; typedef str_llist_elt str_llist_elt_type; typedef str_llist_elt *str_llist_type; #define STR_LLIST(sl) ((sl).str) #define STR_LLIST_MOVED(sl) ((sl).moved) #define STR_LLIST_NEXT(sl) ((sl).next) static void str_llist_add (str_llist_type *l, const std::string& str); static void str_llist_float (str_llist_type *l, str_llist_elt_type *mover); static std::string kpse_var_expand (const std::string& src); static str_llist_type *kpse_element_dirs (const std::string& elt); static std::string kpse_expand (const std::string& s); static std::string kpse_expand_default (const std::string& path, const std::string& dflt); static string_vector kpse_db_search (const std::string& name, const std::string& path_elt, bool all); #include <ctime> /* for `time' */ static bool kpse_is_env_sep (char c) { return IS_ENV_SEP (c); } /* These routines just check the return status from standard library routines and abort if an error happens. */ static FILE * xfopen (const std::string& filename, const char *mode) { FILE *f; assert (! filename.empty () && mode); f = fopen (filename.c_str (), mode); if (! f) FATAL_PERROR (filename.c_str ()); return f; } /* A single (key,value) pair. */ struct hash_element_type { std::string key; std::string value; struct hash_element_type *next; }; /* The usual arrangement of buckets initialized to null. */ struct hash_table_type { hash_element_type **buckets; unsigned size; }; static unsigned kpse_hash (hash_table_type table, const std::string& key) { unsigned n = 0; /* Our keys aren't often anagrams of each other, so no point in weighting the characters. */ size_t len = key.length (); for (size_t i = 0; i < len; i++) n = (n + n + key[i]) % table.size; return n; } /* Look up STR in MAP. Return a (dynamically-allocated) list of the corresponding strings or NULL if no match. */ static string_vector hash_lookup (hash_table_type table, const std::string& key) { hash_element_type *p; string_vector ret; unsigned n = kpse_hash (table, key); /* Look at everything in this bucket. */ for (p = table.buckets[n]; p; p = p->next) if (key == p->key) ret.append (p->value); #ifdef KPSE_DEBUG if (KPSE_DEBUG_P (KPSE_DEBUG_HASH)) { DEBUGF1 ("hash_lookup (%s) =>", key.c_str ()); if (ret.empty ()) fputs (" (nil)\n", stderr); else { int len = ret.length (); for (int i = 0; i < len; i++) { putc (' ', stderr); fputs (ret[i].c_str (), stderr); } putc ('\n', stderr); } fflush (stderr); } #endif return ret; } /* A way to step through a path, extracting one directory name at a time. */ class kpse_path_iterator { public: kpse_path_iterator (const std::string& p) : path (p), b (0), e (0), len (path.length ()) { set_end (); } kpse_path_iterator (const kpse_path_iterator& pi) : path (pi.path), b (pi.b), e (pi.e), len (pi.len) { } kpse_path_iterator operator ++ (int) { kpse_path_iterator retval (*this); next (); return retval; } std::string operator * (void) { return path.substr (b, e-b); } bool operator != (const size_t sz) { return b != sz; } private: const std::string& path; size_t b; size_t e; size_t len; void set_end (void) { e = b + 1; if (e == len) ; /* OK, we have found the last element. */ else if (e > len) b = e = std::string::npos; else { /* Find the next colon not enclosed by braces (or the end of the path). */ int brace_level = 0; while (e < len && ! (brace_level == 0 && kpse_is_env_sep (path[e]))) e++; } } void next (void) { b = e + 1; /* Skip any consecutive colons. */ while (b < len && kpse_is_env_sep (path[b])) b++; if (b >= len) b = e = std::string::npos; else set_end (); } // No assignment. kpse_path_iterator& operator = (const kpse_path_iterator&); }; /* Here's the simple one, when a program just wants a value. */ static std::string kpse_var_value (const std::string& var) { std::string ret; std::string tmp = octave_env::getenv (var); if (! tmp.empty ()) ret = kpse_var_expand (tmp); #ifdef KPSE_DEBUG if (KPSE_DEBUG_P (KPSE_DEBUG_VARS)) DEBUGF2 ("variable: %s = %s\n", var.c_str (), tmp.empty () ? "(nil)" : tmp.c_str ()); #endif return ret; } /* Truncate any too-long components in NAME, returning the result. It's too bad this is necessary. See comments in readable.c for why. */ static std::string kpse_truncate_filename (const std::string& name) { unsigned c_len = 0; /* Length of current component. */ unsigned ret_len = 0; /* Length of constructed result. */ std::string ret = name; size_t len = name.length (); for (size_t i = 0; i < len; i++) { if (IS_DIR_SEP (name[i]) || IS_DEVICE_SEP (name[i])) { /* At a directory delimiter, reset component length. */ c_len = 0; } else if (c_len > NAME_MAX) { /* If past the max for a component, ignore this character. */ continue; } /* Copy this character. */ ret[ret_len++] = name[i]; c_len++; } ret.resize (ret_len); return ret; } /* If access can read FN, run stat (assigning to stat buffer ST) and check that fn is not a directory. Don't check for just being a regular file, as it is potentially useful to read fifo's or some kinds of devices. */ #ifdef WIN32 static inline bool READABLE (const std::string& fn, struct stat&) { const char *t = fn.c_str (); return (GetFileAttributes (t) != 0xFFFFFFFF && ! (GetFileAttributes (t) & FILE_ATTRIBUTE_DIRECTORY)); } #else static inline bool READABLE (const std::string& fn, struct stat& st) { const char *t = fn.c_str (); return (access (t, R_OK) == 0 && stat (t, &(st)) == 0 && ! S_ISDIR (st.st_mode)); } #endif /* POSIX invented the brain-damage of not necessarily truncating filename components; the system's behavior is defined by the value of the symbol _POSIX_NO_TRUNC, but you can't change it dynamically! Generic const return warning. See extend-fname.c. */ static std::string kpse_readable_file (const std::string& name) { struct stat st; std::string ret; if (READABLE (name, st)) { ret = name; #ifdef ENAMETOOLONG } else if (errno == ENAMETOOLONG) { ret = kpse_truncate_filename (name); /* Perhaps some other error will occur with the truncated name, so let's call access again. */ if (! READABLE (ret, st)) { /* Failed. */ ret = std::string (); } #endif /* ENAMETOOLONG */ } else { /* Some other error. */ if (errno == EACCES) { /* Maybe warn them if permissions are bad. */ perror (name.c_str ()); } ret = std::string (); } return ret; } /* Sorry this is such a system-dependent mess, but I can't see any way to usefully generalize. */ static bool kpse_absolute_p (const std::string& filename, int relative_ok) { size_t len = filename.length (); int absolute = (len > 0 && IS_DIR_SEP (filename[0])) #ifdef DOSISH /* Novell allows non-alphanumeric drive letters. */ || (len > 0 && IS_DEVICE_SEP (filename[1])) #endif /* DOSISH */ #ifdef WIN32 /* UNC names */ || (len > 1 && filename[0] == '\\' && filename[1] == '\\') #endif ; int explicit_relative = relative_ok && (len > 1 && filename[0] == '.' && (IS_DIR_SEP (filename[1]) || (len > 2 && filename[1] == '.' && IS_DIR_SEP (filename[2])))); return absolute || explicit_relative; } /* The very first search is for texmf.cnf, called when someone tries to initialize the TFM path or whatever. init_path calls kpse_cnf_get which calls kpse_all_path_search to find all the texmf.cnf's. We need to do various special things in this case, since we obviously don't yet have the configuration files when we're searching for the configuration files. */ static bool first_search = true; /* This function is called after every search (except the first, since we definitely want to allow enabling the logging in texmf.cnf) to record the filename(s) found in $TEXMFLOG. */ static void log_search (const string_vector& filenames) { static FILE *log_file = 0; static bool first_time = true; /* Need to open the log file? */ if (first_time) { first_time = false; /* Get name from either envvar or config file. */ std::string log_name = kpse_var_value ("TEXMFLOG"); if (! log_name.empty ()) { log_file = xfopen (log_name.c_str (), "a"); if (! log_file) perror (log_name.c_str ()); } } if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH) || log_file) { /* FILENAMES should never be null, but safety doesn't hurt. */ for (int e = 0; e < filenames.length () && ! filenames[e].empty (); e++) { std::string filename = filenames[e]; /* Only record absolute filenames, for privacy. */ if (log_file && kpse_absolute_p (filename.c_str (), false)) fprintf (log_file, "%lu %s\n", static_cast<unsigned long> (time (0)), filename.c_str ()); /* And show them online, if debugging. We've already started the debugging line in `search', where this is called, so just print the filename here, don't use DEBUGF. */ if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) fputs (filename.c_str (), stderr); } } } /* Concatenate each element in DIRS with NAME (assume each ends with a /, to save time). If SEARCH_ALL is false, return the first readable regular file. Else continue to search for more. In any case, if none, return a list containing just NULL. We keep a single buffer for the potential filenames and reallocate only when necessary. I'm not sure it's noticeably faster, but it does seem cleaner. (We do waste a bit of space in the return value, though, since we don't shrink it to the final size returned.) */ static string_vector dir_list_search (str_llist_type *dirs, const std::string& name, bool search_all) { str_llist_elt_type *elt; string_vector ret; for (elt = *dirs; elt; elt = STR_LLIST_NEXT (*elt)) { const std::string dir = STR_LLIST (*elt); std::string potential = dir + name; std::string tmp = kpse_readable_file (potential); if (! tmp.empty ()) { ret.append (potential); /* Move this element towards the top of the list. */ str_llist_float (dirs, elt); if (! search_all) return ret; } } return ret; } /* This is called when NAME is absolute or explicitly relative; if it's readable, return (a list containing) it; otherwise, return NULL. */ static string_vector absolute_search (const std::string& name) { string_vector ret_list; std::string found = kpse_readable_file (name); /* Add `found' to the return list even if it's null; that tells the caller we didn't find anything. */ ret_list.append (found); return ret_list; } /* This is the hard case -- look for NAME in PATH. If ALL is false, return the first file found. Otherwise, search all elements of PATH. */ static string_vector path_search (const std::string& path, const std::string& name, bool /* must_exist */, bool all) { string_vector ret_list; bool done = false; for (kpse_path_iterator pi (path); ! done && pi != std::string::npos; pi++) { std::string elt = *pi; string_vector found; bool allow_disk_search = true; if (elt.length () > 1 && elt[0] == '!' && elt[1] == '!') { /* Those magic leading chars in a path element means don't search the disk for this elt. And move past the magic to get to the name. */ allow_disk_search = false; elt = elt.substr (2); } /* Do not touch the device if present */ if (NAME_BEGINS_WITH_DEVICE (elt)) { while (elt.length () > 3 && IS_DIR_SEP (elt[2]) && IS_DIR_SEP (elt[3])) { elt[2] = elt[1]; elt[1] = elt[0]; elt = elt.substr (1); } } else { /* We never want to search the whole disk. */ while (elt.length () > 1 && IS_DIR_SEP (elt[0]) && IS_DIR_SEP (elt[1])) elt = elt.substr (1); } /* Try ls-R, unless we're searching for texmf.cnf. Our caller (search), also tests first_search, and does the resetting. */ found = first_search ? string_vector () : kpse_db_search (name, elt, all); /* Search the filesystem if (1) the path spec allows it, and either (2a) we are searching for texmf.cnf ; or (2b) no db exists; or (2c) no db's are relevant to this elt; or (3) MUST_EXIST && NAME was not in the db. In (2*), `found' will be NULL. In (3), `found' will be an empty list. */ if (allow_disk_search && found.empty ()) { str_llist_type *dirs = kpse_element_dirs (elt); if (dirs && *dirs) found = dir_list_search (dirs, name, all); } /* Did we find anything anywhere? */ if (! found.empty ()) { if (all) ret_list.append (found); else { ret_list.append (found[0]); done = true; } } } return ret_list; } /* Search PATH for ORIGINAL_NAME. If ALL is false, or ORIGINAL_NAME is absolute_p, check ORIGINAL_NAME itself. Otherwise, look at each element of PATH for the first readable ORIGINAL_NAME. Always return a list; if no files are found, the list will contain just NULL. If ALL is true, the list will be terminated with NULL. */ static string_vector search (const std::string& path, const std::string& original_name, bool must_exist, bool all) { string_vector ret_list; bool absolute_p; /* Make a leading ~ count as an absolute filename, and expand $FOO's. */ std::string name = kpse_expand (original_name); /* If the first name is absolute or explicitly relative, no need to consider PATH at all. */ absolute_p = kpse_absolute_p (name, true); if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) DEBUGF4 ("start search (file=%s, must_exist=%d, find_all=%d, path=%s).\n", name.c_str (), must_exist, all, path.c_str ()); /* Find the file(s). */ ret_list = absolute_p ? absolute_search (name) : path_search (path, name, must_exist, all); /* The very first search is for texmf.cnf. We can't log that, since we want to allow setting TEXMFLOG in texmf.cnf. */ if (first_search) { first_search = false; } else { /* Record the filenames we found, if desired. And wrap them in a debugging line if we're doing that. */ if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) DEBUGF1 ("search (%s) =>", original_name.c_str ()); log_search (ret_list); if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) putc ('\n', stderr); } return ret_list; } /* Search PATH for the first NAME. */ /* Call `kpse_expand' on NAME. If the result is an absolute or explicitly relative filename, check whether it is a readable (regular) file. Otherwise, look in each of the directories specified in PATH (also do tilde and variable expansion on elements in PATH), using a prebuilt db (see db.h) if it's relevant for a given path element. If the prebuilt db doesn't exist, or if MUST_EXIST is true and NAME isn't found in the prebuilt db, look on the filesystem. (I.e., if MUST_EXIST is false, and NAME isn't found in the db, do *not* look on the filesystem.) The caller must expand PATH. This is because it makes more sense to do this once, in advance, instead of for every search using it. In any case, return the complete filename if found, otherwise NULL. */ static std::string kpse_path_search (const std::string& path, const std::string& name, bool must_exist) { string_vector ret_list = search (path, name, must_exist, false); return ret_list.empty () ? std::string () : ret_list[0]; } /* Search all elements of PATH for files named NAME. Not sure if it's right to assert `must_exist' here, but it suffices now. */ /* Like `kpse_path_search' with MUST_EXIST true, but return a list of all the filenames (or NULL if none), instead of taking the first. */ static string_vector kpse_all_path_search (const std::string& path, const std::string& name) { return search (path, name, true, true); } /* This is the hard case -- look in each element of PATH for each element of NAMES. If ALL is false, return the first file found. Otherwise, search all elements of PATH. */ static string_vector path_find_first_of (const std::string& path, const string_vector& names, bool /* must_exist */, bool all) { string_vector ret_list; bool done = false; for (kpse_path_iterator pi (path); ! done && pi != std::string::npos; pi++) { std::string elt = *pi; str_llist_type *dirs; str_llist_elt_type *dirs_elt; string_vector found; bool allow_disk_search = true; if (elt.length () > 1 && elt[0] == '!' && elt[1] == '!') { /* Those magic leading chars in a path element means don't search the disk for this elt. And move past the magic to get to the name. */ allow_disk_search = false; elt = elt.substr (2); } /* Do not touch the device if present */ if (NAME_BEGINS_WITH_DEVICE (elt)) { while (elt.length () > 3 && IS_DIR_SEP (elt[2]) && IS_DIR_SEP (elt[3])) { elt[2] = elt[1]; elt[1] = elt[0]; elt = elt.substr (1); } } else { /* We never want to search the whole disk. */ while (elt.length () > 1 && IS_DIR_SEP (elt[0]) && IS_DIR_SEP (elt[1])) elt = elt.substr (1); } /* We have to search one directory at a time. */ dirs = kpse_element_dirs (elt); for (dirs_elt = *dirs; dirs_elt; dirs_elt = STR_LLIST_NEXT (*dirs_elt)) { const std::string dir = STR_LLIST (*dirs_elt); int len = names.length (); for (int i = 0; i < len && !done; i++) { std::string name = names[i]; /* Try ls-R, unless we're searching for texmf.cnf. Our caller (find_first_of), also tests first_search, and does the resetting. */ found = first_search ? string_vector () : kpse_db_search (name, dir.c_str (), all); /* Search the filesystem if (1) the path spec allows it, and either (2a) we are searching for texmf.cnf ; or (2b) no db exists; or (2c) no db's are relevant to this elt; or (3) MUST_EXIST && NAME was not in the db. In (2*), `found' will be NULL. In (3), `found' will be an empty list. */ if (allow_disk_search && found.empty ()) { static str_llist_type *tmp = 0; if (! tmp) { tmp = new str_llist_type; *tmp = 0; str_llist_add (tmp, ""); } STR_LLIST (*(*tmp)) = dir; found = dir_list_search (tmp, name, all); } /* Did we find anything anywhere? */ if (! found.empty ()) { if (all) ret_list.append (found); else { ret_list.append (found[0]); done = true; } } } } } return ret_list; } static string_vector find_first_of (const std::string& path, const string_vector& names, bool must_exist, bool all) { string_vector ret_list; if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) { fputs ("start find_first_of ((", stderr); int len = names.length (); for (int i = 0; i < len; i++) { if (i == 0) fputs (names[i].c_str (), stderr); else fprintf (stderr, ", %s", names[i].c_str ()); } fprintf (stderr, "), path=%s, must_exist=%d).\n", path.c_str (), must_exist); } for (int i = 0; i < names.length (); i++) { std::string name = names[i]; if (kpse_absolute_p (name, true)) { /* If the name is absolute or explicitly relative, no need to consider PATH at all. If we find something, then we are done. */ ret_list = absolute_search (name); if (! ret_list.empty ()) return ret_list; } } /* Find the file. */ ret_list = path_find_first_of (path, names, must_exist, all); /* The very first search is for texmf.cnf. We can't log that, since we want to allow setting TEXMFLOG in texmf.cnf. */ if (first_search) { first_search = false; } else { /* Record the filenames we found, if desired. And wrap them in a debugging line if we're doing that. */ if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) { fputs ("find_first_of (", stderr); int len = names.length (); for (int i = 0; i < len; i++) { if (i == 0) fputs (names[i].c_str (), stderr); else fprintf (stderr, ", %s", names[i].c_str ()); } fputs (") =>", stderr); } log_search (ret_list); if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) putc ('\n', stderr); } return ret_list; } /* Search each element of PATH for each element of NAMES. Return the first one found. */ /* Search each element of PATH for each element in the list of NAMES. Return the first one found. */ static std::string kpse_path_find_first_of (const std::string& path, const string_vector& names, bool must_exist) { string_vector ret_list = find_first_of (path, names, must_exist, false); return ret_list.empty () ? std::string () : ret_list[0]; } /* Search each element of PATH for each element of NAMES and return a list containing everything found, in the order found. */ /* Like `kpse_path_find_first_of' with MUST_EXIST true, but return a list of all the filenames (or NULL if none), instead of taking the first. */ static string_vector kpse_all_path_find_first_of (const std::string& path, const string_vector& names) { return find_first_of (path, names, true, true); } /* General expansion. Some of this file (the brace-expansion code from bash) is covered by the GPL; this is the only GPL-covered code in kpathsea. The part of the file that I wrote (the first couple of functions) is covered by the LGPL. */ /* If NAME has a leading ~ or ~user, Unix-style, expand it to the user's home directory, and return a new malloced string. If no ~, or no <pwd.h>, just return NAME. */ static std::string kpse_tilde_expand (const std::string& name) { std::string expansion; /* If no leading tilde, do nothing. */ if (name.empty () || name[0] != '~') { expansion = name; /* If a bare tilde, return the home directory or `.'. (Very unlikely that the directory name will do anyone any good, but ... */ } else if (name.length () == 1) { expansion = octave_env::getenv ("HOME"); if (expansion.empty ()) expansion = "."; /* If `~/', remove any trailing / or replace leading // in $HOME. Should really check for doubled intermediate slashes, too. */ } else if (IS_DIR_SEP (name[1])) { unsigned c = 1; std::string home = octave_env::getenv ("HOME"); if (home.empty ()) home = "."; size_t home_len = home.length (); /* handle leading // */ if (home_len > 1 && IS_DIR_SEP (home[0]) && IS_DIR_SEP (home[1])) home = home.substr (1); /* omit / after ~ */ if (IS_DIR_SEP (home[home_len - 1])) c++; expansion = home + name.substr (c); /* If `~user' or `~user/', look up user in the passwd database (but OS/2 doesn't have this concept. */ } else #ifdef HAVE_PWD_H { unsigned c = 2; /* find user name */ while (name.length () > c && ! IS_DIR_SEP (name[c])) c++; std::string user = name.substr (1, c-1); /* We only need the cast here for (deficient) systems which do not declare `getpwnam' in <pwd.h>. */ octave_passwd p = octave_passwd::getpwnam (user); /* If no such user, just use `.'. */ std::string home = p ? p.dir () : std::string ("."); if (home.empty ()) home = "."; /* handle leading // */ if (home.length () > 1 && IS_DIR_SEP (home[0]) && IS_DIR_SEP (home[1])) home = home.substr (1); /* If HOME ends in /, omit the / after ~user. */ if (name.length () > c && IS_DIR_SEP (home[home.length () - 1])) c++; expansion = name.length () > c ? home : home + name.substr (c); } #else /* not HAVE_PWD_H */ expansion = name; #endif /* not HAVE_PWD_H */ return expansion; } /* Do variable expansion first so ~${USER} works. (Besides, it's what the shells do.) */ /* Call kpse_var_expand and kpse_tilde_expand (in that order). Result is always in fresh memory, even if no expansions were done. */ static std::string kpse_expand (const std::string& s) { std::string var_expansion = kpse_var_expand (s); return kpse_tilde_expand (var_expansion); } /* Forward declarations of functions from the original expand.c */ static string_vector brace_expand (const std::string&); /* If $KPSE_DOT is defined in the environment, prepend it to any relative path components. */ static std::string kpse_expand_kpse_dot (const std::string& path) { std::string ret; std::string kpse_dot = octave_env::getenv ("KPSE_DOT"); if (kpse_dot.empty ()) return path; for (kpse_path_iterator pi (path); pi != std::string::npos; pi++) { std::string elt = *pi; /* We assume that the !! magic is only used on absolute components. Single "." get special treatment, as does "./" or its equivalent. */ size_t elt_len = elt.length (); if (kpse_absolute_p (elt, false) || (elt_len > 1 && elt[0] == '!' && elt[1] == '!')) ret += elt + ENV_SEP_STRING; else if (elt_len == 1 && elt[0] == '.') ret += kpse_dot + ENV_SEP_STRING; else if (elt_len > 1 && elt[0] == '.' && IS_DIR_SEP (elt[1])) ret += kpse_dot + elt.substr (1) + ENV_SEP_STRING; else ret += kpse_dot + DIR_SEP_STRING + elt + ENV_SEP_STRING; } int len = ret.length (); if (len > 0) ret.resize (len-1); return ret; } /* Do brace expansion on ELT; then do variable and ~ expansion on each element of the result; then do brace expansion again, in case a variable definition contained braces (e.g., $TEXMF). Return a string comprising all of the results separated by ENV_SEP_STRING. */ static std::string kpse_brace_expand_element (const std::string& elt) { std::string ret; string_vector expansions = brace_expand (elt); for (int i = 0; i < expansions.length (); i++) { /* Do $ and ~ expansion on each element. */ std::string x = kpse_expand (expansions[i]); if (x != expansions[i]) { /* If we did any expansions, do brace expansion again. Since recursive variable definitions are not allowed, this recursion must terminate. (In practice, it's unlikely there will ever be more than one level of recursion.) */ x = kpse_brace_expand_element (x); } ret += x + ENV_SEP_STRING; } ret.resize (ret.length () - 1); return ret; } /* Do brace expansion and call `kpse_expand' on each element of the result; return the final expansion (always in fresh memory, even if no expansions were done). We don't call `kpse_expand_default' because there is a whole sequence of defaults to run through; see `kpse_init_format'. */ static std::string kpse_brace_expand (const std::string& path) { /* Must do variable expansion first because if we have foo = .:~ TEXINPUTS = $foo we want to end up with TEXINPUTS = .:/home/karl. Since kpse_path_element is not reentrant, we must get all the path elements before we start the loop. */ std::string tmp = kpse_var_expand (path); std::string ret; for (kpse_path_iterator pi (tmp); pi != std::string::npos; pi++) { std::string elt = *pi; /* Do brace expansion first, so tilde expansion happens in {~ka,~kb}. */ std::string expansion = kpse_brace_expand_element (elt); ret += expansion + ENV_SEP_STRING; } size_t len = ret.length (); if (len > 0) ret.resize (len-1); return kpse_expand_kpse_dot (ret); } /* Expand all special constructs in a path, and include only the actually existing directories in the result. */ /* Do brace expansion and call `kpse_expand' on each argument of the result, then expand any `//' constructs. The final expansion (always in fresh memory) is a path of all the existing directories that match the pattern. */ static std::string kpse_path_expand (const std::string& path) { std::string ret; unsigned len; len = 0; /* Expand variables and braces first. */ std::string tmp = kpse_brace_expand (path); /* Now expand each of the path elements, printing the results */ for (kpse_path_iterator pi (tmp); pi != std::string::npos; pi++) { std::string elt = *pi; str_llist_type *dirs; /* Skip and ignore magic leading chars. */ if (elt.length () > 1 && elt[0] == '!' && elt[1] == '!') elt = elt.substr (2); /* Do not touch the device if present */ if (NAME_BEGINS_WITH_DEVICE (elt)) { while (elt.length () > 3 && IS_DIR_SEP (elt[2]) && IS_DIR_SEP (elt[3])) { elt[2] = elt[1]; elt[1] = elt[0]; elt = elt.substr (1); } } else { /* We never want to search the whole disk. */ while (elt.length () > 1 && IS_DIR_SEP (elt[0]) && IS_DIR_SEP (elt[1])) elt = elt.substr (1); } /* Search the disk for all dirs in the component specified. Be faster to check the database, but this is more reliable. */ dirs = kpse_element_dirs (elt); if (dirs && *dirs) { str_llist_elt_type *dir; for (dir = *dirs; dir; dir = STR_LLIST_NEXT (*dir)) { const std::string thedir = STR_LLIST (*dir); unsigned dirlen = thedir.length (); ret += thedir; len += dirlen; /* Retain trailing slash if that's the root directory. */ if (dirlen == 1 || (dirlen == 3 && NAME_BEGINS_WITH_DEVICE (thedir) && IS_DIR_SEP (thedir[2]))) { ret += ENV_SEP_STRING; len++; } ret[len-1] = ENV_SEP; } } } if (len > 0) ret.resize (len-1); return ret; } /* braces.c -- code for doing word expansion in curly braces. Taken from bash 1.14.5. [Ans subsequently modified for kpatshea.] Copyright (C) 1987,1991 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, 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; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define brace_whitespace(c) (! (c) || (c) == ' ' || (c) == '\t' || (c) == '\n') /* Basic idea: Segregate the text into 3 sections: preamble (stuff before an open brace), postamble (stuff after the matching close brace) and amble (stuff after preamble, and before postamble). Expand amble, and then tack on the expansions to preamble. Expand postamble, and tack on the expansions to the result so far. */ /* Return a new array of strings which is the result of appending each string in ARR2 to each string in ARR1. The resultant array is len (arr1) * len (arr2) long. For convenience, ARR1 (and its contents) are free ()'ed. ARR1 can be NULL, in that case, a new version of ARR2 is returned. */ static string_vector array_concat (const string_vector& arr1, const string_vector& arr2) { string_vector result; if (arr1.empty ()) result = arr2; else if (arr2.empty ()) result = arr1; else { int len1 = arr1.length (); int len2 = arr2.length (); result = string_vector (len1 * len2); int k = 0; for (int i = 0; i < len2; i++) for (int j = 0; j < len1; j++) result[k++] = arr1[j] + arr2[i]; } return result; } static int brace_gobbler (const std::string&, int&, int); static string_vector expand_amble (const std::string&); /* Return an array of strings; the brace expansion of TEXT. */ static string_vector brace_expand (const std::string& text) { /* Find the text of the preamble. */ int i = 0; int c = brace_gobbler (text, i, '{'); std::string preamble = text.substr (0, i); string_vector result = string_vector (preamble); if (c == '{') { /* Find the amble. This is the stuff inside this set of braces. */ int start = ++i; c = brace_gobbler (text, i, '}'); /* What if there isn't a matching close brace? */ if (! c) { (*current_liboctave_warning_handler) ("%s: Unmatched {", text.c_str ()); result = string_vector (text); } else { std::string amble = text.substr (start, i-start); result = array_concat (result, expand_amble (amble)); std::string postamble = text.substr (i+1); result = array_concat (result, brace_expand (postamble)); } } return result; } /* The character which is used to separate arguments. */ static int brace_arg_separator = ','; /* Expand the text found inside of braces. We simply try to split the text at BRACE_ARG_SEPARATORs into separate strings. We then brace expand each slot which needs it, until there are no more slots which need it. */ static string_vector expand_amble (const std::string& text) { string_vector result; size_t text_len = text.length (); size_t start; int i, c; for (start = 0, i = 0, c = 1; c && start < text_len; start = ++i) { int i0 = i; int c0 = brace_gobbler (text, i0, brace_arg_separator); int i1 = i; int c1 = brace_gobbler (text, i1, ENV_SEP); c = c0 | c1; i = (i0 < i1 ? i0 : i1); std::string tem = text.substr (start, i-start); string_vector partial = brace_expand (tem); if (result.empty ()) result = partial; else result.append (partial); } return result; } /* Start at INDEX, and skip characters in TEXT. Set INDEX to the index of the character matching SATISFY. This understands about quoting. Return the character that caused us to stop searching; this is either the same as SATISFY, or 0. */ static int brace_gobbler (const std::string& text, int& indx, int satisfy) { int c = 0, level = 0, quoted = 0, pass_next = 0; size_t text_len = text.length (); size_t i = indx; for (; i < text_len; i++) { c = text[i]; if (pass_next) { pass_next = 0; continue; } /* A backslash escapes the next character. This allows backslash to escape the quote character in a double-quoted string. */ if (c == '\\' && (quoted == 0 || quoted == '"' || quoted == '`')) { pass_next = 1; continue; } if (quoted) { if (c == quoted) quoted = 0; continue; } if (c == '"' || c == '\'' || c == '`') { quoted = c; continue; } if (c == satisfy && !level && !quoted) { /* We ignore an open brace surrounded by whitespace, and also an open brace followed immediately by a close brace, that was preceded with whitespace. */ if (c == '{' && ((i == 0 || brace_whitespace (text[i-1])) && (i+1 < text_len && (brace_whitespace (text[i+1]) || text[i+1] == '}')))) continue; /* If this is being compiled as part of bash, ignore the `{' in a `${}' construct */ if ((c != '{') || i == 0 || (text[i-1] != '$')) break; } if (c == '{') level++; else if (c == '}' && level) level--; } indx = i; return c; } /* For each file format, we record the following information. The main thing that is not part of this structure is the environment variable lists. They are used directly in tex-file.c. We could incorporate them here, but it would complicate the code a bit. We could also do it via variable expansion, but not now, maybe not ever: ${PKFONTS-${TEXFONTS-/usr/local/lib/texmf/fonts//}}. */ struct kpse_format_info_type { std::string type; /* Human-readable description. */ std::string path; /* The search path to use. */ std::string raw_path; /* Pre-$~ (but post-default) expansion. */ std::string path_source; /* Where the path started from. */ std::string override_path; /* From client environment variable. */ std::string client_path; /* E.g., from dvips's config.ps. */ std::string cnf_path; /* From texmf.cnf. */ std::string default_path; /* If all else fails. */ string_vector suffix; /* For kpse_find_file to check for/append. */ }; /* The sole variable of that type, indexed by `kpse_file_format_type'. Initialized by calls to `kpse_find_file' for `kpse_init_format'. */ static kpse_format_info_type kpse_format_info; /* And EXPAND_DEFAULT calls kpse_expand_default on try_path and the present info->path. */ #define EXPAND_DEFAULT(try_path, source_string) \ do \ { \ if (! try_path.empty ()) \ { \ info.raw_path = try_path; \ info.path = kpse_expand_default (try_path, info.path); \ info.path_source = source_string; \ } \ } \ while (0) static hash_table_type db; /* The hash table for all the ls-R's. */ static hash_table_type alias_db; static string_vector db_dir_list; /* Return true if FILENAME could be in PATH_ELT, i.e., if the directory part of FILENAME matches PATH_ELT. Have to consider // wildcards, but $ and ~ expansion have already been done. */ static bool match (const std::string& filename_arg, const std::string& path_elt_arg) { const char *filename = filename_arg.c_str (); const char *path_elt = path_elt_arg.c_str (); const char *original_filename = filename; bool matched = false; for (; *filename && *path_elt; filename++, path_elt++) { if (*filename == *path_elt) /* normal character match */ ; else if (IS_DIR_SEP (*path_elt) /* at // */ && original_filename < filename && IS_DIR_SEP (path_elt[-1])) { while (IS_DIR_SEP (*path_elt)) path_elt++; /* get past second and any subsequent /'s */ if (*path_elt == 0) { /* Trailing //, matches anything. We could make this part of the other case, but it seems pointless to do the extra work. */ matched = true; break; } else { /* Intermediate //, have to match rest of PATH_ELT. */ for (; !matched && *filename; filename++) { /* Try matching at each possible character. */ if (IS_DIR_SEP (filename[-1]) && *filename == *path_elt) matched = match (filename, path_elt); } /* Prevent filename++ when *filename='\0'. */ break; } } else /* normal character nonmatch, quit */ break; } /* If we've reached the end of PATH_ELT, check that we're at the last component of FILENAME, we've matched. */ if (! matched && *path_elt == 0) { /* Probably PATH_ELT ended with `vf' or some such, and FILENAME ends with `vf/ptmr.vf'. In that case, we'll be at a directory separator. On the other hand, if PATH_ELT ended with a / (as in `vf/'), FILENAME being the same `vf/ptmr.vf', we'll be at the `p'. Upshot: if we're at a dir separator in FILENAME, skip it. But if not, that's ok, as long as there are no more dir separators. */ if (IS_DIR_SEP (*filename)) filename++; while (*filename && !IS_DIR_SEP (*filename)) filename++; matched = *filename == 0; } return matched; } /* If DB_DIR is a prefix of PATH_ELT, return true; otherwise false. That is, the question is whether to try the db for a file looked up in PATH_ELT. If PATH_ELT == ".", for example, the answer is no. If PATH_ELT == "/usr/local/lib/texmf/fonts//tfm", the answer is yes. In practice, ls-R is only needed for lengthy subdirectory comparisons, but there's no gain to checking PATH_ELT to see if it is a subdir match, since the only way to do that is to do a string search in it, which is all we do anyway. */ static bool elt_in_db (const std::string& db_dir, const std::string& path_elt) { bool found = false; size_t db_dir_len = db_dir.length (); size_t path_elt_len = path_elt.length (); size_t i = 0; while (! found && db_dir[i] == path_elt[i]) { i++; /* If we've matched the entire db directory, it's good. */ if (i == db_dir_len) found = true; /* If we've reached the end of PATH_ELT, but not the end of the db directory, it's no good. */ else if (i == path_elt_len) break; } return found; } /* Avoid doing anything if this PATH_ELT is irrelevant to the databases. */ /* Return list of matches for NAME in the ls-R file matching PATH_ELT. If ALL is set, return (null-terminated list) of all matches, else just the first. If no matches, return a pointer to an empty list. If no databases can be read, or PATH_ELT is not in any of the databases, return NULL. */ static string_vector kpse_db_search (const std::string& name_arg, const std::string& orig_path_elt, bool all) { bool done; string_vector ret; string_vector aliases; bool relevant = false; std::string name = name_arg; /* If we failed to build the database (or if this is the recursive call to build the db path), quit. */ if (! db.buckets) return ret; /* When tex-glyph.c calls us looking for, e.g., dpi600/cmr10.pk, we won't find it unless we change NAME to just `cmr10.pk' and append `/dpi600' to PATH_ELT. We are justified in using a literal `/' here, since that's what tex-glyph.c unconditionally uses in DPI_BITMAP_SPEC. But don't do anything if the / begins NAME; that should never happen. */ std::string path_elt; size_t last_slash = name.rfind ('/'); if (last_slash != std::string::npos && last_slash != 0) { std::string dir_part = name.substr (0, last_slash); name = name.substr (last_slash + 1); } else path_elt = orig_path_elt; /* Don't bother doing any lookups if this `path_elt' isn't covered by any of database directories. We do this not so much because the extra couple of hash lookups matter -- they don't -- but rather because we want to return NULL in this case, so path_search can know to do a disk search. */ for (int e = 0; ! relevant && e < db_dir_list.length (); e++) relevant = elt_in_db (db_dir_list[e], path_elt); if (! relevant) return ret; /* If we have aliases for this name, use them. */ if (alias_db.buckets) aliases = hash_lookup (alias_db, name); /* Push aliases up by one and insert the original name at the front. */ int len = aliases.length (); aliases.resize (len+1); for (int i = len; i > 0; i--) aliases[i] = aliases[i - 1]; aliases[0] = name; done = false; len = aliases.length (); for (int i = 0; i < len && !done; i++) { std::string atry = aliases[i]; /* We have an ls-R db. Look up `atry'. */ string_vector db_dirs = hash_lookup (db, atry); /* For each filename found, see if it matches the path element. For example, if we have .../cx/cmr10.300pk and .../ricoh/cmr10.300pk, and the path looks like .../cx, we don't want the ricoh file. */ int db_dirs_len = db_dirs.length (); for (int j = 0; j < db_dirs_len && !done; j++) { std::string db_file = db_dirs[j] + atry; bool matched = match (db_file, path_elt); #ifdef KPSE_DEBUG if (KPSE_DEBUG_P (KPSE_DEBUG_SEARCH)) DEBUGF3 ("db:match (%s,%s) = %d\n", db_file.c_str (), path_elt.c_str (), matched); #endif /* We got a hit in the database. Now see if the file actually exists, possibly under an alias. */ if (matched) { std::string found; std::string tmp = kpse_readable_file (db_file); if (! tmp.empty ()) found = db_file; else { /* The hit in the DB doesn't exist in disk. Now try all its aliases. For example, suppose we have a hierarchy on CD, thus `mf.bas', but ls-R contains `mf.base'. Find it anyway. Could probably work around this with aliases, but this is pretty easy and shouldn't hurt. The upshot is that if one of the aliases actually exists, we use that. */ int aliases_len = aliases.length (); for (int k = 1; k < aliases_len && found.empty (); k++) { std::string aatry = db_dirs[j] + aliases[k]; tmp = kpse_readable_file (aatry); if (! tmp.empty ()) found = aatry; } } /* If we have a real file, add it to the list, maybe done. */ if (! found.empty ()) { ret.append (found); if (! (all || found.empty ())) done = true; } } } } return ret; } /* Expand extra colons. */ /* Check for leading colon first, then trailing, then doubled, since that is fastest. Usually it will be leading or trailing. */ /* Replace a leading or trailing or doubled : in PATH with DFLT. If no extra colons, return PATH. Only one extra colon is replaced. DFLT may not be NULL. */ static std::string kpse_expand_default (const std::string& path, const std::string& fallback) { std::string expansion; size_t path_len = path.length (); if (path_len == 0) expansion = fallback; /* Solitary or leading :? */ else if (IS_ENV_SEP (path[0])) { expansion = path_len == 1 ? fallback : fallback + path; } /* Sorry about the assignment in the middle of the expression, but conventions were made to be flouted and all that. I don't see the point of calling strlen twice or complicating the logic just to avoid the assignment (especially now that I've pointed it out at such great length). */ else if (IS_ENV_SEP (path[path_len-1])) expansion = path + fallback; /* OK, not leading or trailing. Check for doubled. */ else { /* What we'll return if we find none. */ expansion = path; for (size_t i = 0; i < path_len; i++) { if (i + 1 < path_len && IS_ENV_SEP (path[i]) && IS_ENV_SEP (path[i+1])) { /* We have a doubled colon. */ /* Copy stuff up to and including the first colon. */ /* Copy in FALLBACK, and then the rest of PATH. */ expansion = path.substr (0, i+1) + fallback + path.substr (i+1); break; } } } return expansion; } /* Translate a path element to its corresponding director{y,ies}. */ /* To avoid giving prototypes for all the routines and then their real definitions, we give all the subroutines first. The entry point is the last routine in the file. */ /* Make a copy of DIR (unless it's null) and save it in L. Ensure that DIR ends with a DIR_SEP for the benefit of later searches. */ static void dir_list_add (str_llist_type *l, const std::string& dir) { char last_char = dir[dir.length () - 1]; std::string saved_dir = dir; if (! (IS_DIR_SEP (last_char) || IS_DEVICE_SEP (last_char))) saved_dir += DIR_SEP_STRING; str_llist_add (l, saved_dir); } /* Return true if FN is a directory or a symlink to a directory, false if not. */ static bool dir_p (const std::string& fn) { #ifdef WIN32 unsigned int fa = GetFileAttributes (fn.c_str ()); return (fa != 0xFFFFFFFF && (fa & FILE_ATTRIBUTE_DIRECTORY)); #else struct stat stats; return stat (fn.c_str (), &stats) == 0 && S_ISDIR (stats.st_mode); #endif } /* If DIR is a directory, add it to the list L. */ static void checked_dir_list_add (str_llist_type *l, const std::string& dir) { if (dir_p (dir)) dir_list_add (l, dir); } /* The cache. Typically, several paths have the same element; for example, /usr/local/lib/texmf/fonts//. We don't want to compute the expansion of such a thing more than once. Even though we also cache the dir_links call, that's not enough -- without this path element caching as well, the execution time doubles. */ struct cache_entry { std::string key; str_llist_type *value; }; static cache_entry *the_cache = 0; static unsigned cache_length = 0; /* Associate KEY with VALUE. We implement the cache as a simple linear list, since it's unlikely to ever be more than a dozen or so elements long. We don't bother to check here if PATH has already been saved; we always add it to our list. We copy KEY but not VALUE; not sure that's right, but it seems to be all that's needed. */ static void cache (const std::string key, str_llist_type *value) { cache_entry *new_cache = new cache_entry [cache_length+1]; for (unsigned i = 0; i < cache_length; i++) { new_cache[i].key = the_cache[i].key; new_cache[i].value = the_cache[i].value; } delete [] the_cache; the_cache = new_cache; the_cache[cache_length].key = key; the_cache[cache_length].value = value; cache_length++; } /* To retrieve, just check the list in order. */ static str_llist_type * cached (const std::string& key) { unsigned p; for (p = 0; p < cache_length; p++) { if (key == the_cache[p].key) return the_cache[p].value; } return 0; } /* Handle the magic path constructs. */ /* Declare recursively called routine. */ static void expand_elt (str_llist_type *, const std::string&, unsigned); /* POST is a pointer into the original element (which may no longer be ELT) to just after the doubled DIR_SEP, perhaps to the null. Append subdirectories of ELT (up to ELT_LENGTH, which must be a /) to STR_LIST_PTR. */ #ifdef WIN32 /* Shared across recursive calls, it acts like a stack. */ static std::string dirname; #else /* WIN32 */ /* Return -1 if FN isn't a directory, else its number of links. Duplicate the call to stat; no need to incur overhead of a function call for that little bit of cleanliness. */ static int dir_links (const std::string& fn) { std::map<std::string, long> link_table; long ret; if (link_table.find (fn) != link_table.end ()) ret = link_table[fn]; else { struct stat stats; ret = stat (fn.c_str (), &stats) == 0 && S_ISDIR (stats.st_mode) ? stats.st_nlink : static_cast<unsigned> (-1); link_table[fn] = ret; #ifdef KPSE_DEBUG if (KPSE_DEBUG_P (KPSE_DEBUG_STAT)) DEBUGF2 ("dir_links (%s) => %ld\n", fn.c_str (), ret); #endif } return ret; } #endif /* WIN32 */ static void do_subdir (str_llist_type *str_list_ptr, const std::string& elt, unsigned elt_length, const std::string& post) { #ifdef WIN32 WIN32_FIND_DATA find_file_data; HANDLE hnd; int proceed; #else DIR *dir; struct dirent *e; #endif /* not WIN32 */ std::string name = elt.substr (0, elt_length); assert (IS_DIR_SEP (elt[elt_length - 1]) || IS_DEVICE_SEP (elt[elt_length - 1])); #if defined (WIN32) dirname = name + "/*.*"; /* "*.*" or "*" -- seems equivalent. */ hnd = FindFirstFile (dirname.c_str (), &find_file_data); if (hnd == INVALID_HANDLE_VALUE) return; /* Include top level before subdirectories, if nothing to match. */ if (post.empty ()) dir_list_add (str_list_ptr, name); else { /* If we do have something to match, see if it exists. For example, POST might be `pk/ljfour', and they might have a directory `$TEXMF/fonts/pk/ljfour' that we should find. */ name += post; expand_elt (str_list_ptr, name, elt_length); name.resize (elt_length); } proceed = 1; while (proceed) { if (find_file_data.cFileName[0] != '.') { /* Construct the potential subdirectory name. */ name += find_file_data.cFileName; if (find_file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { /* It's a directory, so append the separator. */ name += DIR_SEP_STRING; unsigned potential_len = name.length (); do_subdir (str_list_ptr, name, potential_len, post); } name.resize (elt_length); } proceed = FindNextFile (hnd, &find_file_data); } FindClose (hnd); #else /* not WIN32 */ /* If we can't open it, quit. */ dir = opendir (name.c_str ()); if (! dir) return; /* Include top level before subdirectories, if nothing to match. */ if (post.empty ()) dir_list_add (str_list_ptr, name); else { /* If we do have something to match, see if it exists. For example, POST might be `pk/ljfour', and they might have a directory `$TEXMF/fonts/pk/ljfour' that we should find. */ name += post; expand_elt (str_list_ptr, name, elt_length); name.resize (elt_length); } while ((e = readdir (dir))) { /* If it begins with a `.', never mind. (This allows ``hidden'' directories that the algorithm won't find.) */ if (e->d_name[0] != '.') { int links; /* Construct the potential subdirectory name. */ name += e->d_name; /* If we can't stat it, or if it isn't a directory, continue. */ links = dir_links (name); if (links >= 0) { /* It's a directory, so append the separator. */ name += DIR_SEP_STRING; unsigned potential_len = name.length (); /* Should we recurse? To see if the subdirectory is a leaf, check if it has two links (one for . and one for ..). This means that symbolic links to directories do not affect the leaf-ness. This is arguably wrong, but the only alternative I know of is to stat every entry in the directory, and that is unacceptably slow. The #ifdef here makes all this configurable at compile-time, so that if we're using VMS directories or some such, we can still find subdirectories, even if it is much slower. */ #ifdef ST_NLINK_TRICK if (links != 2) #endif /* not ST_NLINK_TRICK */ /* All criteria are met; find subdirectories. */ do_subdir (str_list_ptr, name, potential_len, post); #ifdef ST_NLINK_TRICK else if (post.empty ()) /* Nothing to match, no recursive subdirectories to look for: we're done with this branch. Add it. */ dir_list_add (str_list_ptr, name); #endif } /* Remove the directory entry we just checked from `name'. */ name.resize (elt_length); } } xclosedir (dir); #endif /* not WIN32 */ } /* Assume ELT is non-empty and non-NULL. Return list of corresponding directories (with no terminating NULL entry) in STR_LIST_PTR. Start looking for magic constructs at START. */ static void expand_elt (str_llist_type *str_list_ptr, const std::string& elt, unsigned /* start */) { #if 0 // We don't want magic constructs. size_t elt_len = elt.length (); size_t dir = start; while (dir < elt_len) { if (IS_DIR_SEP (elt[dir])) { /* If two or more consecutive /'s, find subdirectories. */ if (++dir < elt_len && IS_DIR_SEP (elt[dir])) { size_t i = dir; while (i < elt_len && IS_DIR_SEP (elt[i])) i++; std::string post = elt.substr (i); do_subdir (str_list_ptr, elt, dir, post); return; } /* No special stuff at this slash. Keep going. */ } else dir++; } #endif /* When we reach the end of ELT, it will be a normal filename. */ checked_dir_list_add (str_list_ptr, elt); } /* Here is the entry point. Returns directory list for ELT. */ /* Given a path element ELT, return a pointer to a NULL-terminated list of the corresponding (existing) directory or directories, with trailing slashes, or NULL. If ELT is the empty string, check the current working directory. It's up to the caller to expand ELT. This is because this routine is most likely only useful to be called from `kpse_path_search', which has already assumed expansion has been done. */ static str_llist_type * kpse_element_dirs (const std::string& elt) { str_llist_type *ret; /* If given nothing, return nothing. */ if (elt.empty ()) return 0; /* If we've already cached the answer for ELT, return it. */ ret = cached (elt); if (ret) return ret; /* We're going to have a real directory list to return. */ ret = new str_llist_type; *ret = 0; /* We handle the hard case in a subroutine. */ expand_elt (ret, elt, 0); /* Remember the directory list we just found, in case future calls are made with the same ELT. */ cache (elt, ret); #ifdef KPSE_DEBUG if (KPSE_DEBUG_P (KPSE_DEBUG_EXPAND)) { DEBUGF1 ("path element %s =>", elt.c_str ()); if (ret) { str_llist_elt_type *e; for (e = *ret; e; e = STR_LLIST_NEXT (*e)) fprintf (stderr, " %s", (STR_LLIST (*e)).c_str ()); } putc ('\n', stderr); fflush (stderr); } #endif /* KPSE_DEBUG */ return ret; } #ifndef WIN32 void xclosedir (DIR *d) { #ifdef CLOSEDIR_VOID closedir (d); #else int ret = closedir (d); if (ret != 0) FATAL ("closedir failed"); #endif } #endif /* Help the user discover what's going on. */ #ifdef KPSE_DEBUG /* If the real definitions of fopen or fclose are macros, we lose -- the #undef won't restore them. */ static FILE * fopen (const char *filename, const char *mode) { #undef fopen FILE *ret = fopen (filename, mode); if (KPSE_DEBUG_P (KPSE_DEBUG_FOPEN)) DEBUGF3 ("fopen (%s, %s) => 0x%lx\n", filename, mode, reinterpret_cast<unsigned long> (ret)); return ret; } #endif /* Implementation of a linked list of strings. */ /* Add the new string STR to the end of the list L. */ static void str_llist_add (str_llist_type *l, const std::string& str) { str_llist_elt_type *e; str_llist_elt_type *new_elt = new str_llist_elt_type; /* The new element will be at the end of the list. */ STR_LLIST (*new_elt) = str; STR_LLIST_MOVED (*new_elt) = 0; STR_LLIST_NEXT (*new_elt) = 0; /* Find the current end of the list. */ for (e = *l; e && STR_LLIST_NEXT (*e); e = STR_LLIST_NEXT (*e)) ; if (! e) *l = new_elt; else STR_LLIST_NEXT (*e) = new_elt; } /* Move an element towards the top. The idea is that when a file is found in a given directory, later files will likely be in that same directory, and looking for the file in all the directories in between is thus a waste. */ static void str_llist_float (str_llist_type *l, str_llist_elt_type *mover) { str_llist_elt_type *last_moved, *unmoved; /* If we've already moved this element, never mind. */ if (STR_LLIST_MOVED (*mover)) return; /* Find the first unmoved element (to insert before). We're guaranteed this will terminate, since MOVER itself is currently unmoved, and it must be in L (by hypothesis). */ for (last_moved = 0, unmoved = *l; STR_LLIST_MOVED (*unmoved); last_moved = unmoved, unmoved = STR_LLIST_NEXT (*unmoved)) ; /* If we are the first unmoved element, nothing to relink. */ if (unmoved != mover) { /* Remember `mover's current successor, so we can relink `mover's predecessor to it. */ str_llist_elt_type *before_mover; str_llist_elt_type *after_mover = STR_LLIST_NEXT (*mover); /* Find `mover's predecessor. */ for (before_mover = unmoved; STR_LLIST_NEXT (*before_mover) != mover; before_mover = STR_LLIST_NEXT (*before_mover)) ; /* `before_mover' now links to `after_mover'. */ STR_LLIST_NEXT (*before_mover) = after_mover; /* Insert `mover' before `unmoved' and after `last_moved' (or at the head of the list). */ STR_LLIST_NEXT (*mover) = unmoved; if (! last_moved) *l = mover; else STR_LLIST_NEXT (*last_moved) = mover; } /* We've moved it. */ STR_LLIST_MOVED (*mover) = 1; } /* Variable expansion. */ /* We have to keep track of variables being expanded, otherwise constructs like TEXINPUTS = $TEXINPUTS result in an infinite loop. (Or indirectly recursive variables, etc.) Our simple solution is to add to a list each time an expansion is started, and check the list before expanding. */ static std::map <std::string, bool> expansions; static void expanding (const std::string& var, bool xp) { expansions[var] = xp; } /* Return whether VAR is currently being expanding. */ static bool expanding_p (const std::string& var) { return (expansions.find (var) != expansions.end ()) ? expansions[var] : false; } /* Append the result of value of `var' to EXPANSION, where `var' begins at START and ends at END. If `var' is not set, do not complain. This is a subroutine for the more complicated expansion function. */ static void expand (std::string &expansion, const std::string& var) { if (expanding_p (var)) { (*current_liboctave_warning_handler) ("kpathsea: variable `%s' references itself (eventually)", var.c_str ()); } else { /* Check for an environment variable. */ std::string value = octave_env::getenv (var); if (! value.empty ()) { expanding (var, true); std::string tmp = kpse_var_expand (value); expanding (var, false); expansion += tmp; } } } /* Can't think of when it would be useful to change these (and the diagnostic messages assume them), but ... */ #ifndef IS_VAR_START /* starts all variable references */ #define IS_VAR_START(c) ((c) == '$') #endif #ifndef IS_VAR_CHAR /* variable name constituent */ #define IS_VAR_CHAR(c) (isalnum (c) || (c) == '_') #endif #ifndef IS_VAR_BEGIN_DELIMITER /* start delimited variable name (after $) */ #define IS_VAR_BEGIN_DELIMITER(c) ((c) == '{') #endif #ifndef IS_VAR_END_DELIMITER #define IS_VAR_END_DELIMITER(c) ((c) == '}') #endif /* Maybe we should support some or all of the various shell ${...} constructs, especially ${var-value}. */ static std::string kpse_var_expand (const std::string& src) { std::string expansion; size_t src_len = src.length (); /* Copy everything but variable constructs. */ for (size_t i = 0; i < src_len; i++) { if (IS_VAR_START (src[i])) { i++; /* Three cases: `$VAR', `${VAR}', `$<anything-else>'. */ if (IS_VAR_CHAR (src[i])) { /* $V: collect name constituents, then expand. */ size_t var_end = i; do { var_end++; } while (IS_VAR_CHAR (src[var_end])); var_end--; /* had to go one past */ expand (expansion, src.substr (i, var_end - i + 1)); i = var_end; } else if (IS_VAR_BEGIN_DELIMITER (src[i])) { /* ${: scan ahead for matching delimiter, then expand. */ size_t var_end = ++i; while (var_end < src_len && !IS_VAR_END_DELIMITER (src[var_end])) var_end++; if (var_end == src_len) { (*current_liboctave_warning_handler) ("%s: No matching } for ${", src.c_str ()); i = var_end - 1; /* will incr to eos at top of loop */ } else { expand (expansion, src.substr (i, var_end - i)); i = var_end; /* will incr past } at top of loop*/ } } else { /* $<something-else>: error. */ (*current_liboctave_warning_handler) ("%s: Unrecognized variable construct `$%c'", src.c_str (), src[i]); /* Just ignore those chars and keep going. */ } } else expansion += src[i]; } return expansion; } /* ;;; Local Variables: *** ;;; mode: C++ *** ;;; End: *** */
aJanker/TypeChef-LinuxAnalysis
linux26333/systems/redhat/usr/include/octave-3.2.4/octave/kpse.cc
C++
gpl-3.0
72,347
#!/bin/bash if [ -z "$STOQS_HOME" ]; then echo "Set STOQS_HOME variable first, e.g. STOQS_HOME=/opt/stoqsgit" exit 1 fi if [ -z "$DATABASE_URL" ]; then echo "Set DATABASE_URL variable first" exit 1 fi cd "$STOQS_HOME/stoqs/loaders/CANON/realtime" post='--post' #post='' debug='' ##debug='--debug' database='stoqs_lrauv_jun2019' urlbase='http://dods.mbari.org/thredds/catalog/LRAUV' declare -a searchstr=("/realtime/sbdlogs/2019/.*shore.nc4$" "/realtime/cell-logs/.*Priority.nc4$" "/realtime/cell-logs/.*Normal.nc4$") ##declare -a searchstr=("/realtime/cell-logs/.*Normal.nc4$") ##declare -a searchstr=("/realtime/sbdlogs/2019/.*shore.nc4$") declare -a platforms=("whoidhs") pos=$(( ${#searchstr[*]} - 1 )) last=${searchstr[$pos]} for platform in "${platforms[@]}" do for search in "${searchstr[@]}" do # only plot the 24 hour plot in the last search group, otherwise this updates the timestamp on the files stored in the odss-data-repo per every search string if [[ $search == $last ]] then latest24plot='--latest24hr' else latest24plot='' fi # get everything before the last / - this is used as the directory base for saving the interpolated .nc files directory=`echo ${search} | sed 's:/[^/]*$::'` python monitorLrauv.py --start '20190602T000000' --end '20190620T000000' -d 'WHOIDHS Santa Barbara data - June 2019' --productDir '/mbari/ODSS/data/other/routine/Products/LRAUV' \ --contourDir '/mbari/LRAUV/stoqs' --contourUrl 'http://dods.mbari.org/opendap/data/lrauv/stoqs/' -o /mbari/LRAUV/${platform}/${directory}/ -i /mbari/LRAUV/${platform}/${directory} \ -u ${urlbase}/${platform}/${search} -b ${database} -c 'WHOIDHS Santa Barbara data - June 2019' --append --autoscale \ --iparm depth \ --parms depth concentration_of_chromophoric_dissolved_organic_matter_in_sea_water \ mass_concentration_of_chlorophyll_in_sea_water \ --plotparms depth concentration_of_chromophoric_dissolved_organic_matter_in_sea_water \ mass_concentration_of_chlorophyll_in_sea_water ##--plotgroup \ ##chlorophyll ##$latest24plot $post $debug > /tmp/monitorLrauv${platform}.out 2>&1 done done
stoqs/stoqs
stoqs/loaders/CANON/realtime/monitorLrauv_jun2019.sh
Shell
gpl-3.0
2,226
import { CharacterManager, Notifications } from 'charactersheet/utilities'; import { AppearanceViewModel } from 'charactersheet/viewmodels/character/appearance'; import { CharacterAppearance } from 'charactersheet/models/character'; import { MockCharacterManager } from '../mocks'; import { PersistenceService } from 'charactersheet/services/common/persistence_service'; import Should from 'should'; import simple from 'simple-mock'; describe('Appearance', function() { //Clean up after each test. afterEach(function() { simple.restore(); }); describe('Load', function() { it('should load values from database', function() { var app = new CharacterAppearance(); app.height('6ft'); simple.mock(CharacterManager, 'activeCharacter').callFn(MockCharacterManager.activeCharacter); simple.mock(PersistenceService, 'findBy').returnWith([app]); var a = new AppearanceViewModel(); app.height('6ft'); a.load(); a.appearance().height().should.equal('6ft'); }); it('should not load values from database', function() { simple.mock(CharacterManager, 'activeCharacter').callFn(MockCharacterManager.activeCharacter); simple.mock(PersistenceService, 'findBy').returnWith([]); var a = new AppearanceViewModel(); a.load(); a.appearance().characterId().should.equal('12345'); }); }); describe('Clear', function() { it('should clear the values of the model', function() { var a = new AppearanceViewModel(); var notifySpy = simple.mock(a.appearance(), 'clear'); a.clear(); notifySpy.called.should.equal(true); }); }); });
Sonictherocketman/charactersheet
test/viewmodels/test_appearance.js
JavaScript
gpl-3.0
1,805
/* radare - LGPL - Copyright 2008-2021 - pancake */ #include "r_io.h" #include "r_lib.h" #include <stdio.h> #include <stdlib.h> #include "../io_memory.h" static bool __check(RIO *io, const char *pathname, bool many) { return (!strncmp (pathname, "http://", 7)); } static RIODesc *__open(RIO *io, const char *pathname, int rw, int mode) { if (__check (io, pathname, 0)) { int rlen, code; RIOMalloc *mal = R_NEW0 (RIOMalloc); if (!mal) { return NULL; } mal->offset = 0; mal->buf = (ut8*)r_socket_http_get (pathname, &code, &rlen); if (mal->buf && rlen > 0) { mal->size = rlen; return r_io_desc_new (io, &r_io_plugin_malloc, pathname, R_PERM_RW | rw, mode, mal); } eprintf ("No HTTP response\n"); free (mal); } return NULL; } RIOPlugin r_io_plugin_http = { .name = "http", .desc = "Make http get requests", .uris = "http://", .license = "LGPL3", .open = __open, .close = io_memory_close, .read = io_memory_read, .check = __check, .seek = io_memory_lseek, .write = io_memory_write, }; #ifndef R2_PLUGIN_INCORE R_API RLibStruct radare_plugin = { .type = R_LIB_TYPE_IO, .data = &r_io_plugin_http, .version = R2_VERSION }; #endif
jjdredd/radare2
libr/io/p/io_http.c
C
gpl-3.0
1,174
/************************************************************************ ** ** Copyright (C) 2015-2021 Kevin B. Hendricks, Stratford Ontario Canada ** Copyright (C) 2011 John Schember <[email protected]> ** ** This file is part of Sigil. ** ** Sigil 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. ** ** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>. ** *************************************************************************/ #include "LanguageWidget.h" #include "Misc/SettingsStore.h" #include "Misc/Language.h" #include "Misc/UILanguage.h" #include <QString> #include <QStringList> LanguageWidget::LanguageWidget() { ui.setupUi(this); // Metadata language combobox foreach(QString lang, Language::instance()->GetSortedPrimaryLanguageNames()) { ui.cbMetadataLanguage->addItem(lang); } // UI language combobox - smaller subset of available languages QStringList ui_language_names; foreach(QString language_code, UILanguage::GetUILanguages()) { // Convert standard language codes to those used for translations. QString std_language_code = language_code; std_language_code.replace("_", "-"); QString language_name = Language::instance()->GetLanguageName(std_language_code); if (language_name.isEmpty()) { language_name = language_code; } ui_language_names.append(language_name); } ui_language_names.sort(); foreach(QString ui_language_name, ui_language_names) { ui.cbUILanguage->addItem(ui_language_name); } readSettings(); } PreferencesWidget::ResultActions LanguageWidget::saveSettings() { PreferencesWidget::ResultActions results = PreferencesWidget::ResultAction_None; SettingsStore settings; settings.setDefaultMetadataLang(Language::instance()->GetLanguageCode(ui.cbMetadataLanguage->currentText())); settings.setUILanguage(Language::instance()->GetLanguageCode(ui.cbUILanguage->currentText()).replace("-", "_")); if (ui.cbUILanguage->currentText() != m_UILanguage) { results = results | PreferencesWidget::ResultAction_RestartSigil; } results = results & PreferencesWidget::ResultAction_Mask; return results; } void LanguageWidget::readSettings() { SettingsStore settings; // Metadata Language int index = ui.cbMetadataLanguage->findText(Language::instance()->GetLanguageName(settings.defaultMetadataLang())); if (index == -1) { index = ui.cbMetadataLanguage->findText(Language::instance()->GetLanguageName("en")); if (index == -1) { index = 0; } } ui.cbMetadataLanguage->setCurrentIndex(index); // UI Language QString langcode = settings.uiLanguage().replace("_","-"); index = ui.cbUILanguage->findText(Language::instance()->GetLanguageName(langcode)); // try again with just part of language code that exists before the "-" if (index == -1) { langcode = langcode.split("-").at(0); index = ui.cbUILanguage->findText(Language::instance()->GetLanguageName(langcode)); } if (index == -1) { index = ui.cbUILanguage->findText(Language::instance()->GetLanguageName("en")); if (index == -1) { index = 0; } } ui.cbUILanguage->setCurrentIndex(index); m_UILanguage = ui.cbUILanguage->currentText(); }
mihailim/Sigil
src/Dialogs/PreferenceWidgets/LanguageWidget.cpp
C++
gpl-3.0
3,878
<?php namespace FormaLibre\PresenceBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration as EXT; use JMS\DiExtraBundle\Annotation as DI; use JMS\SecurityExtraBundle\Annotation as SEC; use Claroline\CoreBundle\Persistence\ObjectManager; use Doctrine\ORM\EntityManager; use Symfony\Component\HttpFoundation\Request; use Claroline\CoreBundle\Entity\Group; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\RouterInterface; use Claroline\CoreBundle\Library\Configuration\PlatformConfigurationHandler; use FormaLibre\PresenceBundle\Entity\PresenceRights; use FormaLibre\PresenceBundle\Entity\Period; use FormaLibre\PresenceBundle\Entity\Presence; use FormaLibre\PresenceBundle\Entity\Status; use FormaLibre\PresenceBundle\Entity\SchoolYear; use Claroline\CoreBundle\Entity\User; use FormaLibre\PresenceBundle\Manager\PresenceManager; /** * @DI\Tag("security.secure_service") * @SEC\PreAuthorize("canOpenAdminTool('formalibre_presence_admin_tool')") */ class AdminPresenceController extends Controller { private $om; private $em; private $presenceRepo; private $periodRepo; private $groupRepo; private $userRepo; private $schoolYearRepo; private $router; private $config; private $presenceManager; /** * @DI\InjectParams({ * "om" = @DI\Inject("claroline.persistence.object_manager"), * "em" = @DI\Inject("doctrine.orm.entity_manager"), * "router" = @DI\Inject("router"), * "config" = @DI\Inject("claroline.config.platform_config_handler"), * "presenceManager" = @DI\Inject("formalibre.manager.presence_manager") * }) */ public function __construct( ObjectManager $om, EntityManager $em, RouterInterface $router, PlatformConfigurationHandler $config, PresenceManager $presenceManager ) { $this->router = $router; $this->om = $om; $this->em = $em; $this->userRepo = $om->getRepository('ClarolineCoreBundle:User'); $this->periodRepo = $om->getRepository('FormaLibrePresenceBundle:Period'); $this->groupRepo = $om->getRepository('ClarolineCoreBundle:Group'); $this->userRepo = $om->getRepository('ClarolineCoreBundle:User'); $this->statuRepo = $om->getRepository('FormaLibrePresenceBundle:Status'); $this->schoolYearRepo = $om->getRepository('FormaLibrePresenceBundle:SchoolYear'); $this->presenceRepo = $om->getRepository('FormaLibrePresenceBundle:Presence'); $this->config = $config; $this->presenceManager = $presenceManager; } /** * @EXT\Route( * "/admin/presence/tool/index", * name="formalibre_presence_admin_tool_index", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * @EXT\Template() */ public function adminToolIndexAction() { $rightsValue = array(); $rightsForArray = $this->presenceManager->getAllPresenceRights(); foreach ($rightsForArray as $oneRightForArray) { $mask = $oneRightForArray->getMask(); $oneValue = array(); $oneValue['right'] = $oneRightForArray; $oneValue[PresenceRights::PERSONAL_ARCHIVES] = (PresenceRights::PERSONAL_ARCHIVES & $mask) === PresenceRights::PERSONAL_ARCHIVES; $oneValue[PresenceRights::CHECK_PRESENCES] = (PresenceRights::CHECK_PRESENCES & $mask) === PresenceRights::CHECK_PRESENCES; $oneValue[PresenceRights::READING_ARCHIVES] = (PresenceRights::READING_ARCHIVES & $mask) === PresenceRights::READING_ARCHIVES; $oneValue[PresenceRights::EDIT_ARCHIVES] = (PresenceRights::EDIT_ARCHIVES & $mask) === PresenceRights::EDIT_ARCHIVES; $rightsValue[] = $oneValue; } $rightNameId = array(); $rightNameId[] = PresenceRights::PERSONAL_ARCHIVES; $rightNameId[] = PresenceRights::CHECK_PRESENCES; $rightNameId[] = PresenceRights::READING_ARCHIVES; $rightNameId[] = PresenceRights::EDIT_ARCHIVES; $rightName = array(); $rightName[PresenceRights::PERSONAL_ARCHIVES] = 'Voir ses archives'; $rightName[PresenceRights::CHECK_PRESENCES] = 'Relever les présences'; $rightName[PresenceRights::READING_ARCHIVES] = 'Consulter les archives'; $rightName[PresenceRights::EDIT_ARCHIVES] = 'Editer les archives'; $listStatus = $this->statuRepo->findAll(); $NewStatusForm = $this->createFormBuilder() ->add('name', 'text') ->add('color', 'text') ->add('principalStatus', 'checkbox', array( 'required' => false, ) ) ->add('valider', 'submit', array( 'label' => 'Ajouter', )) ->getForm(); $request = $this->getRequest(); if ($request->getMethod() === 'POST') { $NewStatusForm->handleRequest($request); $name = $NewStatusForm->get('name')->getData(); $color = $NewStatusForm->get('color')->getData(); $principal = $NewStatusForm->get('principalStatus')->getData(); $actualStatus = new Status(); $actualStatus->setStatusName($name); $actualStatus->setStatusColor($color); $actualStatus->setStatusByDefault($principal); $this->em->persist($actualStatus); $this->em->flush(); return $this->redirect($this->generateUrl('formalibre_presence_admin_tool_index')); } $ActualSchoolYear = $this->schoolYearRepo->findOneBySchoolYearActual(1); $AllSchoolYear = $this->schoolYearRepo->findAll(); $NewSchoolYearForm = $this->createFormBuilder() ->add('name', 'text') ->add('beginDate', 'text') ->add('endDate', 'text') ->add('beginHour', 'text') ->add('endHour', 'text') ->add('actual', 'checkbox', array( 'required' => false, ) ) ->add('valider2', 'submit', array( 'label' => 'Ajouter', )) ->getForm(); return array('rightsForArray' => $rightsForArray, 'rightsValue' => $rightsValue, 'rightNameId' => $rightNameId, 'rightName' => $rightName, 'NewStatusForm' => $NewStatusForm->createView(), 'NewSchoolYearForm' => $NewSchoolYearForm->createView(), 'listStatus' => $listStatus, 'allSchoolYear' => $AllSchoolYear, 'actualSchoolYear' => $ActualSchoolYear, ); } /** * @EXT\Route( * "/admin/presence/addSchoolYear/index", * name="formalibre_presence_admin_add_school_year", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * @EXT\Template() */ public function adminAddSchoolYearAction() { $NewSchoolYearForm = $this->createFormBuilder() ->add('name', 'text') ->add('beginDate', 'text') ->add('endDate', 'text') ->add('beginHour', 'text') ->add('endHour', 'text') ->add('actual', 'checkbox', array( 'required' => false, ) ) ->add('valider2', 'submit', array( 'label' => 'Ajouter', )) ->getForm(); $request = $this->getRequest(); if ($request->getMethod() === 'POST') { $NewSchoolYearForm->handleRequest($request); $name = $NewSchoolYearForm->get('name')->getData(); $beginDate = $NewSchoolYearForm->get('beginDate')->getData(); $endDate = $NewSchoolYearForm->get('endDate')->getData(); $beginHour = $NewSchoolYearForm->get('beginHour')->getData(); $endHour = $NewSchoolYearForm->get('endHour')->getData(); $actual = $NewSchoolYearForm->get('actual')->getData(); $beginDateFormat = \DateTime::createFromFormat('d-m-Y', $beginDate); $endDateFormat = \DateTime::createFromFormat('d-m-Y', $endDate); $beginHourFormat = \DateTime::createFromFormat('H:i', $beginHour); $endHourFormat = \DateTime::createFromFormat('H:i', $endHour); if ($actual) { $AllSchoolYear = $this->schoolYearRepo->findAll(); foreach ($AllSchoolYear as $oneSchoolYear) { $oneSchoolYear->setSchoolYearActual(false); } } $actualSchoolYear = new SchoolYear(); $actualSchoolYear->setSchoolYearName($name); $actualSchoolYear->setSchoolYearBegin($beginDateFormat); $actualSchoolYear->setSchoolYearEnd($endDateFormat); $actualSchoolYear->setSchoolDayBeginHour($beginHourFormat); $actualSchoolYear->setSchoolDayEndHour($endHourFormat); $actualSchoolYear->setSchoolYearActual($actual); $this->em->persist($actualSchoolYear); $this->em->flush(); } return $this->redirect($this->generateUrl('formalibre_presence_admin_tool_index')); } /** * @EXT\Route( * "/presence/schoolYear_modif/id/{theSchoolYear}", * name="formalibre_school_year_modif", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user * @EXT\Template() */ public function SchoolYearModifAction(SchoolYear $theSchoolYear) { $ModifSchoolYearForm = $this->createFormBuilder() ->add('nameModifSchoolYear', 'text') ->add('beginDateModifSchoolYear', 'text') ->add('endDateModifSchoolYear', 'text') ->add('beginHourModifSchoolYear', 'text') ->add('endHourModifSchoolYear', 'text') ->add('actualModifSchoolYear', 'checkbox', array( 'required' => false, ) ) ->add('validerModifSchoolYear', 'submit', array( 'label' => 'Ajouter', )) ->getForm(); $request = $this->getRequest(); if ($request->getMethod() === 'POST') { $ModifSchoolYearForm->handleRequest($request); $modifName = $ModifSchoolYearForm->get('nameModifSchoolYear')->getData(); $modifBeginDate = $ModifSchoolYearForm->get('beginDateModifSchoolYear')->getData(); $modifEndDate = $ModifSchoolYearForm->get('endDateModifSchoolYear')->getData(); $modifBeginHour = $ModifSchoolYearForm->get('beginHourModifSchoolYear')->getData(); $modifEndHour = $ModifSchoolYearForm->get('endHourModifSchoolYear')->getData(); $modifActual = $ModifSchoolYearForm->get('actualModifSchoolYear')->getData(); if ($modifActual) { $AllSchoolYear = $this->schoolYearRepo->findAll(); foreach ($AllSchoolYear as $oneSchoolYear) { $oneSchoolYear->setSchoolYearActual(false); } } $beginDateFormat = \DateTime::createFromFormat('d-m-Y', $modifBeginDate); $endDateFormat = \DateTime::createFromFormat('d-m-Y', $modifEndDate); $beginHourFormat = \DateTime::createFromFormat('H:i', $modifBeginHour); $endHourFormat = \DateTime::createFromFormat('H:i', $modifEndHour); $theSchoolYear->setSchoolYearName($modifName); $theSchoolYear->setSchoolYearBegin($beginDateFormat); $theSchoolYear->setSchoolYearEnd($endDateFormat); $theSchoolYear->setSchoolDayBeginHour($beginHourFormat); $theSchoolYear->setSchoolDayEndHour($endHourFormat); $theSchoolYear->setSchoolYearActual($modifActual); $this->em->persist($theSchoolYear); $this->em->flush(); return new JsonResponse('success', 200); } return array('ModifSchoolYearForm' => $ModifSchoolYearForm->createView(), 'theSchoolYear' => $theSchoolYear, ); } /** * @EXT\Route( * "/presence/schoolYear_supprimer/theSchoolYear/{theSchoolYear}", * name="formalibre_school_year_supprimer", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user */ public function SchoolYearSupprimerAction(SchoolYear $theSchoolYear) { $this->em->remove($theSchoolYear); $this->em->flush(); return new JsonResponse('success', 200); } /** * @EXT\Route( * "/admin/presence/right/right/{right}/rightValue/{rightValue}", * name="formalibre_presence_admin_right", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) */ public function adminRightAction(PresenceRights $right, $rightValue) { $mask = $right->getMask(); $newmask = $mask ^ $rightValue; $right->setMask($newmask); $this->om->persist($right); $this->om->flush(); return new Response('success', 200); } /** * @EXT\Route( * "/admin/presence/horaire", * name="formalibre_presence_horaire", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user * @EXT\Template() */ public function adminHoraireAction() { $Periods = $this->periodRepo->findAll(); $SchoolYear = $this->schoolYearRepo->findOneBySchoolYearActual(true); if (!is_null($SchoolYear)) { $SchoolYearBeginHour = $SchoolYear->getSchoolDayBeginHour(); $SchoolYearEndHour = $SchoolYear->getSchoolDayEndHour(); } else { $SchoolYearBeginHour = '08:00:00'; $SchoolYearEndHour = '18:00:00'; } $NewPeriodForm = $this->createFormBuilder() ->add('day', 'choice', array( 'choices' => array( 'monday' => 'lundi', 'tuesday' => 'mardi', 'wednesday' => 'mercredi', 'thursday' => 'jeudi', 'friday' => 'vendredi', 'saturday' => 'samedi', ), 'multiple' => true, 'expanded' => true, )) ->add('number', 'text') ->add('name', 'text') ->add('start', 'text') ->add('end', 'text') ->add('valider', 'submit', array( 'label' => 'Ajouter', )) ->getForm(); $request = $this->getRequest(); if ($request->getMethod() === 'POST') { $NewPeriodForm->handleRequest($request); $startHour = $NewPeriodForm->get('start')->getData(); $endHour = $NewPeriodForm->get('end')->getData(); $name = $NewPeriodForm->get('name')->getData(); $number = $NewPeriodForm->get('number')->getData(); $wichDay = $NewPeriodForm->get('day')->getData(); $startHourFormat = \DateTime::createFromFormat('H:i', $startHour); $endHourFormat = \DateTime::createFromFormat('H:i', $endHour); if (!is_null($SchoolYear)) { $BeginSchoolYearDate = $SchoolYear->getSchoolYearBegin(); $EndSchoolYearDate = $SchoolYear->getSchoolYearEnd(); foreach ($wichDay as $oneDay) { $begin = $BeginSchoolYearDate; $begin->modify('last '.$oneDay); $interval = new \DateInterval('P1W'); //interval d'une semaine $end = $EndSchoolYearDate; $end->modify('next '.$oneDay); //dernier jour du mois $period = new \DatePeriod($begin, $interval, $end); foreach ($period as $date) { $dateFormat = $date->format('Y-m-d'); $dayNameFormat = $date->format('l'); $actualPeriod = new Period(); $actualPeriod->setBeginHour($startHourFormat); $actualPeriod->setEndHour($endHourFormat); $actualPeriod->setDay($date); $actualPeriod->setDayName($dayNameFormat); $actualPeriod->setName($name); $actualPeriod->setNumPeriod($number); $actualPeriod->setSchoolYearId($SchoolYear); $this->em->persist($actualPeriod); $this->em->flush(); } } } else { $session = $request->getSession(); $session->getFlashBag()->add('error', "Vous n'avez pas selectionner l'année courante dans le menu de configuration"); } return $this->redirect($this->generateUrl('formalibre_presence_horaire')); } return array('NewPeriodForm' => $NewPeriodForm->createView(), 'periods' => $Periods, 'schoolYear' => $SchoolYear, 'schoolYearBeginHour' => $SchoolYearBeginHour, 'schoolYearEndHour' => $SchoolYearEndHour, ); } /** * @EXT\Route( * "/admin/presence/modifier_horaire/period/{period}", * name="formalibre_presence_modifier_horaire", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user * @EXT\Template() */ public function adminModifierHoraireAction(Period $period) { $ModifPeriodForm = $this->createFormBuilder() ->add('numberMod', 'text') ->add('nameMod', 'text') ->add('startMod', 'text') ->add('endMod', 'text') ->add('dayName', 'hidden') ->add('modifier', 'submit') ->getForm(); $request = $this->get('request'); if ($request->getMethod() == 'POST') { $ModifPeriodForm->handleRequest($request); $startHour = $ModifPeriodForm->get('startMod')->getData(); $endHour = $ModifPeriodForm->get('endMod')->getData(); $name = $ModifPeriodForm->get('nameMod')->getData(); $number = $ModifPeriodForm->get('numberMod')->getData(); $dayName = $ModifPeriodForm->get('dayName')->getData(); $startHourFormat = \DateTime::createFromFormat('H:i', $startHour); $endHourFormat = \DateTime::createFromFormat('H:i', $endHour); $PeriodToModif = $this->periodRepo->findBy(array('beginHour' => $startHourFormat, 'endHour' => $endHourFormat, 'dayName' => $dayName, )); foreach ($PeriodToModif as $OnePeriodToModif) { $OnePeriodToModif->setBeginHour($startHourFormat); $OnePeriodToModif->setEndHour($endHourFormat); $OnePeriodToModif->setName($name); $OnePeriodToModif->setNumPeriod($number); } $this->em->flush(); return new JsonResponse('success', 200); } return array('ModifPeriodForm' => $ModifPeriodForm->createView(), 'period' => $period); } /** * @EXT\Route( * "/admin/period_supprimer/period/{period}", * name="formalibre_period_supprimer", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user */ public function adminPeriodSupprimerAction(Period $period) { $startHour = $period->getBeginHour(); $endHour = $period->getEndHour(); $dayName = $period->getDayName(); $PeriodToModif = $this->periodRepo->findBy(array('beginHour' => $startHour, 'endHour' => $endHour, 'dayName' => $dayName, )); foreach ($PeriodToModif as $OnePeriodToModif) { $this->em->remove($OnePeriodToModif); } $this->em->flush(); return new RedirectResponse($this->router->generate('formalibre_presence_horaire')); } /** * @EXT\Route( * "/admin/listing/roles", * name="formalibre_admin_listing_roles", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) */ public function adminListingRolesAction() { return array(); } /** * @EXT\Route( * "/presence/status_modif/id/{theStatus}", * name="formalibre_status_modif", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user * @EXT\Template() */ public function StatusModifAction(Status $theStatus) { $ModifStatusForm = $this->createFormBuilder() ->add('name2', 'text') ->add('color2', 'text') ->add('principalStatus2', 'checkbox', array( 'required' => false, ) ) ->add('valider2', 'submit', array( 'label' => 'Modifier', )) ->getForm(); $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $ModifStatusForm->handleRequest($request); $NewName = $ModifStatusForm->get('name2')->getData(); $NewColor = $ModifStatusForm->get('color2')->getData(); $NewByDefault = $ModifStatusForm->get('principalStatus2')->getData(); $theStatus->setStatusName($NewName); $theStatus->setStatusColor($NewColor); $theStatus->setStatusByDefault($NewByDefault); $this->em->persist($theStatus); $this->em->flush(); return new JsonResponse('success', 200); } return array('ModifStatusForm' => $ModifStatusForm->createView(), 'theStatus' => $theStatus, ); } /** * @EXT\Route( * "/presence/status_supprimerf/id/{theStatus}", * name="formalibre_status_supprimer", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user */ public function StatussupprimerAction(Status $theStatus) { $this->em->remove($theStatus); $this->em->flush(); return new JsonResponse('success', 200); } /** * @EXT\Route( * "/presence/listingstatusbydefault", * name="formalibre_presence_listingstatusbydefault", * options={"expose"=true} * ) * * @EXT\ParamConverter("user", options={"authenticatedUser" = true}) * * @param User $user */ public function ListingStatusByDefaultAction() { $liststatus = $this->statuRepo->findByStatusByDefault(0); $datas = array(); foreach ($liststatus as $status) { $datas[$status->getId()] = array(); $datas[$status->getId()] = $status->getId(); } return new JsonResponse($datas, 200); } }
ClaroBot/Distribution
plugin/presence/Controller/AdminPresenceController.php
PHP
gpl-3.0
23,906
/* * Example program for the Allegro library, by Dave Thomson. * * This program draws a 3D star field (depth-cued) and a polygon * starship (controllable with the keyboard cursor keys), using * the Allegro math functions. */ #include <allegro.h> /* star field system */ typedef struct VECTOR { fixed x, y, z; } VECTOR; #define NUM_STARS 512 #define Z_NEAR 24 #define Z_FAR 1024 #define XY_CUBE 2048 #define SPEED_LIMIT 20 VECTOR stars[NUM_STARS]; fixed star_x[NUM_STARS]; fixed star_y[NUM_STARS]; VECTOR delta; /* polygonal models */ #define NUM_VERTS 4 #define NUM_FACES 4 #define ENGINE 3 /* which face is the engine */ #define ENGINE_ON 64 /* colour index */ #define ENGINE_OFF 32 typedef struct FACE /* for triangular models */ { int v1, v2, v3; int colour, range; VECTOR normal, rnormal; } FACE; typedef struct MODEL { VECTOR points[NUM_VERTS]; FACE faces[NUM_FACES]; fixed x, y, z; fixed rx, ry, rz; int minx, miny, maxx, maxy; VECTOR aim; int velocity; } MODEL; MODEL ship; VECTOR direction; BITMAP *buffer; /* initialises the star field system */ void init_stars(void) { int i; for (i=0; i<NUM_STARS; i++) { stars[i].x = itofix((AL_RAND() % XY_CUBE) - (XY_CUBE >> 1)); stars[i].y = itofix((AL_RAND() % XY_CUBE) - (XY_CUBE >> 1)); stars[i].z = itofix((AL_RAND() % (Z_FAR - Z_NEAR)) + Z_NEAR); } delta.x = 0; delta.y = 0; delta.z = 0; } /* draws the star field */ void draw_stars(void) { int i, c; MATRIX m; VECTOR outs[NUM_STARS]; for (i=0; i<NUM_STARS; i++) { get_translation_matrix(&m, delta.x, delta.y, delta.z); apply_matrix(&m, stars[i].x, stars[i].y, stars[i].z, &outs[i].x, &outs[i].y, &outs[i].z); persp_project(outs[i].x, outs[i].y, outs[i].z, &star_x[i], &star_y[i]); c = (fixtoi(outs[i].z) >> 8) + 16; putpixel(buffer, fixtoi(star_x[i]), fixtoi(star_y[i]), palette_color[c]); } } /* deletes the stars from the screen */ void erase_stars(void) { int i; for (i=0; i<NUM_STARS; i++) putpixel(buffer, fixtoi(star_x[i]), fixtoi(star_y[i]), palette_color[0]); } /* moves the stars */ void move_stars(void) { int i; for (i=0; i<NUM_STARS; i++) { stars[i].x += delta.x; stars[i].y += delta.y; stars[i].z += delta.z; if (stars[i].x > itofix(XY_CUBE >> 1)) stars[i].x = itofix(-(XY_CUBE >> 1)); else if (stars[i].x < itofix(-(XY_CUBE >> 1))) stars[i].x = itofix(XY_CUBE >> 1); if (stars[i].y > itofix(XY_CUBE >> 1)) stars[i].y = itofix(-(XY_CUBE >> 1)); else if (stars[i].y < itofix(-(XY_CUBE >> 1))) stars[i].y = itofix(XY_CUBE >> 1); if (stars[i].z > itofix(Z_FAR)) stars[i].z = itofix(Z_NEAR); else if (stars[i].z < itofix(Z_NEAR)) stars[i].z = itofix(Z_FAR); } } /* initialises the ship model */ void init_ship(void) { VECTOR v1, v2, *pts; FACE *face; int i; ship.points[0].x = itofix(0); ship.points[0].y = itofix(0); ship.points[0].z = itofix(32); ship.points[1].x = itofix(16); ship.points[1].y = itofix(-16); ship.points[1].z = itofix(-32); ship.points[2].x = itofix(-16); ship.points[2].y = itofix(-16); ship.points[2].z = itofix(-32); ship.points[3].x = itofix(0); ship.points[3].y = itofix(16); ship.points[3].z = itofix(-32); ship.faces[0].v1 = 3; ship.faces[0].v2 = 0; ship.faces[0].v3 = 1; pts = &ship.points[0]; face = &ship.faces[0]; v1.x = (pts[face->v2].x - pts[face->v1].x); v1.y = (pts[face->v2].y - pts[face->v1].y); v1.z = (pts[face->v2].z - pts[face->v1].z); v2.x = (pts[face->v3].x - pts[face->v1].x); v2.y = (pts[face->v3].y - pts[face->v1].y); v2.z = (pts[face->v3].z - pts[face->v1].z); cross_product(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, &(face->normal.x), &(face->normal.y), &(face->normal.z)); ship.faces[1].v1 = 2; ship.faces[1].v2 = 0; ship.faces[1].v3 = 3; face = &ship.faces[1]; v1.x = (pts[face->v2].x - pts[face->v1].x); v1.y = (pts[face->v2].y - pts[face->v1].y); v1.z = (pts[face->v2].z - pts[face->v1].z); v2.x = (pts[face->v3].x - pts[face->v1].x); v2.y = (pts[face->v3].y - pts[face->v1].y); v2.z = (pts[face->v3].z - pts[face->v1].z); cross_product(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, &(face->normal.x), &(face->normal.y), &(face->normal.z)); ship.faces[2].v1 = 1; ship.faces[2].v2 = 0; ship.faces[2].v3 = 2; face = &ship.faces[2]; v1.x = (pts[face->v2].x - pts[face->v1].x); v1.y = (pts[face->v2].y - pts[face->v1].y); v1.z = (pts[face->v2].z - pts[face->v1].z); v2.x = (pts[face->v3].x - pts[face->v1].x); v2.y = (pts[face->v3].y - pts[face->v1].y); v2.z = (pts[face->v3].z - pts[face->v1].z); cross_product(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, &(face->normal.x), &(face->normal.y), &(face->normal.z)); ship.faces[3].v1 = 2; ship.faces[3].v2 = 3; ship.faces[3].v3 = 1; face = &ship.faces[3]; v1.x = (pts[face->v2].x - pts[face->v1].x); v1.y = (pts[face->v2].y - pts[face->v1].y); v1.z = (pts[face->v2].z - pts[face->v1].z); v2.x = (pts[face->v3].x - pts[face->v1].x); v2.y = (pts[face->v3].y - pts[face->v1].y); v2.z = (pts[face->v3].z - pts[face->v1].z); cross_product(v1.x, v1.y, v1.z, v2.x, v2.y, v2.z, &(face->normal.x), &(face->normal.y), &(face->normal.z)); for (i=0; i<NUM_FACES; i++) { ship.faces[i].colour = 32; ship.faces[i].range = 15; normalize_vector(&ship.faces[i].normal.x, &ship.faces[i].normal.y, &ship.faces[i].normal.z); ship.faces[i].rnormal.x = ship.faces[i].normal.x; ship.faces[i].rnormal.y = ship.faces[i].normal.y; ship.faces[i].rnormal.z = ship.faces[i].normal.z; } ship.x = ship.y = 0; ship.z = itofix(192); ship.rx = ship.ry = ship.rz = 0; ship.aim.x = direction.x = 0; ship.aim.y = direction.y = 0; ship.aim.z = direction.z = itofix(-1); ship.velocity = 0; } /* draws the ship model */ void draw_ship(void) { VECTOR outs[NUM_VERTS]; MATRIX m; int i, col; ship.minx = SCREEN_W; ship.miny = SCREEN_H; ship.maxx = ship.maxy = 0; get_rotation_matrix(&m, ship.rx, ship.ry, ship.rz); apply_matrix(&m, ship.aim.x, ship.aim.y, ship.aim.z, &outs[0].x, &outs[0].y, &outs[0].z); direction.x = outs[0].x; direction.y = outs[0].y; direction.z = outs[0].z; for (i=0; i<NUM_FACES; i++) apply_matrix(&m, ship.faces[i].normal.x, ship.faces[i].normal.y, ship.faces[i].normal.z, &ship.faces[i].rnormal.x, &ship.faces[i].rnormal.y, &ship.faces[i].rnormal.z); get_transformation_matrix(&m, itofix(1), ship.rx, ship.ry, ship.rz, ship.x, ship.y, ship.z); for (i=0; i<NUM_VERTS; i++) { apply_matrix(&m, ship.points[i].x, ship.points[i].y, ship.points[i].z, &outs[i].x, &outs[i].y, &outs[i].z); persp_project(outs[i].x, outs[i].y, outs[i].z, &outs[i].x, &outs[i].y); if (fixtoi(outs[i].x) < ship.minx) ship.minx = fixtoi(outs[i].x); if (fixtoi(outs[i].x) > ship.maxx) ship.maxx = fixtoi(outs[i].x); if (fixtoi(outs[i].y) < ship.miny) ship.miny = fixtoi(outs[i].y); if (fixtoi(outs[i].y) > ship.maxy) ship.maxy = fixtoi(outs[i].y); } for (i=0; i<NUM_FACES; i++) { if (fixtof(ship.faces[i].rnormal.z) < 0.0) { col = fixtoi(fixmul(dot_product(ship.faces[i].rnormal.x, ship.faces[i].rnormal.y, ship.faces[i].rnormal.z, 0, 0, itofix(1)), itofix(ship.faces[i].range))); if (col < 0) col = -col + ship.faces[i].colour; else col = col + ship.faces[i].colour; triangle(buffer, fixtoi(outs[ship.faces[i].v1].x), fixtoi(outs[ship.faces[i].v1].y), fixtoi(outs[ship.faces[i].v2].x), fixtoi(outs[ship.faces[i].v2].y), fixtoi(outs[ship.faces[i].v3].x), fixtoi(outs[ship.faces[i].v3].y), palette_color[col]); } } } /* removes the ship model from the screen */ void erase_ship(void) { rectfill(buffer, ship.minx, ship.miny, ship.maxx, ship.maxy, palette_color[0]); } int main(int argc, char *argv[]) { PALETTE pal; int i; if (allegro_init() != 0) return 1; install_keyboard(); install_timer(); if (set_gfx_mode(GFX_AUTODETECT, 640, 480, 0, 0) != 0) { if (set_gfx_mode(GFX_SAFE, 640, 480, 0, 0) != 0) { set_gfx_mode(GFX_TEXT, 0, 0, 0, 0); allegro_message("Unable to set any graphic mode\n%s\n", allegro_error); return 1; } } for (i=0; i<16; i++) pal[i].r = pal[i].g = pal[i].b = 0; /* greyscale */ pal[16].r = pal[16].g = pal[16].b = 63; pal[17].r = pal[17].g = pal[17].b = 48; pal[18].r = pal[18].g = pal[18].b = 32; pal[19].r = pal[19].g = pal[19].b = 16; pal[20].r = pal[20].g = pal[20].b = 8; /* red range */ for (i=0; i<16; i++) { pal[i+32].r = 31 + i*2; pal[i+32].g = 15; pal[i+32].b = 7; } /* a nice fire orange */ for (i=64; i<68; i++) { pal[i].r = 63; pal[i].g = 17 + (i-64)*3; pal[i].b = 0; } set_palette(pal); buffer = create_bitmap(SCREEN_W, SCREEN_H); clear_bitmap(buffer); set_projection_viewport(0, 0, SCREEN_W, SCREEN_H); init_stars(); draw_stars(); init_ship(); draw_ship(); for (;;) { erase_stars(); erase_ship(); move_stars(); draw_stars(); textprintf_centre_ex(buffer, font, SCREEN_W / 2, SCREEN_H-10, palette_color[17], 0, " direction: [%f] [%f] [%f] ", fixtof(direction.x), fixtof(direction.y), fixtof(direction.z)); textprintf_centre_ex(buffer, font, SCREEN_W / 2, SCREEN_H-20, palette_color[17], 0, " delta: [%f] [%f] [%f] ", fixtof(delta.x), fixtof(delta.y), fixtof(delta.z)); textprintf_centre_ex(buffer, font, SCREEN_W / 2, SCREEN_H-30, palette_color[17], 0, " velocity: %d ", ship.velocity); textout_centre_ex(buffer, font, "Press ESC to exit", SCREEN_W/2, 16, palette_color[18], 0); textout_centre_ex(buffer, font, "Press CTRL to fire engine", SCREEN_W/2, 32, palette_color[18], 0); draw_ship(); vsync(); blit(buffer, screen, 0, 0, 0, 0, SCREEN_W, SCREEN_H); poll_keyboard(); /* exit program */ if (key[KEY_ESC]) break; /* rotates */ if (key[KEY_UP]) ship.rx -= itofix(5); else if (key[KEY_DOWN]) ship.rx += itofix(5); if (key[KEY_LEFT]) ship.ry -= itofix(5); else if (key[KEY_RIGHT]) ship.ry += itofix(5); if (key[KEY_PGUP]) ship.rz -= itofix(5); else if (key[KEY_PGDN]) ship.rz += itofix(5); /* thrust */ if ((key[KEY_LCONTROL]) || (key[KEY_RCONTROL])) { ship.faces[ENGINE].colour = ENGINE_ON; ship.faces[ENGINE].range = 3; if (ship.velocity < SPEED_LIMIT) ship.velocity += 2; } else { ship.faces[ENGINE].colour = ENGINE_OFF; ship.faces[ENGINE].range = 15; if (ship.velocity > 0) ship.velocity -= 2; } ship.rx &= itofix(255); ship.ry &= itofix(255); ship.rz &= itofix(255); delta.x = fixmul(direction.x, itofix(ship.velocity)); delta.y = fixmul(direction.y, itofix(ship.velocity)); delta.z = fixmul(direction.z, itofix(ship.velocity)); } destroy_bitmap(buffer); return 0; } END_OF_MAIN()
ArmageddonGames/ZeldaClassic
allegro/examples/exstars.c
C
gpl-3.0
11,469
/* * BPG encoder * * Copyright (c) 2014 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifdef __cplusplus extern "C" { #endif #include "libbpg.h" typedef struct { int w, h; BPGImageFormatEnum format; /* x_VIDEO values are forbidden here */ uint8_t c_h_phase; /* 4:2:2 or 4:2:0 : give the horizontal chroma position. 0=MPEG2, 1=JPEG. */ uint8_t has_alpha; uint8_t has_w_plane; uint8_t limited_range; uint8_t premultiplied_alpha; BPGColorSpaceEnum color_space; uint8_t bit_depth; uint8_t pixel_shift; /* (1 << pixel_shift) bytes per pixel */ uint8_t *data[4]; int linesize[4]; } Image; typedef struct { int width; int height; int chroma_format; /* 0-3 */ int bit_depth; /* 8-14 */ int intra_only; /* 0-1 */ int qp; /* quantizer 0-51 */ int lossless; /* 0-1 lossless mode */ int sei_decoded_picture_hash; /* 0=no hash, 1=MD5 hash */ int compress_level; /* 1-9 */ int verbose; } HEVCEncodeParams; typedef struct HEVCEncoderContext HEVCEncoderContext; typedef struct { HEVCEncoderContext *(*open)(const HEVCEncodeParams *params); int (*encode)(HEVCEncoderContext *s, Image *img); int (*close)(HEVCEncoderContext *s, uint8_t **pbuf); } HEVCEncoder; extern HEVCEncoder jctvc_encoder; extern HEVCEncoder x265_hevc_encoder; int x265_encode_picture(uint8_t **pbuf, Image *img, const HEVCEncodeParams *params); void save_yuv1(Image *img, FILE *f); void save_yuv(Image *img, const char *filename); #ifdef __cplusplus } #endif
AlienCowEatCake/ImageViewer
src/ThirdParty/libbpg/libbpg-0.9.8/bpgenc.h
C
gpl-3.0
2,627
<?php /* All functions related to user/role access privileges. * * Access is restricted in two ways: by function and by a user's calendar. * * The webcal_access_user table keeps track of when one user can view * the calendar of another user. * * The webcal_access_function table grants access to specific * WebCalendar pages for specific users. * * @author Craig Knudsen <[email protected]> * @copyright Craig Knudsen, <[email protected]>, http://www.k5n.us/cknudsen * @license http://www.gnu.org/licenses/gpl.html GNU GPL * @version $Id: access.php,v 1.46.2.8 2008/04/21 19:45:21 umcesrjones Exp $ * @package WebCalendar */ /* The following define statements are based on this matrix PUBLIC CONFIDENTIAL PRIVATE EVENT 1 8 64 = 73 TASK 2 16 128 = 146 JOURNAL 4 32 256 = 292 ---------------------------------------------- 7 56 448 = 511 */ define ( 'EVENT_WT', 73 ); define ( 'TASK_WT', 146 ); define ( 'JOURNAL_WT', 292 ); define ( 'PUBLIC_WT', 7 ); define ( 'CONF_WT', 56 ); define ( 'PRIVATE_WT', 448 ); define ( 'CAN_DOALL', 511 ); // Can access all types and levels. /*#@+ * Constants for use with cal_permissions column in webcal_access_function table. */ define ( 'ACCESS_EVENT_VIEW', 0 ); define ( 'ACCESS_EVENT_EDIT', 1 ); define ( 'ACCESS_DAY', 2 ); define ( 'ACCESS_WEEK', 3 ); define ( 'ACCESS_MONTH', 4 ); define ( 'ACCESS_YEAR', 5 ); define ( 'ACCESS_ADMIN_HOME', 6 ); define ( 'ACCESS_REPORT', 7 ); define ( 'ACCESS_VIEW', 8 ); define ( 'ACCESS_VIEW_MANAGEMENT', 9 ); define ( 'ACCESS_CATEGORY_MANAGEMENT', 10 ); define ( 'ACCESS_LAYERS', 11 ); define ( 'ACCESS_SEARCH', 12 ); define ( 'ACCESS_ADVANCED_SEARCH', 13 ); define ( 'ACCESS_ACTIVITY_LOG', 14 ); define ( 'ACCESS_USER_MANAGEMENT', 15 ); define ( 'ACCESS_ACCOUNT_INFO', 16 ); define ( 'ACCESS_ACCESS_MANAGEMENT', 17 ); define ( 'ACCESS_PREFERENCES', 18 ); define ( 'ACCESS_SYSTEM_SETTINGS', 19 ); define ( 'ACCESS_IMPORT', 20 ); define ( 'ACCESS_EXPORT', 21 ); define ( 'ACCESS_PUBLISH', 22 ); define ( 'ACCESS_ASSISTANTS', 23 ); define ( 'ACCESS_TRAILER', 24 ); define ( 'ACCESS_HELP', 25 ); define ( 'ACCESS_ANOTHER_CALENDAR', 26 ); define ( 'ACCESS_SECURITY_AUDIT', 27 ); // Note: If you modify ACCESS_NUMBER_FUNCTIONS, you must add the new function // to the order[] array defined in ../access.php. define ( 'ACCESS_NUMBER_FUNCTIONS', 28 ); // How many function did we define? /*#@-*/ // The following pages will be handled differently than the others since they // have different uses. For example, edit_user.php adds a user when the user is // an admin. If the user is not an admin, it updates account info. Register is // just for new users. Most of the pages have dual uses, so we will have access // checks within these files. $GLOBALS['page_lookup_ex'] = array ( 'about.php' => 1, 'colors.php' => 1, 'css_cacher.php' => 1, 'edit_template.php' => 1, 'edit_user.php' => 1, 'edit_user_handler.php' => 1, 'icons.php' => 1, 'index.php' => 1, 'js_cacher.php' => 1, 'nulogin.php' => 1, 'register.php' => 1 ); /* The following array provides a way to convert a page filename into a numeric * $ACCESS_XXX number. The array key is a regular expression. If the page * matches the regular expression, then it will use the corresponding access id. * There are some pages that have more than one use (edit_template.php is used * for editing a report and editing the custom header). These pages will be * handled differently and are listed in the $page_lookup_ex[] array. * @global array $GLOBAL['page_lookup'] * @name $page_lookup */ $GLOBALS['page_lookup'] = array ( ACCESS_EVENT_VIEW =>'(view_entry.php|select_user.php|purge.php|category*php|doc.php)', ACCESS_EVENT_EDIT =>'(_entry|list_unapproved|usersel|availability|datesel|catsel|docadd|docdel)', ACCESS_DAY => 'day.php', ACCESS_WEEK => '(week.php|week_details.php)', ACCESS_MONTH => 'month.php', ACCESS_YEAR => 'year.php', ACCESS_ADMIN_HOME => '(adminhome.php)', ACCESS_REPORT => 'report', ACCESS_VIEW => 'view_..php', ACCESS_VIEW_MANAGEMENT => '(views.php|views_edit)', ACCESS_CATEGORY_MANAGEMENT => 'category.*php', ACCESS_LAYERS => 'layer', ACCESS_SEARCH => 'search', ACCESS_ADVANCED_SEARCH => 'search', ACCESS_ACTIVITY_LOG => 'activity_log.php', ACCESS_SECURITY_AUDIT => 'security_audit.php', ACCESS_USER_MANAGEMENT => '(edit.*user.*.php|nonusers.*php|group.*php|users.php)', ACCESS_ACCOUNT_INFO => '(users.php|XYZXYZ_special_case)', ACCESS_ACCESS_MANAGEMENT => '(access.*php)', ACCESS_PREFERENCES => 'pref.*php', ACCESS_SYSTEM_SETTINGS => '(admin.php|admin_handler.php|controlpanel.php)', ACCESS_IMPORT => '(import.*php|edit_remotes.php|edit_remotes_handler.php)', ACCESS_EXPORT => 'export.*php', ACCESS_PUBLISH =>'(publish.php|freebusy.php|icalclient.php|rss.php|minical.php|upcoming.php)', ACCESS_ASSISTANTS => 'assist.*php', ACCESS_TRAILER => 'trailer.*php', ACCESS_HELP => 'help_.*php', ACCESS_ANOTHER_CALENDAR => 'select_user_.*php', ACCESS_SECURITY_AUDIT => 'security_audit.*php', ACCESS_NUMBER_FUNCTIONS => '' ); /* Is user access control enabled? * * @return bool True if user access control is enabled */ function access_is_enabled () { global $UAC_ENABLED; return ( ! empty ( $UAC_ENABLED ) && $UAC_ENABLED == 'Y' ); } /* Return the name of a specific function. * * @param int $function The function (ACCESS_DAY, etc.). * @return string The text description of the function. */ function access_get_function_description ( $function ) { switch ( $function ) { case ACCESS_ACCESS_MANAGEMENT: return translate ( 'User Access Control' ); case ACCESS_ACCOUNT_INFO: return translate ( 'Account' ); case ACCESS_ACTIVITY_LOG: return translate ( 'Activity Log' ); case ACCESS_SECURITY_AUDIT: return translate ( 'Security Audit' ); case ACCESS_ADMIN_HOME: return translate ( 'Administrative Tools' ); case ACCESS_ADVANCED_SEARCH: return translate ( 'Advanced Search' ); case ACCESS_ANOTHER_CALENDAR: return translate ( 'Another Users Calendar' ); case ACCESS_ASSISTANTS: return translate ( 'Assistants' ); case ACCESS_CATEGORY_MANAGEMENT: return translate ( 'Category Management' ); case ACCESS_DAY: return translate ( 'Day View' ); case ACCESS_EVENT_EDIT: return translate ( 'Edit Event' ); case ACCESS_EVENT_VIEW: return translate ( 'View Event' ); case ACCESS_EXPORT: return translate ( 'Export' ); case ACCESS_HELP: return translate ( 'Help' ); case ACCESS_IMPORT: return translate ( 'Import' ); case ACCESS_LAYERS: return translate ( 'Layers' ); case ACCESS_MONTH: return translate ( 'Month View' ); case ACCESS_PREFERENCES: return translate ( 'Preferences' ); case ACCESS_PUBLISH: return translate ( 'Subscribe/Publish' ); case ACCESS_REPORT: return translate ( 'Reports' ); case ACCESS_SEARCH: return translate ( 'Search' ); case ACCESS_SYSTEM_SETTINGS: return translate ( 'System Settings' ); case ACCESS_TRAILER: return translate ( 'Common Trailer' ); case ACCESS_USER_MANAGEMENT: return translate ( 'User Management' ); case ACCESS_VIEW: return translate ( 'Views' ); case ACCESS_VIEW_MANAGEMENT: return translate ( 'Manage Views' ); case ACCESS_WEEK: return translate ( 'Week View' ); case ACCESS_YEAR: return translate ( 'Year View' ); default: die_miserable_death ( translate ( 'Invalid function id' ) . ': ' . $function ); } } /* Load the permissions for all users. * * Settings will be stored in the global array $access_other_cals[]. * * @return array Array of permissions for viewing other calendars. * * @global array Stores permissions for viewing calendars */ function access_load_user_permissions ( $useCache = true ) { global $access_other_cals, $ADMIN_OVERRIDE_UAC, $is_admin; // Don't run this query twice. if ( ! empty ( $access_other_cals ) && $useCache == true ) return $access_other_cals; $admin_override = ( $is_admin && ! empty ( $ADMIN_OVERRIDE_UAC ) && $ADMIN_OVERRIDE_UAC == 'Y' ); $res = dbi_execute ( 'SELECT cal_login, cal_other_user, cal_can_view, cal_can_edit, cal_can_approve, cal_can_email, cal_can_invite, cal_see_time_only FROM webcal_access_user' ); assert ( '$res' ); while ( $row = dbi_fetch_row ( $res ) ) { // TODO should we set admin_override here to apply to // DEFAULT CONFIGURATION only? // $admin_override = ( $row[1] == '__default__' && $is_admin && // ! empty ( $ADMIN_OVERRIDE_UAC ) && $ADMIN_OVERRIDE_UAC == 'Y' ); $key = $row[0] . '.' . $row[1]; $access_other_cals[$key] = array ( 'cal_login' => $row[0], 'cal_other_user' => $row[1], 'view' => ( $admin_override ? CAN_DOALL : $row[2] ), 'edit' => ( $admin_override ? CAN_DOALL : $row[3] ), 'approve' => ( $admin_override ? CAN_DOALL : $row[4] ), 'email' => ( $admin_override ? 'Y' : $row[5] ), 'invite' => ( $admin_override ? 'Y' : $row[6] ), 'time' => ( $admin_override ? 'N' : $row[7] ) ); } dbi_free_result ( $res ); return $access_other_cals; } /* Returns a list of calendar logins that the specified user * is able to view the calendar of. * * @param string $user User login * * @return array An array of logins */ function access_get_viewable_users ( $user ) { global $access_other_cals, $login; $ret = array (); if ( empty ( $user ) ) $user = $login; if ( empty ( $access_other_cals ) ) access_load_user_permissions (); for ( $i = 0, $cnt = count ( $access_other_cals ); $i < $cnt; $i++ ) { if ( preg_match ( "/" . $user . "\. (\S+)/", $access_other_cals[$i], $matches ) ) $ret[] = $matches[1]; } return $ret; } /* Returns the row of the webcal_access_function table for the the specified user. * * If no entry is found for the specified user, then look up the user * '__default__'. If still no info found, then return some default values. * * @param string $user User login * * @return bool True if successful * * @global bool Is the current user an administrator? */ function access_load_user_functions ( $user ) { global $is_admin; static $permissions; if ( ! empty ( $permissions[$user] ) ) return $permissions[$user]; $ret = ''; $rets = array (); $users = array ( $user, '__default__' ); for ( $i = 0, $cnt = count ( $users ); $i < $cnt && empty ( $ret ); $i++ ) { $res = dbi_execute ( 'SELECT cal_permissions FROM webcal_access_function WHERE cal_login = ?', array ( $users[$i] ) ); assert ( '$res' ); if ( $row = dbi_fetch_row ( $res ) ) $rets[$users[$i]] = $row[0]; dbi_free_result ( $res ); } // If still no setting found, then assume access to everything // if an admin user, otherwise access to all non-admin functions. if ( ! empty ( $rets[$user] ) ) $ret = $rets[$user]; else if ( ! empty ( $rets['__default__'] ) ) $ret = $rets['__default__']; else { for ( $i = 0; $i < ACCESS_NUMBER_FUNCTIONS; $i++ ) { $ret .= get_default_function_access ( $i, $user ); } } // do_debug ( $user . " " . $ret); $permissions[$user] = $ret; return $ret; } /* Load permissions for the specified user. * * @param string $user User login * * @return bool True if successful * * @global string * @global bool Is the current user an administrator? */ function access_init ( $user = '' ) { global $access_user, $is_admin, $login; if ( empty ( $user ) && ! empty ( $login ) ) $user = $login; assert ( '! empty ( $user )' ); $access_user = access_load_user_functions ( $user ); return true; } /* Check to see if a user can access the specified page * (or the current page if no page is specified). * * @param int $function Functionality to check access to * @param string $user User login * * @return bool True if user can access the function * * @global string Username of the currently logged-in user */ function access_can_access_function ( $function, $user = '' ) { global $login; if ( ! access_is_enabled () ) return true; if ( empty ( $user ) && ! empty ( $login ) ) $user = $login; assert ( '! empty ( $user )' ); assert ( 'isset ( $function )' ); $access = access_load_user_functions ( $user ); // echo $function . ' ' . $access . '<br />'; $yesno = substr ( $access, $function, 1 ); if ( empty ( $yesno ) ) $yesno = get_default_function_access ( $function, $user ); // echo "yesno = $yesno<br />\n"; assert ( '! empty ( $yesno )' ); return ( $yesno == 'Y' ); } /* Check to see if a user can access the specified page * (or the current page if no page is specified). * * @param string $page Page to check access to. * @param string $user User login. * * @return bool True if user can access the page. * * @global string $access_user The user we're trying to access. * @global string $PHP_SELF The page currently being viewed by the user. * @global string $login The username of the currently logged-in user. * @global array $page_lookup Rules for access. * @global array $page_lookup_ex Exceptions to our rules. * @global bool $is_admin Is the currently logged-in user an administrator? */ function access_can_view_page ( $page = '', $user = '' ) { global $access_user, $is_admin, $login, $page_lookup, $page_lookup_ex, $PHP_SELF; if ( ! access_is_enabled () ) return true; if ( empty ( $user ) && ! empty ( $login ) ) $user = $login; assert ( '! empty ( $user )' ); if ( empty ( $page ) && ! empty ( $PHP_SELF ) ) $page = $PHP_SELF; assert ( '! empty ( $page )' ); $page = basename ( $page ); // Handle special cases for publish.php and freebusy.php. if ( substr ( $page, -3 ) == 'ics' ) $page = 'publish.php'; if ( substr ( $page, -3 ) == 'ifb' ) $page = 'freebusy.php'; // First, check list of exceptions to our rules. if ( ! empty ( $page_lookup_ex[$page] ) ) return true; for ( $i = 0; $i <= ACCESS_NUMBER_FUNCTIONS; $i++ ) { if ( ! empty ( $page_lookup[$i] ) && preg_match ( "/$page_lookup[$i]/", $page ) ) $page_id = $i; } //echo "page_id = $page_id<br />page = $page<br />\n"; // If the specified user is the currently logged in user, then we have already // loaded this user's access, stored in the global variable $access_user. $access = ( ! empty ( $login ) && $user == $login && ! empty ( $access_user ) ? $access_user : // User is not the user logged in. Need to load info from db now. access_load_user_functions ( $user ) ); assert ( '! empty ( $access )' ); // If we did not find a page id, then this is also a WebCalendar bug. // (Someone needs to add another entry in the $page_lookup[] array.) $yesno = substr ( $access, $page_id, 1 ); // No setting found. Use default values. if ( empty ( $yesno ) ) $yesno = get_default_function_access ( $page_id, $user ); //echo "yesno = $yesno<br />\n"; assert ( '! empty ( $yesno )' ); return ( $yesno == 'Y' ); } function get_default_function_access ( $page_id, $user ) { global $user_is_admin; user_load_variables ( $user, 'user_' ); switch ( $page_id ) { case ACCESS_ACTIVITY_LOG: case ACCESS_SECURITY_AUDIT: case ACCESS_ADMIN_HOME: case ACCESS_SYSTEM_SETTINGS: case ACCESS_USER_MANAGEMENT: return ( ! empty ( $user_is_admin ) && $user_is_admin == 'Y' ? 'Y' : 'N' ); break; default: return 'Y'; break; } } function access_user_calendar ( $cal_can_xxx = '', $other_user, $cur_user = '', $type = '', $access = '' ) { global $access_other_cals, $access_users, $login, $ADMIN_OVERRIDE_UAC, $is_admin; $admin_override = ( $is_admin && ! empty ( $ADMIN_OVERRIDE_UAC ) && $ADMIN_OVERRIDE_UAC == 'Y' ); if ( $admin_override ) return ( $cal_can_xxx == 'email' || $cal_can_xxx == 'invite' ? 'Y' : CAN_DOALL ); $access_wt = $ret = $type_wt = 0; if ( empty ( $cur_user ) && empty ( $login ) ) $cur_user = '__public__'; if ( empty ( $cur_user ) && ! empty ( $login ) ) $cur_user = $login; if ( $cur_user == $other_user ) { if ( $login == '__public__' && $cal_can_xxx == 'approve' ) return 'N'; return ( $cal_can_xxx == 'email' || $cal_can_xxx == 'invite' ? 'Y' : CAN_DOALL ); } assert ( '! empty ( $other_user )' ); assert ( '! empty ( $cur_user )' ); if ( empty ( $access_other_cals ) ) access_load_user_permissions (); $key1 = $cur_user . '.' . $other_user; $key2 = $cur_user . '.__default__'; $key3 = '__default__.' . $other_user; $key4 = '__default__.__default__'; if ( isset ( $access_other_cals[$key1][$cal_can_xxx] ) ) $ret = $access_other_cals[$key1][$cal_can_xxx]; else if ( isset ( $access_other_cals[$key2][$cal_can_xxx] ) ) $ret = $access_other_cals[$key2][$cal_can_xxx]; else if ( isset ( $access_other_cals[$key3][$cal_can_xxx] ) ) $ret = $access_other_cals[$key3][$cal_can_xxx]; else if ( isset ( $access_other_cals[$key4][$cal_can_xxx] ) ) $ret = $access_other_cals[$key4][$cal_can_xxx]; // Check type and access levels. if ( ! empty ( $access ) && ! empty ( $type ) ) { if ( $access == 'C' ) $access_wt = CONF_WT; if ( $access == 'P' ) $access_wt = PUBLIC_WT; if ( $access == 'R' ) $access_wt = PRIVATE_WT; if ( $type == 'E' || $type == 'M' ) $type_wt = EVENT_WT; if ( $type == 'J' || $type == 'O' ) $type_wt = JOURNAL_WT; if ( $type == 'T' || $type == 'N' ) $type_wt = TASK_WT; $total_wt = $type_wt & $access_wt; $ret = ( $ret &$total_wt ? $ret : 0 ); } return $ret; } ?>
greencityservice/greencity
src/WebCalendar/includes/access.php
PHP
gpl-3.0
18,002
/* * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client * Copyright (C) 1999-2004 Hiroyuki Yamamoto * This file (C) 2005 Andrej Kacian <[email protected]> * * - generic s-c plugin stuff * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef HAVE_CONFIG_H # include "config.h" # include "claws-features.h" #endif /* Global includes */ #include <glib/gi18n.h> #include <curl/curl.h> /* Claws Mail includes */ #include <common/claws.h> #include <common/version.h> #include <plugin.h> /* Local includes */ #include "rssyl.h" gint plugin_init(gchar **error) { if( !check_plugin_version(MAKE_NUMERIC_VERSION(3, 7, 8, 31), VERSION_NUMERIC, PLUGIN_NAME, error) ) return -1; curl_global_init(CURL_GLOBAL_DEFAULT); rssyl_init(); return 0; } gboolean plugin_done(void) { rssyl_done(); return TRUE; } const gchar *plugin_name(void) { return PLUGIN_NAME; } const gchar *plugin_desc(void) { return _("This plugin allows you to create a mailbox tree where you can add " "newsfeeds in RSS 1.0, RSS 2.0 or Atom format.\n\n" "Each newsfeed will create a folder with appropriate entries, fetched " "from the web. You can read them, and delete or keep old entries."); } const gchar *plugin_type(void) { return "GTK2"; } const gchar *plugin_licence(void) { return "GPL2+"; } const gchar *plugin_version(void) { return VERSION; } struct PluginFeature *plugin_provides(void) { static struct PluginFeature features[] = { {PLUGIN_FOLDERCLASS, N_("RSS feed")}, {PLUGIN_NOTHING, NULL}}; return features; }
eworm-de/claws-mail
src/plugins/rssyl/plugin.c
C
gpl-3.0
2,217
/* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2009 (C) Sindre Mehus */ package net.sourceforge.subsonic.controller; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.zip.CRC32; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.math.LongRange; import org.apache.http.util.EncodingUtils; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.mvc.LastModified; import net.sourceforge.subsonic.Logger; import net.sourceforge.subsonic.domain.MediaFile; import net.sourceforge.subsonic.domain.PlayQueue; import net.sourceforge.subsonic.domain.Player; import net.sourceforge.subsonic.domain.Playlist; import net.sourceforge.subsonic.domain.TransferStatus; import net.sourceforge.subsonic.domain.User; import net.sourceforge.subsonic.io.RangeOutputStream; import net.sourceforge.subsonic.service.MediaFileService; import net.sourceforge.subsonic.service.PlayerService; import net.sourceforge.subsonic.service.PlaylistService; import net.sourceforge.subsonic.service.SecurityService; import net.sourceforge.subsonic.service.SettingsService; import net.sourceforge.subsonic.service.StatusService; import net.sourceforge.subsonic.util.FileUtil; import net.sourceforge.subsonic.util.StringUtil; import net.sourceforge.subsonic.util.Util; /** * A controller used for downloading files to a remote client. If the requested path refers to a file, the * given file is downloaded. If the requested path refers to a directory, the entire directory (including * sub-directories) are downloaded as an uncompressed zip-file. * * @author Sindre Mehus */ public class DownloadController implements Controller, LastModified { private static final Logger LOG = Logger.getLogger(DownloadController.class); private PlayerService playerService; private StatusService statusService; private SecurityService securityService; private PlaylistService playlistService; private SettingsService settingsService; private MediaFileService mediaFileService; public long getLastModified(HttpServletRequest request) { try { MediaFile mediaFile = getMediaFile(request); if (mediaFile == null || mediaFile.isDirectory() || mediaFile.getChanged() == null) { return -1; } return mediaFile.getChanged().getTime(); } catch (ServletRequestBindingException e) { return -1; } } public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { TransferStatus status = null; try { status = statusService.createDownloadStatus(playerService.getPlayer(request, response, false, false)); MediaFile mediaFile = getMediaFile(request); Integer playlistId = ServletRequestUtils.getIntParameter(request, "playlist"); String playerId = request.getParameter("player"); int[] indexes = request.getParameter("i") == null ? null : ServletRequestUtils.getIntParameters(request, "i"); if (mediaFile != null) { response.setIntHeader("ETag", mediaFile.getId()); response.setHeader("Accept-Ranges", "bytes"); } LongRange range = StringUtil.parseRange(request.getHeader("Range")); if (range != null) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); LOG.info("Got range: " + range); } if (mediaFile != null) { if (mediaFile.isFile()) { downloadFile(response, status, mediaFile.getFile(), range); } else { List<MediaFile> children = mediaFileService.getChildrenOf(mediaFile, true, true, true); String zipFileName = FilenameUtils.getBaseName(mediaFile.getPath()) + ".zip"; downloadFiles(response, status, children, indexes, range, zipFileName); } } else if (playlistId != null) { List<MediaFile> songs = playlistService.getFilesInPlaylist(playlistId); Playlist playlist = playlistService.getPlaylist(playlistId); downloadFiles(response, status, songs, null, range, playlist.getName() + ".zip"); } else if (playerId != null) { Player player = playerService.getPlayerById(playerId); PlayQueue playQueue = player.getPlayQueue(); playQueue.setName("Playlist"); downloadFiles(response, status, playQueue.getFiles(), indexes, range, "download.zip"); } } finally { if (status != null) { statusService.removeDownloadStatus(status); User user = securityService.getCurrentUser(request); securityService.updateUserByteCounts(user, 0L, status.getBytesTransfered(), 0L); } } return null; } private MediaFile getMediaFile(HttpServletRequest request) throws ServletRequestBindingException { Integer id = ServletRequestUtils.getIntParameter(request, "id"); return id == null ? null : mediaFileService.getMediaFile(id); } /** * Downloads a single file. * * @param response The HTTP response. * @param status The download status. * @param file The file to download. * @param range The byte range, may be <code>null</code>. * @throws IOException If an I/O error occurs. */ private void downloadFile(HttpServletResponse response, TransferStatus status, File file, LongRange range) throws IOException { LOG.info("Starting to download '" + FileUtil.getShortPath(file) + "' to " + status.getPlayer()); status.setFile(file); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeAsRFC5987(file.getName())); if (range == null) { Util.setContentLength(response, file.length()); } copyFileToStream(file, RangeOutputStream.wrap(response.getOutputStream(), range), status, range); LOG.info("Downloaded '" + FileUtil.getShortPath(file) + "' to " + status.getPlayer()); } private String encodeAsRFC5987(String string) throws UnsupportedEncodingException { byte[] stringAsByteArray = string.getBytes("UTF-8"); char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; byte[] attrChar = {'!', '#', '$', '&', '+', '-', '.', '^', '_', '`', '|', '~', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; StringBuilder sb = new StringBuilder(); for (byte b : stringAsByteArray) { if (Arrays.binarySearch(attrChar, b) >= 0) { sb.append((char) b); } else { sb.append('%'); sb.append(digits[0x0f & (b >>> 4)]); sb.append(digits[b & 0x0f]); } } return sb.toString(); } /** * Downloads a collection of files within a directory. * * @param response The HTTP response. * @param status The download status. * @param dir The directory. * @param indexes Only download files with these indexes within the directory. * @throws IOException If an I/O error occurs. */ private void downloadFiles(HttpServletResponse response, TransferStatus status, File dir, int[] indexes) throws IOException { String zipFileName = dir.getName() + ".zip"; LOG.info("Starting to download '" + zipFileName + "' to " + status.getPlayer()); status.setFile(dir); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''"+ encodeAsRFC5987(zipFileName)); ZipOutputStream out = new ZipOutputStream(response.getOutputStream()); out.setMethod(ZipOutputStream.STORED); // No compression. MediaFile parent = mediaFileService.getMediaFile(dir); List<MediaFile> allChildren = mediaFileService.getChildrenOf(parent, true, true, true); List<MediaFile> mediaFiles = new ArrayList<MediaFile>(); for (int index : indexes) { mediaFiles.add(allChildren.get(index)); } for (MediaFile mediaFile : mediaFiles) { zip(out, mediaFile.getParentFile(), mediaFile.getFile(), status, null); } out.close(); LOG.info("Downloaded '" + zipFileName + "' to " + status.getPlayer()); } /** * Downloads all files in a directory (including sub-directories). The files are packed together in an * uncompressed zip-file. * * @param response The HTTP response. * @param status The download status. * @param file The file to download. * @param range The byte range, may be <code>null</code>. * @throws IOException If an I/O error occurs. */ private void downloadDirectory(HttpServletResponse response, TransferStatus status, File file, LongRange range) throws IOException { String zipFileName = file.getName() + ".zip"; LOG.info("Starting to download '" + zipFileName + "' to " + status.getPlayer()); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''"+ encodeAsRFC5987(zipFileName)); ZipOutputStream out = new ZipOutputStream(RangeOutputStream.wrap(response.getOutputStream(), range)); out.setMethod(ZipOutputStream.STORED); // No compression. zip(out, file.getParentFile(), file, status, range); out.close(); LOG.info("Downloaded '" + zipFileName + "' to " + status.getPlayer()); } /** * Downloads the given files. The files are packed together in an * uncompressed zip-file. * * @param response The HTTP response. * @param status The download status. * @param files The files to download. * @param indexes Only download songs at these indexes. May be <code>null</code>. * @param range The byte range, may be <code>null</code>. * @param zipFileName The name of the resulting zip file. * @throws IOException If an I/O error occurs. */ private void downloadFiles(HttpServletResponse response, TransferStatus status, List<MediaFile> files, int[] indexes, LongRange range, String zipFileName) throws IOException { if (indexes != null && indexes.length == 1) { downloadFile(response, status, files.get(indexes[0]).getFile(), range); return; } LOG.info("Starting to download '" + zipFileName + "' to " + status.getPlayer()); response.setContentType("application/x-download"); response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodeAsRFC5987(zipFileName)); ZipOutputStream out = new ZipOutputStream(RangeOutputStream.wrap(response.getOutputStream(), range)); out.setMethod(ZipOutputStream.STORED); // No compression. List<MediaFile> filesToDownload = new ArrayList<MediaFile>(); if (indexes == null) { filesToDownload.addAll(files); } else { for (int index : indexes) { try { filesToDownload.add(files.get(index)); } catch (IndexOutOfBoundsException x) { /* Ignored */} } } for (MediaFile mediaFile : filesToDownload) { zip(out, mediaFile.getParentFile(), mediaFile.getFile(), status, range); } out.close(); LOG.info("Downloaded '" + zipFileName + "' to " + status.getPlayer()); } /** * Utility method for writing the content of a given file to a given output stream. * * @param file The file to copy. * @param out The output stream to write to. * @param status The download status. * @param range The byte range, may be <code>null</code>. * @throws IOException If an I/O error occurs. */ private void copyFileToStream(File file, OutputStream out, TransferStatus status, LongRange range) throws IOException { LOG.info("Downloading '" + FileUtil.getShortPath(file) + "' to " + status.getPlayer()); final int bufferSize = 16 * 1024; // 16 Kbit InputStream in = new BufferedInputStream(new FileInputStream(file), bufferSize); try { byte[] buf = new byte[bufferSize]; long bitrateLimit = 0; long lastLimitCheck = 0; while (true) { long before = System.currentTimeMillis(); int n = in.read(buf); if (n == -1) { break; } out.write(buf, 0, n); // Don't sleep if outside range. if (range != null && !range.containsLong(status.getBytesSkipped() + status.getBytesTransfered())) { status.addBytesSkipped(n); continue; } status.addBytesTransfered(n); long after = System.currentTimeMillis(); // Calculate bitrate limit every 5 seconds. if (after - lastLimitCheck > 5000) { bitrateLimit = 1024L * settingsService.getDownloadBitrateLimit() / Math.max(1, statusService.getAllDownloadStatuses().size()); lastLimitCheck = after; } // Sleep for a while to throttle bitrate. if (bitrateLimit != 0) { long sleepTime = 8L * 1000 * bufferSize / bitrateLimit - (after - before); if (sleepTime > 0L) { try { Thread.sleep(sleepTime); } catch (Exception x) { LOG.warn("Failed to sleep.", x); } } } } } finally { out.flush(); IOUtils.closeQuietly(in); } } public static String UTF8 (String s) { byte bytes[]=EncodingUtils.getBytes(s,"UTF-8"); return new String(bytes); } public static String cp866 (String s) { byte bytes[]=EncodingUtils.getBytes(s,"cp866"); return new String(bytes); } public static String iso (String s) { byte bytes[]=EncodingUtils.getBytes(s,"ISO-8859-1"); return new String(bytes); } /** * Writes a file or a directory structure to a zip output stream. File entries in the zip file are relative * to the given root. * * @param out The zip output stream. * @param root The root of the directory structure. Used to create path information in the zip file. * @param file The file or directory to zip. * @param status The download status. * @param range The byte range, may be <code>null</code>. * @throws IOException If an I/O error occurs. */ private void zip(ZipOutputStream out, File root, File file, TransferStatus status, LongRange range) throws IOException { // Exclude all hidden files starting with a "." if (file.getName().startsWith(".")) { return; } String zipName = file.getCanonicalPath().substring(root.getCanonicalPath().length() + 1); if (file.isFile()) { status.setFile(file); ZipEntry zipEntry = new ZipEntry(zipName); zipEntry.setSize(file.length()); zipEntry.setCompressedSize(file.length()); zipEntry.setCrc(computeCrc(file)); out.putNextEntry(zipEntry); copyFileToStream(file, out, status, range); out.closeEntry(); } else { ZipEntry zipEntry = new ZipEntry(zipName + '/'); zipEntry.setSize(0); zipEntry.setCompressedSize(0); zipEntry.setCrc(0); out.putNextEntry(zipEntry); out.closeEntry(); File[] children = FileUtil.listFiles(file); for (File child : children) { zip(out, root, child, status, range); } } } /** * Computes the CRC checksum for the given file. * * @param file The file to compute checksum for. * @return A CRC32 checksum. * @throws IOException If an I/O error occurs. */ private long computeCrc(File file) throws IOException { CRC32 crc = new CRC32(); InputStream in = new FileInputStream(file); try { byte[] buf = new byte[8192]; int n = in.read(buf); while (n != -1) { crc.update(buf, 0, n); n = in.read(buf); } } finally { in.close(); } return crc.getValue(); } public void setPlayerService(PlayerService playerService) { this.playerService = playerService; } public void setStatusService(StatusService statusService) { this.statusService = statusService; } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } public void setPlaylistService(PlaylistService playlistService) { this.playlistService = playlistService; } public void setSettingsService(SettingsService settingsService) { this.settingsService = settingsService; } public void setMediaFileService(MediaFileService mediaFileService) { this.mediaFileService = mediaFileService; } }
MadMarty/madsonic-server-5.0
madsonic-main/src/main/java/net/sourceforge/subsonic/controller/DownloadController.java
Java
gpl-3.0
19,776
/* @license * This file is part of the Game Closure SDK. * * The Game Closure SDK is free software: you can redistribute it and/or modify * it under the terms of the Mozilla Public License v. 2.0 as published by Mozilla. * The Game Closure SDK 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 * Mozilla Public License v. 2.0 for more details. * You should have received a copy of the Mozilla Public License v. 2.0 * along with the Game Closure SDK. If not, see <http://mozilla.org/MPL/2.0/>. */ #ifndef JS_PLUGINS_H #define JS_PLUGINS_H #include "js/js.h" using v8::ObjectTemplate; using v8::Handle; Handle<ObjectTemplate> js_plugins_get_template(); #endif
jishnu7/native-android
gradleops/AndroidSeed/tealeaf/src/main/jni/js/js_plugins.h
C
gpl-3.0
807
/// <reference path="../../observable.ts"/> /// <reference path="../../concurrency/scheduler.ts" /> module Rx { export interface Observable<T> { /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observeOn(scheduler: IScheduler): Observable<T>; } } (function () { var o : Rx.Observable<string>; o = o.observeOn(Rx.Scheduler.async); });
tohshige/test
used12_1801_bak/node_modules/rx/ts/core/linq/observable/observeon.ts
TypeScript
gpl-3.0
863
<?php /** * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2013-06-10 at 11:10:20. */ class SpecialtyTypeTest extends PHPUnit_Framework_TestCase { /** * @var SpecialtyType */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new SpecialtyType; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers SpecialtyType::model * @todo Implement testModel(). */ public function testModel() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers SpecialtyType::tableName * @todo Implement testTableName(). */ public function testTableName() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers SpecialtyType::rules * @todo Implement testRules(). */ public function testRules() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers SpecialtyType::relations * @todo Implement testRelations(). */ public function testRelations() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers SpecialtyType::attributeLabels * @todo Implement testAttributeLabels(). */ public function testAttributeLabels() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @covers SpecialtyType::search * @todo Implement testSearch(). */ public function testSearch() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } }
openeyeswales/OpenEyes
protected/tests/unit/models/SpecialtyTypeTest.php
PHP
gpl-3.0
2,499
<?php /** * @package omeka * @subpackage neatline * @copyright 2014 Rector and Board of Visitors, University of Virginia * @license http://www.apache.org/licenses/LICENSE-2.0.html */ class NeatlineRecordTableTest_QueryRecordsFilterHasDate extends Neatline_Case_Default { /** * `hasDate` ~ Match records with start and/or end dates. */ public function testFilterHasSlug() { $exhibit = $this->_exhibit(); $record1 = new NeatlineRecord($exhibit); $record2 = new NeatlineRecord($exhibit); $record3 = new NeatlineRecord($exhibit); $record4 = new NeatlineRecord($exhibit); $record1->start_date = '2014'; // Start $record2->end_date = '2015'; // End $record3->start_date = '2014'; // Both $record3->end_date = '2015'; // Both $record1->added = '2004-01-01'; $record2->added = '2003-01-01'; $record3->added = '2002-01-01'; $record4->added = '2001-01-01'; $record1->save(); $record2->save(); $record3->save(); $record4->save(); // Query for `hasDate`. $result = $this->_records->queryRecords(array( 'exhibit_id' => $exhibit->id, 'hasDate' => true )); $this->assertEquals($result['records'][0]['id'], $record1->id); $this->assertEquals($result['records'][1]['id'], $record2->id); $this->assertEquals($result['records'][2]['id'], $record3->id); $this->assertCount(3, $result['records']); } }
sgbalogh/peddler_clone5
plugins/Neatline/tests/phpunit/tests/unit/NeatlineRecordTable/QueryRecords/FilterHasDateTest.php
PHP
gpl-3.0
1,548
#ifndef FUNCMINIMIZERFACTORYTEST_H_ #define FUNCMINIMIZERFACTORYTEST_H_ #include <cxxtest/TestSuite.h> #include "MantidAPI/FuncMinimizerFactory.h" #include "MantidAPI/IFuncMinimizer.h" #include "MantidAPI/FrameworkManager.h" #include "MantidAPI/IFunction.h" #include "MantidKernel/System.h" #include <sstream> using namespace Mantid; using namespace Mantid::API; class FuncMinimizerFactoryTest_A : public IFuncMinimizer { public: FuncMinimizerFactoryTest_A() { declareProperty("paramA", 0.0); declareProperty("paramB", 0.0); } /// Overloading base class methods std::string name() const override { return "Boevs"; } bool iterate(size_t) override { return true; } int hasConverged() { return 101; } double costFunctionVal() override { return 5.0; } void initialize(API::ICostFunction_sptr, size_t) override {} }; DECLARE_FUNCMINIMIZER(FuncMinimizerFactoryTest_A, nedtur) class FuncMinimizerFactoryTest : public CxxTest::TestSuite { public: // This pair of boilerplate methods prevent the suite being created statically // This means the constructor isn't called when running other tests static FuncMinimizerFactoryTest *createSuite() { return new FuncMinimizerFactoryTest(); } static void destroySuite(FuncMinimizerFactoryTest *suite) { delete suite; } FuncMinimizerFactoryTest() { Mantid::API::FrameworkManager::Instance(); } void testCreateFunction() { IFuncMinimizer *minimizerA = FuncMinimizerFactory::Instance().createUnwrapped("nedtur"); TS_ASSERT(minimizerA); TS_ASSERT(minimizerA->name().compare("Boevs") == 0); delete minimizerA; } void test_createMinimizer_setAllProperties() { auto minimizer = FuncMinimizerFactory::Instance().createMinimizer( "nedtur, paramA= 3.14, paramB = 2.73"); TS_ASSERT(minimizer); TS_ASSERT(minimizer->existsProperty("paramA")); TS_ASSERT(minimizer->existsProperty("paramB")); double a = minimizer->getProperty("paramA"); double b = minimizer->getProperty("paramB"); TS_ASSERT_EQUALS(a, 3.14); TS_ASSERT_EQUALS(b, 2.73); } void test_createMinimizer_defaultPropeties() { auto minimizer = FuncMinimizerFactory::Instance().createMinimizer("nedtur"); TS_ASSERT(minimizer); TS_ASSERT(minimizer->existsProperty("paramA")); TS_ASSERT(minimizer->existsProperty("paramB")); double a = minimizer->getProperty("paramA"); double b = minimizer->getProperty("paramB"); TS_ASSERT_EQUALS(a, 0.0); TS_ASSERT_EQUALS(b, 0.0); } void test_createMinimizer_setOneProperty() { auto minimizer = FuncMinimizerFactory::Instance().createMinimizer( "nedtur, paramB = 2.73"); TS_ASSERT(minimizer); TS_ASSERT(minimizer->existsProperty("paramA")); TS_ASSERT(minimizer->existsProperty("paramB")); double a = minimizer->getProperty("paramA"); double b = minimizer->getProperty("paramB"); TS_ASSERT_EQUALS(a, 0.0); TS_ASSERT_EQUALS(b, 2.73); } }; #endif /*FUNCMINIMIZERFACTORYTEST_H_*/
dymkowsk/mantid
Framework/API/test/FuncMinimizerFactoryTest.h
C
gpl-3.0
2,994
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "InformationElements" * found in "../asn/InformationElements.asn" * `asn1c -fcompound-names -fnative-types` */ #ifndef _ProtocolErrorMoreInformation_H_ #define _ProtocolErrorMoreInformation_H_ #include <asn_application.h> /* Including external dependencies */ #include <NULL.h> #include "IdentificationOfReceivedMessage.h" #include <constr_CHOICE.h> #include <constr_SEQUENCE.h> #ifdef __cplusplus extern "C" { #endif /* Dependencies */ typedef enum ProtocolErrorMoreInformation__diagnosticsType_PR { ProtocolErrorMoreInformation__diagnosticsType_PR_NOTHING, /* No components present */ ProtocolErrorMoreInformation__diagnosticsType_PR_type1, ProtocolErrorMoreInformation__diagnosticsType_PR_spare } ProtocolErrorMoreInformation__diagnosticsType_PR; typedef enum ProtocolErrorMoreInformation__diagnosticsType__type1_PR { ProtocolErrorMoreInformation__diagnosticsType__type1_PR_NOTHING, /* No components present */ ProtocolErrorMoreInformation__diagnosticsType__type1_PR_asn1_ViolationOrEncodingError, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_messageTypeNonexistent, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_messageNotCompatibleWithReceiverState, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_ie_ValueNotComprehended, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_conditionalInformationElementError, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_messageExtensionNotComprehended, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_spare1, ProtocolErrorMoreInformation__diagnosticsType__type1_PR_spare2 } ProtocolErrorMoreInformation__diagnosticsType__type1_PR; /* ProtocolErrorMoreInformation */ typedef struct ProtocolErrorMoreInformation { struct ProtocolErrorMoreInformation__diagnosticsType { ProtocolErrorMoreInformation__diagnosticsType_PR present; union ProtocolErrorMoreInformation__diagnosticsType_u { struct ProtocolErrorMoreInformation__diagnosticsType__type1 { ProtocolErrorMoreInformation__diagnosticsType__type1_PR present; union ProtocolErrorMoreInformation__diagnosticsType__type1_u { NULL_t asn1_ViolationOrEncodingError; NULL_t messageTypeNonexistent; IdentificationOfReceivedMessage_t messageNotCompatibleWithReceiverState; IdentificationOfReceivedMessage_t ie_ValueNotComprehended; IdentificationOfReceivedMessage_t conditionalInformationElementError; IdentificationOfReceivedMessage_t messageExtensionNotComprehended; NULL_t spare1; NULL_t spare2; } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } type1; NULL_t spare; } choice; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } diagnosticsType; /* Context for parsing across buffer boundaries */ asn_struct_ctx_t _asn_ctx; } ProtocolErrorMoreInformation_t; /* Implementation */ extern asn_TYPE_descriptor_t asn_DEF_ProtocolErrorMoreInformation; #ifdef __cplusplus } #endif #endif /* _ProtocolErrorMoreInformation_H_ */ #include <asn_internal.h>
E3V3A/snoopsnitch
contrib/libosmo-asn1-rrc/include/ProtocolErrorMoreInformation.h
C
gpl-3.0
3,159
package com.redhat.lightblue.client.expression.update; import java.util.Collection; import com.redhat.lightblue.client.util.JSON; /** * created by Michael White 10/10/2014 */ public class SetUpdate implements Update { private final PathValuePair[] pathValuePairs; public SetUpdate(PathValuePair... statements) { pathValuePairs = statements; } public SetUpdate(Collection<PathValuePair> statements) { if (statements != null) { pathValuePairs = statements.toArray(new PathValuePair[statements.size()]); } else { pathValuePairs = null; } } @Override public String toJson() { StringBuilder json = new StringBuilder("{"); json.append(JSON.toJson("$set")).append(":{"); for (int index = 0; index < pathValuePairs.length; index++) { json.append(pathValuePairs[index].toJson()); if ((this.pathValuePairs.length - index) > 1) { json.append(", "); } } json.append("}}"); return json.toString(); } }
vritant/lightblue-client
core/src/main/java/com/redhat/lightblue/client/expression/update/SetUpdate.java
Java
gpl-3.0
1,085
/* * InfraRecorder - CD/DVD burning software * Copyright (C) 2006-2012 Christian Kindahl * * 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/>. */ #pragma once #include "resource.h" class CBurnAdvancedPage : public CPropertyPageImpl<CBurnAdvancedPage> { private: CTrackBarCtrl m_VariRecTrackBar; bool Translate(); public: enum { IDD = IDD_PROPPAGE_BURNIMAGEADVANCED }; CBurnAdvancedPage(); ~CBurnAdvancedPage(); bool OnApply(); void OnHelp(); BEGIN_MSG_MAP(CBurnAdvancedPage) MESSAGE_HANDLER(WM_INITDIALOG,OnInitDialog) MESSAGE_HANDLER(WM_SHOWWINDOW,OnShowWindow) MESSAGE_HANDLER(WM_HSCROLL,OnHScroll) CHAIN_MSG_MAP(CPropertyPageImpl<CBurnAdvancedPage>) END_MSG_MAP() LRESULT OnInitDialog(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL &bHandled); LRESULT OnShowWindow(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL &bHandled); LRESULT OnHScroll(UINT uMsg,WPARAM wParam,LPARAM lParam,BOOL &bHandled); };
kindahl/infrarecorder
src/app/dialog/burn_advanced_page.hh
C++
gpl-3.0
1,634
/* * This file is part of AtlasMapper server and clients. * * Copyright (C) 2011 Australian Institute of Marine Science * * Contact: Gael Lafond <[email protected]> * * 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/>. */ package au.gov.aims.atlasmapperserver.layerConfig; import au.gov.aims.atlasmapperserver.ConfigManager; import au.gov.aims.atlasmapperserver.Utils; import au.gov.aims.atlasmapperserver.annotation.ConfigField; import java.util.Arrays; public class WMSLayerConfig extends AbstractLayerConfig { @ConfigField private Boolean wmsQueryable; @ConfigField private String[] wmsFeatureRequestLayers; public WMSLayerConfig(ConfigManager configManager) { super(configManager); } public Boolean isWmsQueryable() { return this.wmsQueryable; } public void setWmsQueryable(Boolean wmsQueryable) { this.wmsQueryable = wmsQueryable; } public String[] getWmsFeatureRequestLayers() { return wmsFeatureRequestLayers; } public void setWmsFeatureRequestLayers(String[] wmsFeatureRequestLayers) { this.wmsFeatureRequestLayers = wmsFeatureRequestLayers; } public String toString() { return "WMSLayerConfig {\n" + (Utils.isBlank(this.getLayerId()) ? "" : " layerId=" + this.getLayerId() + "\n") + (Utils.isBlank(this.getLayerName()) ? "" : " layerName=" + this.getLayerName() + "\n") + (this.getAliasIds()==null ? "" : " aliasIds=" + Arrays.toString(this.getAliasIds()) + "\n") + (Utils.isBlank(this.getTitle()) ? "" : " title=" + this.getTitle() + "\n") + (Utils.isBlank(this.getDescription()) ? "" : " description=" + this.getDescription() + "\n") + (this.getLayerBoundingBox()==null ? "" : " layerBoundingBox=" + Arrays.toString(this.getLayerBoundingBox()) + "\n") + (this.getInfoHtmlUrls()==null ? "" : " infoHtmlUrls=" + Arrays.toString(this.getInfoHtmlUrls()) + "\n") + (this.isIsBaseLayer()==null ? "" : " isBaseLayer=" + this.isIsBaseLayer() + "\n") + (this.isHasLegend()==null ? "" : " hasLegend=" + this.isHasLegend() + "\n") + (Utils.isBlank(this.getLegendGroup()) ? "" : " legendGroup=" + this.getLegendGroup() + "\n") + (Utils.isBlank(this.getLegendTitle()) ? "" : " legendTitle=" + this.getLegendTitle() + "\n") + (wmsQueryable==null ? "" : " wmsQueryable=" + wmsQueryable + "\n") + (Utils.isBlank(this.getTreePath()) ? "" : " treePath=" + this.getTreePath() + "\n") + (wmsFeatureRequestLayers==null ? "" : " wmsFeatureRequestLayers=" + Arrays.toString(wmsFeatureRequestLayers) + "\n") + (this.getStyles()==null ? "" : " styles=" + this.getStyles() + "\n") + (this.getOptions()==null ? "" : " options=" + this.getOptions() + "\n") + (this.isSelected()==null ? "" : " selected=" + this.isSelected() + "\n") + '}'; } }
windrobin/atlasmapper
src/main/java/au/gov/aims/atlasmapperserver/layerConfig/WMSLayerConfig.java
Java
gpl-3.0
3,514
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * mod_lesson essay assessed event. * * @package mod_lesson * @copyright 2014 Adrian Greeve <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace mod_lesson\event; defined('MOODLE_INTERNAL') || die(); /** * mod_lesson essay assessed event class. * * @property-read array $other { * Extra information about the event. * * @type int lessonid The ID of the lesson. * @type int attemptid The ID for the attempt. * } * * @package mod_lesson * @copyright 2014 Adrian Greeve <[email protected]> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class essay_assessed extends \core\event\base { /** * Init method. * * @return void */ protected function init() { $this->data['crud'] = 'u'; $this->data['edulevel'] = self::LEVEL_TEACHING; $this->data['objecttable'] = 'lesson_grades'; } /** * Returns description of what happened. * * @return string */ public function get_description() { return 'User ' . $this->userid . ' has marked the essay ' . $this->other['attemptid'] . ' and recorded a mark ' . $this->objectid . ' in the lesson ' . $this->other['lessonid'] . '.'; } /** * Return legacy data for add_to_log(). * * @return array */ protected function get_legacy_logdata() { $lesson = $this->get_record_snapshot('lesson', $this->other['lessonid']); return array($this->courseid, 'lesson', 'update grade', 'essay.php?id=' . $this->contextinstanceid, $lesson->name, $this->contextinstanceid); } /** * Return localised event name. * * @return string */ public static function get_name() { return get_string('eventessayassessed', 'mod_lesson'); } /** * Get URL related to the action * * @return \moodle_url */ public function get_url() { return new \moodle_url('/mod/lesson/essay.php', array('id' => $this->contextinstanceid)); } /** * Custom validation. * * @throws \coding_exception * @return void */ protected function validate_data() { if (!isset($this->relateduserid)) { throw new \coding_exception('relateduserid is a mandatory property.'); } if (!isset($this->other['lessonid'])) { throw new \coding_exception('lessonid is a mandatory property.'); } if (!isset($this->other['attemptid'])) { throw new \coding_exception('attemptid is a mandatory property.'); } } }
jethac/moodle
mod/lesson/classes/event/essay_assessed.php
PHP
gpl-3.0
3,354
from tvdb_api.tvdb_api import Tvdb from tvrage_api.tvrage_api import TVRage import requests INDEXER_TVDB = 1 INDEXER_TVRAGE = 2 initConfig = {} indexerConfig = {} initConfig['valid_languages'] = [ "da", "fi", "nl", "de", "it", "es", "fr", "pl", "hu", "el", "tr", "ru", "he", "ja", "pt", "zh", "cs", "sl", "hr", "ko", "en", "sv", "no"] initConfig['langabbv_to_id'] = { 'el': 20, 'en': 7, 'zh': 27, 'it': 15, 'cs': 28, 'es': 16, 'ru': 22, 'nl': 13, 'pt': 26, 'no': 9, 'tr': 21, 'pl': 18, 'fr': 17, 'hr': 31, 'de': 14, 'da': 10, 'fi': 11, 'hu': 19, 'ja': 25, 'he': 24, 'ko': 32, 'sv': 8, 'sl': 30} indexerConfig[INDEXER_TVDB] = { 'id': INDEXER_TVDB, 'name': 'theTVDB', 'module': Tvdb, 'api_params': {'apikey': 'F9C450E78D99172E', 'language': 'en', 'useZip': True, }, 'session': requests.Session() } indexerConfig[INDEXER_TVRAGE] = { 'id': INDEXER_TVRAGE, 'name': 'TVRage', 'module': TVRage, 'api_params': {'apikey': 'Uhewg1Rr0o62fvZvUIZt', 'language': 'en', }, 'session': requests.Session() } # TVDB Indexer Settings indexerConfig[INDEXER_TVDB]['trakt_id'] = 'tvdb_id' indexerConfig[INDEXER_TVDB]['xem_origin'] = 'tvdb' indexerConfig[INDEXER_TVDB]['icon'] = 'thetvdb16.png' indexerConfig[INDEXER_TVDB]['scene_loc'] = 'http://sickragetv.github.io/sb_tvdb_scene_exceptions/exceptions.txt' indexerConfig[INDEXER_TVDB]['show_url'] = 'http://thetvdb.com/?tab=series&id=' indexerConfig[INDEXER_TVDB]['base_url'] = 'http://thetvdb.com/api/%(apikey)s/series/' % indexerConfig[INDEXER_TVDB]['api_params'] # TVRAGE Indexer Settings indexerConfig[INDEXER_TVRAGE]['trakt_id'] = 'tvrage_id' indexerConfig[INDEXER_TVRAGE]['xem_origin'] = 'rage' indexerConfig[INDEXER_TVRAGE]['icon'] = 'tvrage16.png' indexerConfig[INDEXER_TVRAGE]['scene_loc'] = 'http://sickragetv.github.io/sr_tvrage_scene_exceptions/exceptions.txt' indexerConfig[INDEXER_TVRAGE]['show_url'] = 'http://tvrage.com/shows/id-' indexerConfig[INDEXER_TVRAGE]['base_url'] = 'http://tvrage.com/showinfo.php?key=%(apikey)s&sid=' % indexerConfig[INDEXER_TVRAGE]['api_params']
keen99/SickRage
sickbeard/indexers/indexer_config.py
Python
gpl-3.0
2,154
/* * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * -Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Oracle nor the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF * THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that Software is not designed, licensed or * intended for use in the design, construction, operation or * maintenance of any nuclear facility. */ package examples.rmisocfac; import java.io.*; import java.net.*; import java.rmi.server.*; public class XorClientSocketFactory implements RMIClientSocketFactory, Serializable { private final byte pattern; public XorClientSocketFactory(byte pattern) { this.pattern = pattern; } public Socket createSocket(String host, int port) throws IOException { return new XorSocket(host, port, pattern); } public int hashCode() { return (int) pattern; } public boolean equals(Object obj) { return (getClass() == obj.getClass() && pattern == ((XorClientSocketFactory) obj).pattern); } }
DeanAaron/jdk8
jdk8zh_cn/docs/technotes/guides/rmi/socketfactory/code/XorClientSocketFactory.java
Java
gpl-3.0
2,467
/** * Required to undo YUI resets that override input size */ input[type=text],input[type=password],textarea{width:auto;} /* Fix for YUI overriding styles */ strong{font-style:inherit;}em{font-weight:inherit;} /** * General */ th, td, a img {border-width:0;} acronym, abbr {cursor: help;} .dir-ltr, .mdl-left, .dir-rtl .mdl-right {text-align: left;} .dir-rtl, .mdl-right, .dir-rtl .mdl-left {text-align: right;} #add, #remove, .centerpara, .mdl-align {text-align: center;} a.dimmed, a.dimmed:link, a.dimmed:visited, a.dimmed_text, a.dimmed_text:link, a.dimmed_text:visited, .dimmed_text, .dimmed_text a, .dimmed_text a:link, .dimmed_text a:visited, .usersuspended, .usersuspended a, .usersuspended a:link, .usersuspended a:visited, .dimmed_category, .dimmed_category a { color: #AAA; } .activity.label .dimmed_text { opacity: 0.5; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; filter: alpha(opacity=50); } .unlist, .unlist li, .inline-list, .inline-list li, .block .list, .block .list li, .sitetopic .section li.activity, .course-content .section li.activity, .tabtree li {list-style: none;margin:0;padding:0;} .course-content .current {background:#E3E3E3;} .inline, .inline-list li {display: inline;} .notifytiny {font-size:0.7em;} .notifytiny li, .notifytiny td {font-size:100%;} .red, .notifyproblem {color:#660000;} .green, .notifysuccess {color:#006600;} .reportlink {text-align:right;} a.autolink.glossary:hover {cursor: help;} /* Block which is hidden if javascript enabled, prevents fickering visible when JS from footer used! */ .collapsibleregioncaption {white-space: nowrap;} .collapsibleregioncaption img {vertical-align: middle;} .jsenabled .hiddenifjs {display: none;} .visibleifjs {display: none;} .jsenabled .visibleifjs {display: inline;} .jsenabled .collapsibleregion {overflow:hidden;} .jsenabled .collapsed .collapsibleregioninner {visibility: hidden;} .yui-overlay .yui-widget-bd {background-color:#FFEE69;border:1px solid #A6982B;border-top-color: #D4C237;color:#000000;left:0;padding:2px 5px;position:relative;top:0;z-index:1;} .clearer {background:transparent;border-width:0;clear:both;display:block;height:1px;margin:0;padding:0;} .clearfix:after {clear: both;content: ".";display: block;height: 0;min-width: 0;visibility: hidden;} .bold, .warning, .errorbox .title, .pagingbar .title, .pagingbar .thispage, .headingblock {font-weight: bold;} img.resize {height: 1em;width: 1em;} .block img.resize, .breadcrumb img.resize {height: 0.9em;width: 0.8em;} /* Icon styles */ img.icon {height:16px;vertical-align:text-bottom;width:16px;padding-right: 6px;} .dir-rtl img.icon {padding-left: 6px; padding-right: 0; } img.iconsmall {height:12px;margin-right:3px;vertical-align:middle;width:12px;} img.iconhelp, .helplink img {height:16px; padding-left:3px;vertical-align:text-bottom;width:16px;} .dir-rtl img.iconhelp, .dir-rtl .helplink img {padding-right: 3px; padding-left: 0; } img.iconlarge {height: 24px; width: 24px; vertical-align:middle;} img.iconsort { vertical-align: text-bottom; padding-left: .3em; margin-bottom: .15em;} .dir-rtl img.iconsort { padding-right: .3em; padding-left: 0;} img.icontoggle {height:17px;vertical-align:middle;width:50px;} img.iconkbhelp {height:17px;width:49px;} img.icon-pre, .dir-rtl img.icon-post { padding-right: 3px; padding-left: 0; } img.icon-post, .dir-rtl img.icon-pre { padding-left: 3px; padding-right: 0; } .categorybox .category {font-size:1.2em;font-weight:bold;} .generalbox {border:1px solid;} .boxaligncenter {margin-left:auto;margin-right:auto;} .boxalignright {margin-left:auto;margin-right:0;} .boxalignleft {margin-left:0;margin-right:auto;} .boxwidthnarrow {width: 30%;} .boxwidthnormal {width: 50%;} .boxwidthwide {width: 80%;} .buttons .singlebutton, .buttons .singlebutton form, .buttons .singlebutton div {display: inline;} .buttons .singlebutton input {margin:20px 5px;} .headermain {font-weight:bold;} #maincontent {display: block;height: 1px;overflow: hidden;} img.uihint {cursor: help;} #addmembersform table {margin-left: auto;margin-right: auto;} .formtable tbody th, .generaltable th.header {vertical-align: top;} .flexible th {white-space: nowrap;} .cell {vertical-align: top;} img.emoticon {vertical-align: middle;width: 15px;height: 15px;} form.popupform, form.popupform div {display: inline;} .arrow_button input {overflow:hidden;} .action-icon img.smallicon { vertical-align: text-bottom; margin-left: .45em;} .dir-rtl .action-icon img.smallicon { margin-right: .45em; margin-left: 0;} h1.main img, h2.main img, h3.main img, h4.main img, h5.main img, h6.main img {vertical-align: middle;} /** The 1-pixel padding is there to avoid phantom scroll bars on OS X (FF, Safari and Chrome)**/ .no-overflow {overflow:auto;padding-bottom:1px;} .pagelayout-report .no-overflow {overflow:visible;} .no-overflow > .generaltable {margin-bottom:0;} .ie6 .no-overflow {width:100%;} /** IE6 float + background bug solution **/ .ie6 li.section {line-height:1.2em;width:100%;} /** * Accessibility features */ /*Accessibility: text 'seen' by screen readers but not visual users. */ .accesshide {position:absolute;left:-10000px;font-weight:normal;font-size:1em;} .dir-rtl .accesshide {top:-30000px;left:auto;} span.hide, div.hide {display:none;} .invisiblefieldset {display:inline;border-width:0;padding:0;margin:0;} /*Accessibility: Skip block link, for keyboard-only users. */ a.skip-block, a.skip {position: absolute;top: -1000em;font-size: 0.85em;text-decoration:none;} a.skip-block:focus, a.skip-block:active, a.skip:focus, a.skip:active {position: static;display: block;} .skip-block-to {display: block;height: 1px;overflow: hidden;} /* Accessibility: only certain fonts support Unicode chars like &#x25BA; in IE6 */ .arrow, .arrow_button input {font-family: Arial,Helvetica,Courier,sans-serif;} /** * Header */ .headermain {float:left;margin:15px;font-size:2.3em;} .headermenu {float:right;margin:10px;font-size:0.8em;text-align:right;} #course-header {clear:both;} /** * Navbar */ .navbar {clear:both;overflow:hidden;} .ie6 .navbar {overflow:hidden;height:100%;} .breadcrumb {float:left;} .navbutton {text-align:right;} .breadcrumb ul {padding:0;margin:0;text-indent:0;list-style:none;} .navbutton {float: right;} .breadcrumb li, .navbutton div, .navbutton form {display:inline;} /** * Footer */ #page-footer {text-align:center;font-size:0.9em;} #page-footer .homelink {margin: 1em 0;} #page-footer .homelink a {padding-left:1em;padding-right:1em;} #page-footer .logininfo, #page-footer .sitelink, #page-footer .helplink {margin:0px 10px;} #page-footer .performanceinfo {text-align:center;margin:10px 20%;} #page-footer .performanceinfo span {display:block;} #page-footer .validators {margin-top:40px;padding-top:5px;border-top: 1px dotted gray;} #page-footer .validators ul {margin:0px;padding:0px;list-style-type:none;} #page-footer .validators ul li {display:inline;margin-right:10px;margin-left:10px;} .performanceinfo .cachesused {margin-top:1em;} .performanceinfo .cachesused .cache-stats-heading {font-weight: bold;text-decoration: underline;font-size:110%;} .performanceinfo .cachesused .cache-definition-stats {font-weight:bold;margin-top:0.3em;} .performanceinfo .cachesused .cache-store-stats {text-indent: 1em;} .performanceinfo .cachesused .cache-total-stats {font-weight:bold;margin-top:0.3em;} #course-footer {clear:both;} /** * Tabs */ .tabtree {position:relative;margin-bottom:3.5em;} .tabtree li {display:inline;} .tabtree ul {margin:5px;} .tabtree ul li.here ul {position:absolute;top:100%;width:100%;} .tabtree ul li.here .empty {display:none;} /** * Mforms */ .mform fieldset {border:1px solid;} .mform fieldset fieldset {border-width:0px;} .mform fieldset legend {font-weight:bold;margin-left:0.5em;} .mform fieldset div {margin:10px;margin-top:0;} .mform fieldset div div {margin:0;} .mform fieldset .advancedbutton {text-align:right;} .mform fieldset.hidden {border-width:0;} .mform fieldset.group {margin-bottom: 0} .mform fieldset.error {border: 1px solid #A00;} .mform .fitem {width:100%;overflow:hidden;margin-top:5px;margin-bottom:1px;clear:right;} .mform .fitem .fitemtitle {width:15%;text-align:right;float:left;} .mform .fitem .fitemtitle div {display: inline;} .mform .fitem .felement {border-width: 0;width:80%;margin-left:16%;} .mform .fitem fieldset.felement {margin-left:15%;padding-left:1%;margin-bottom:0} .dir-rtl .mform .fitem fieldset.felement {padding-right: 1%;margin-right: 15%;} .mform .error, .mform .required {color:#A00;} .mform .required .fgroup span label {color:#000;} .mform .fdescription.required {color:#A00;text-align:right;} .mform .fpassword .unmask {display:inline;margin-left:0.5em;} .mform .ftextarea #id_alltext {width: 100%;} .mform ul.file-list {padding:0;margin:0;list-style:none;} .mform label .req, .mform label .adv {cursor: help;} .mform .fcheckbox input {margin-left: 0;} .mform .fitem fieldset.fgroup label, .mform .fradio label, .mform .fcheckbox label, .mform fieldset.fdate_selector label {display:inline;float: none;width: auto;} .mform .ftags label.accesshide {display: block;position: static;} .mform .ftags select {margin-bottom: 0.7em;min-width: 22em;} .mform .helplink img { margin: 0 0 0 .45em; padding: 0;} .dir-rtl .mform .helplink img { margin: 0 .45em 0 0; padding: 0;} .mform legend .helplink img { margin-right: .2em; } .dir-rtl .mform legend .helplink img { margin: 0 .45em 0 .2em; } .singleselect label { margin-right: .3em; } .dir-rtl .singleselect label { margin-left: .3em; margin-right: 0; } input#id_externalurl {direction:ltr;} /** Browser corrections for mforms **/ .ie .mform .fitem .felement {margin-left:0;text-align:left;float:left;} /** Fix IE double margin + float bugs **/ .ie .mform .fitem .fitemtitle {padding-right:1em;} #portfolio-add-button {display:inline;} /** * phpinfo styles */ .phpinfo .center {text-align: center;} .phpinfo .center table {margin-left: auto;margin-right: auto;text-align: left;border-collapse: collapse;} .phpinfo .center th {text-align: center;} .phpinfo .e, .phpinfo .v, .phpinfo .h {border: 1px solid #000000;font-size: 0.8em;vertical-align: baseline;color: #000000;background-color: #cccccc;} .phpinfo .e {background-color: #ccccff;font-weight: bold;} .phpinfo .h {background-color: #9999cc;font-weight: bold;} /** * Blogs */ .addbloglink {text-align: center;} .blog_entry .audience {text-align: right;padding-right: 4px;} .blog_entry .tags {margin-top: 15px;} .blog_entry .tags .action-icon img.smallicon { height: 16px; width: 16px; } .blog_entry .content {margin-left: 43px;} /** * Group */ #page-group-index #groupeditform {text-align: center;} #doc-contents h1 {margin: 1em 0 0 0;} #doc-contents ul {margin: 0;padding: 0;width: 90%;} #doc-contents ul li {list-style-type: none;} .groupmanagementtable td {vertical-align: top;} .groupmanagementtable #existingcell, .groupmanagementtable #potentialcell {width: 42%;} .groupmanagementtable #buttonscell {width: 16%;} .groupmanagementtable #buttonscell input {width: 80%;} .groupmanagementtable #removeselect_wrapper, .groupmanagementtable #addselect_wrapper {width: 100%;} .groupmanagementtable #removeselect_wrapper label, .groupmanagementtable #addselect_wrapper label {font-weight: normal;} .dir-rtl .groupmanagementtable p {text-align: right;} #group-usersummary {width: 14em;} .groupselector {margin-top: 3px;margin-bottom: 3px;} /** * Login */ .loginbox {margin:15px;overflow:visible;} .loginbox.twocolumns {margin:15px;} .loginbox h2, .loginbox .subcontent {margin:5px;padding:10px;text-align:center;} .loginbox .loginpanel .desc {margin:0;padding:0;margin-bottom:5px;} .loginbox .signuppanel .subcontent {text-align:left;} .dir-rtl .loginbox .signuppanel .subcontent {text-align: right;} .loginbox .loginsub {margin-left:0;margin-right:0;} .loginbox .guestsub, .loginbox .forgotsub, .loginbox .potentialidps {margin:5px 12%;} .loginbox .potentialidps .potentialidplist {margin-left:40%;} .loginbox .potentialidps .potentialidplist div {text-align:left;} .loginbox .loginform {margin-top:1em;text-align:left;} .loginbox .loginform .form-label {float:left;text-align:right;width:44%;direction:rtl; white-space:nowrap;} .dir-rtl .loginbox .loginform .form-label {float:left;text-align:right;width:44%;direction:ltr; white-space:nowrap;} .loginbox .loginform .form-input {float:right;width:55%;} .loginbox .loginform .form-input input {width: 6em;} .loginbox .signupform {margin-top:1em;text-align:center;} .loginbox.twocolumns .loginpanel {float:left;width:49.5%;border-right: 1px solid;margin-bottom:-2000px;padding-bottom:2000px;} .loginbox.twocolumns .signuppanel {float:right;width:50%;margin-bottom:-2000px;padding-bottom:2000px;} .loginbox .potentialidp .smallicon { vertical-align: text-bottom; margin: 0 .3em; } /** * Notes */ .notepost {margin-bottom: 1em;} .notepost .userpicture {float: left;margin-right: 5px;} .notepost .content, .notepost .footer {clear: both;} .notesgroup {margin-left:20px;} /** * My Moodle */ .path-my .coursebox .overview {margin: 15px 30px 10px 30px;} .path-my .coursebox .info {float: none; margin: 0;} /** * Logs */ .logtable th {text-align:left;} /** * Modules */ .mod_introbox {border:1px solid;padding:10px;} table.mod_index {width:100%;} /** * Help */ #help_icon_tooltip div.bd {width: 35em;} #help hr {border: none;height: 1px;background: #ccc;} #help .center {text-align: center;} #help .moreinfo {text-align: right;} #help .indent {margin-left: 40px;} #help .indent-big {margin-left: 160px;margin-right: 160px;} #help #emoticons{text-align: center;clear:both;width: 300px;margin-right: auto;margin-left:auto;} #help #emoticons ul{list-style-type: none;} #help #emoticons li{margin-bottom: 3px;width: 120px;border-left: 3px solid gray;padding-left: 7px;float: left;} /** * Comments */ .comment-ctrl {font-size: 12px;display: none;margin:0;padding:0;} .comment-ctrl h5 {margin:0;padding: 5px;} .comment-area {max-width: 400px;padding: 5px;} .comment-area textarea {width:100%;overflow:auto;} .comment-area .fd {text-align:right;} .comment-meta span {color:gray;} .comment-link img { vertical-align: text-bottom; } .comment-list {font-size: 11px;overflow:auto;list-style:none;padding:0;margin:0;} .comment-list li {margin: 2px;list-style:none;margin-bottom:5px;clear:both;padding: .3em;position: relative;} .comment-list li.first {display:none} .comment-paging{text-align:center;} .comment-paging .pageno{padding:2px;} .comment-paging .curpage{border:1px solid #CCC;} .comment-message .picture {width: 20px;float:left;} .dir-rtl .comment-message .picture {float:right;} .comment-message .text {margin:0;padding:0;} .comment-message .text p {padding:0;margin:0 18px 0 0;} .comment-delete {position: absolute; top: 0; right: 0;margin: .3em;} .dir-rtl .comment-delete {position: absolute; left: 0; right: auto;margin: .3em;} .comment-delete-confirm {background: #eee; padding: 2px; width: 5em;text-align:center;} .comment-container {float:left;margin: 4px;} .comment-report-selectall{display:none} .comment-link {display:none} .jsenabled .comment-link {display:block} .jsenabled .showcommentsnonjs{display:none} .jsenabled .comment-report-selectall{display:inline} /** * Completion progress report */ .completion-expired {background:#FFDDDD;} .completion-expected {font-size:0.75em;} .completion-sortchoice, .completion-identifyfield {font-size:0.75em;vertical-align:bottom;} .completion-progresscell {text-align:right;} .completion-expired .completion-expected {font-weight:bold;} /** * Tags */ #page-tag-coursetags_edit .coursetag_edit_centered {position: relative;width: 600px;margin: 20px auto;} #page-tag-coursetags_edit .coursetag_edit_row {clear:both;} #page-tag-coursetags_edit .coursetag_edit_row .coursetag_edit_left {float:left;width:50%;text-align:right;} #page-tag-coursetags_edit .coursetag_edit_row .coursetag_edit_right {margin-left:50%;} #page-tag-coursetags_edit .coursetag_edit_input3 {display: none;} #page-tag-coursetags_more .coursetag_more_large {font-size: 120%;} #page-tag-coursetags_more .coursetag_more_small {font-size: 80%;} #page-tag-coursetags_more .coursetag_more_link {font-size: 80%;} #tag-description, #tag-blogs {width:100%;} #tag-management-box {margin-bottom:10px;line-height:20px;} #tag-user-table {padding:3px;clear: both;width:100%;} #tag-user-table:after {content:".";display:block;clear:both;visibility:hidden;height:0;overflow:hidden;} img.user-image {height:100px;width:100px;} #small-tag-cloud-box {width:300px;margin:0 auto;} #big-tag-cloud-box {width:600px;margin:0 auto;float:none;} ul#tag-cloud-list {list-style:none;padding:5px;margin:0;} ul#tag-cloud-list li {margin:0;display:inline;list-style-type:none;} #tag-search-box {text-align:center;margin:10px auto;} #tag-search-results-container {padding:0;width:100%;} #tag-search-results {padding:0;margin: 15px 20% 0 20%;float:left;width:60%;display:block;} #tag-search-results li {width:30%;float:left;padding-left:1%;text-align:left;line-height:20px;padding-right:1%;list-style:none;} span.flagged-tag, span.flagged-tag a {color:#FF0000;} table#tag-management-list {text-align:left;width:100%;} table#tag-management-list td, table#tag-management-list th {vertical-align: middle;text-align: left;padding: 4px;} .tag-management-form {text-align:center;} #relatedtags-autocomplete-container {margin-left:auto;margin-right:auto;min-height:4.6em;width:100%;} #relatedtags-autocomplete {position:relative;display:block;width:60%;margin-left:auto;margin-right:auto;} #relatedtags-autocomplete .yui-ac-content {position:absolute;width:420px;left:20%;border:1px solid #404040;background:#fff;overflow:hidden;z-index:9050;} #relatedtags-autocomplete .ysearchquery {position:absolute;right:10px;color:#808080;z-index:10;} #relatedtags-autocomplete .yui-ac-shadow {position:absolute;margin:.3em;width:100%;background:#a0a0a0;z-index:9049;} #relatedtags-autocomplete ul {padding:0;width:100%;margin:0;list-style-type:none;} #relatedtags-autocomplete li {padding:0 5px;cursor:default;white-space:nowrap;} #relatedtags-autocomplete li.yui-ac-highlight{background:#FFFFCC;} h2.tag-heading, div#tag-description, div#tag-blogs, body.tag .managelink {padding: 5px;} .tag_cloud .s20 {font-size: 1.5em;font-weight: bold;} .tag_cloud .s19 {font-size: 1.5em;} .tag_cloud .s18 {font-size: 1.4em;font-weight: bold;} .tag_cloud .s17 {font-size: 1.4em;} .tag_cloud .s16 {font-size: 1.3em;font-weight: bold;} .tag_cloud .s15 {font-size: 1.3em;} .tag_cloud .s14 {font-size: 1.2em;font-weight: bold;} .tag_cloud .s13 {font-size: 1.2em;} .tag_cloud .s12, .tag_cloud .s11 {font-size: 1.1em;font-weight: bold;} .tag_cloud .s10, .tag_cloud .s9 {font-size: 1.1em;} .tag_cloud .s8, .tag_cloud .s7 {font-size: 1em;font-weight: bold;} .tag_cloud .s6, .tag_cloud .s5 {font-size: 1em;} .tag_cloud .s4, .tag_cloud .s3 {font-size: 0.9em;font-weight: bold;} .tag_cloud .s2, .tag_cloud .s1 {font-size: 0.9em;} .tag_cloud .s0 {font-size: 0.8em;} /* * Backup and Restore CSS */ .path-backup .mform .grouped_settings.section_level {clear:both;} .path-backup .mform .grouped_settings {clear:both;overflow:hidden;} .path-backup .mform .grouped_settings .fitem .fitemtitle {width:40%;padding-right:10px;} .path-backup.dir-rtl .mform .grouped_settings .fitem .fitemtitle {width: 60%;} .path-backup .mform .grouped_settings .fitem .felement {width:50%;} .path-backup.dir-rtl .mform .grouped_settings .fitem .felement {width: 99%;} .path-backup .mform .grouped_settings.section_level .include_setting {width:50%;margin:0;float:left;clear:left;font-weight:bold;} .path-backup.dir-rtl .mform .grouped_settings.section_level .include_setting {float: right; clear: right;} .path-backup .mform .grouped_settings.section_level .normal_setting {width:50%;margin:0;margin-left:50%;} .path-backup.dir-rtl .mform .grouped_settings.section_level .normal_setting {margin:0;} .path-backup .mform .grouped_settings.activity_level .include_setting label {font-weight:normal;} .path-backup.dir-rtl .mform .grouped_settings.activity_level .include_setting label img {float:right;} .path-backup .mform .fitem fieldset.felement {margin-left:0;width:auto;padding-left:0;} .path-backup .notification.dependencies_enforced {text-align:center;color:#A00;font-weight:bold;} .path-backup .backup_progress {text-align:center;} .path-backup .backup_progress span.backup_stage {color:#999;} .path-backup .backup_progress .backup_stage.backup_stage_current {font-weight:bold;color:inherit;} .path-backup .backup_progress .backup_stage.backup_stage_next {} .path-backup .backup_progress span.backup_stage.backup_stage_complete {color:inherit;} #page-backup-restore .filealiasesfailures {background-color:#ffd3d9} #page-backup-restore .filealiasesfailures .aliaseslist {width:90%;margin:0.8em auto;background-color:white;border:1px dotted #666;} .path-backup .fitemtitle .iconlarge.icon-post { padding-left: 6px; } .path-backup.dir-rtl .fitemtitle .iconlarge.icon-post { padding-right: 6px; padding-right: 0; } .path-backup .fitem .smallicon { vertical-align: text-bottom; } /** * Web Service */ #webservice-doc-generator td {text-align: left;border: 0px solid black;} /** * Help Content (pop-up) */ #helppopupbox {background-color: #eee; border: 1px solid #848484;z-index: 10000 !important;} #helppopupbox .yui3-widget-hd {float:right;margin:3px 3px 0 0;} #helppopupbox .yui3-widget-bd {margin:0 1em 1em 1em;border-top:1px solid #eee;} #helppopupbox .yui3-widget-ft {text-align: center;} #helppopupbox .yui3-widget-ft .closebtn {margin:0 1em 1em 1em;} #helppopupbox .helpheading {font-size: 1em;} #helppopupbox .spinner {margin:1em;} .dir-rtl #helppopupbox .yui3-widget-hd {float:left;margin:3px 0 0 3px;} /** * Custom menu */ #custommenu {clear:both;} #custommenu .yui3-menu .yui3-menu {z-index:500;} #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content, #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content .ul {border:1px solid #000;} #custommenu .yui3-menu-horizontal.javascript-disabled ul {margin:0;padding:0;} #custommenu .yui3-menu-horizontal.javascript-disabled li {margin:0;padding:0;list-style:none;width:auto;position:relative;} #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu .yui3-menu-label {padding-right:20px;} #custommenu .yui3-menu-horizontal.javascript-disabled>.yui3-menu-content>ul>li {float:left;} #custommenu .yui3-menu-horizontal.javascript-disabled li a {padding:0 10px;} #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu {position:absolute;top:-10000px;left:-10000px;visibility:hidden;white-space: nowrap;max-width: 250px;background-color:#FFF;} #custommenu .yui3-menu-horizontal.javascript-disabled li:hover>.yui3-menu {top:100%;left:0;visibility: visible;z-index:10;} #custommenu .yui3-menu-horizontal.javascript-disabled li:hover .yui3-menu .yui3-menu {top:0;left:100%;min-width:200px;} #custommenu .yui3-menu-horizontal.javascript-disabled>.yui3-menu-content>ul:after {content:"";display:block;clear:both;line-height:0;font-size:0;visibility:hidden;} #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content {font-size:93%;line-height:2;padding:0;} #custommenu .yui3-menu-horizontal.javascript-disabled .yui3-menu-content .yui3-menu-content {font-size:100%;} /** * Fix for broken YUI images in the menunav component */ #custommenu .yui3-menu-label, #custommenu .yui3-menuitem-content {cursor:pointer;} #custommenu .yui3-menuitem-active {background-color:#B3D4FF;} #custommenu .yui3-menuitem-active, #custommenu .yui3-menuitem-active .yui3-menuitem-content, #custommenu .yui3-menu-horizontal .yui3-menu-label, #custommenu .yui3-menu-horizontal .yui3-menu-content {background-image:none;background-position:right center;background-repeat:no-repeat;} #custommenu .yui3-menu-label, #custommenu .yui3-menu .yui3-menu .yui3-menu-label {background-image:url([[pix:theme|vertical-menu-submenu-indicator]]); padding-right: 20px;} #custommenu .yui3-menu .yui3-menu .yui3-menu-label-menuvisible {background-image:url([[pix:theme|horizontal-menu-submenu-indicator]]);} /** * Smart Select Element */ .smartselect {position:absolute;} .smartselect .smartselect_mask {background-color:#fff;} .smartselect ul {padding: 0;margin: 0;} .smartselect ul li {list-style: none;} .smartselect .smartselect_menu {margin-right:5px;} .safari .smartselect .smartselect_menu {margin-left:2px;} .smartselect .smartselect_menu, .smartselect .smartselect_submenu {border:1px solid #000;background-color:#FFF;display: none;} .smartselect .smartselect_menu.visible, .smartselect .smartselect_submenu.visible {display:block;} .smartselect .smartselect_menu_content ul li {position:relative;padding:2px 5px;} .smartselect .smartselect_menu_content ul li a {color:#333;text-decoration:none;} .smartselect .smartselect_menu_content ul li a.selectable {color:inherit;} .smartselect .smartselect_submenuitem {background-image:url([[pix:moodle|t/collapsed]]);background-repeat: no-repeat;background-position:100%;} /** Spanning mode */ .smartselect.spanningmenu .smartselect_submenu {position:absolute;top:-1px;left:100%;} .smartselect.spanningmenu .smartselect_submenu a {white-space: nowrap;padding-right:16px;} .smartselect.spanningmenu .smartselect_menu_content ul li a.selectable:hover {text-decoration:underline;} /** Compact mode */ .smartselect.compactmenu .smartselect_submenu {position:relative;margin:2px -3px; margin-left: 10px;display:none;border-width:0;z-index: 1010;} .smartselect.compactmenu .smartselect_submenu.visible {display:block;} .smartselect.compactmenu .smartselect_menu {z-index: 1000;overflow:hidden;} .smartselect.compactmenu .smartselect_submenu .smartselect_submenu {z-index: 1020;} .smartselect.compactmenu .smartselect_submenuitem:hover > .smartselect_menuitem_label {font-weight:bold;} /** * Registration */ #page-admin-registration-register .registration_textfield {width: 300px;} /** * Enrol */ .userenrolment {width:100%;border-collapse: collapse;} .userenrolment td {padding:0;height:41px;} .userenrolment .subfield {margin-right:5px;} .userenrolment .col_userdetails .subfield_picture {float:left;} .userenrolment .col_lastseen {width:150px;} .userenrolment .col_role {width:262px;} .userenrolment .col_role .roles {margin-right:30px;} .userenrolment .col_role .role {float:left;padding:3px;margin:3px;} .dir-rtl .userenrolment .col_role .role {float:right;} .userenrolment .col_role .role a {margin-left:3px;cursor:pointer;} .userenrolment .col_role .addrole {float:right;width:18px;margin:3px;height:18px;text-align:center;} .userenrolment .col_role .addrole a img {vertical-align:bottom;} .userenrolment .hasAllRoles .col_role .addrole {display:none;} .userenrolment .col_group .groups {margin-right:30px;} .userenrolment .col_group .group {float:left;padding:3px;margin:3px;white-space:nowrap;} .userenrolment .col_group .group a {margin-left:3px;cursor:pointer;} .userenrolment .col_group .addgroup {float:right;width:18px;margin:3px;height:18px;text-align:center;} .userenrolment .col_group .addgroup a img {vertical-align:bottom;} .userenrolment .col_enrol .enrolment {float:left;padding:3px;margin:3px;} .userenrolment .col_enrol .enrolment a {float:right;margin-left:3px;} #page-enrol-users .enrol_user_buttons {float:right;} #page-enrol-users .enrol_user_buttons .enrolusersbutton {margin-left:1em;display:inline;} #page-enrol-users .enrol_user_buttons .enrolusersbutton div, #page-enrol-users .enrol_user_buttons .enrolusersbutton form {display:inline;} #page-enrol-users .enrol_user_buttons .enrolusersbutton input {padding-left:6px;padding-right:6px;} #page-enrol-users.dir-rtl .col_userdetails .subfield_picture {float: right;} /** * Overide for RTL layout **/ .dir-rtl .headermain {float:right;} .dir-rtl .headermenu {float:left;} .dir-rtl .breadcrumb {float:right;} .dir-rtl .navbutton {float: left;} .dir-rtl .breadcrumb ul li { float: right; margin-left: 5px;} .dir-rtl .mform .fitem .fitemtitle {float:right;} .dir-rtl .loginbox .loginform .form-label {float:right;text-align:left;} .dir-rtl .loginbox .loginform .form-input {text-align: right;} .dir-rtl .yui3-menu-hidden {left: 0px;} #page-admin-roles-define.dir-rtl #rolesform .felement {margin-right: 180px;} #page-message-edit.dir-rtl table.generaltable th.c0 {text-align: right;} /** * Backup */ .backup-restore .backup-section {clear:both;border:1px solid #ddd;background-color:#f6f6f6;margin-bottom:1em;} .backup-restore .backup-section > h2.header {padding:5px 6px;margin:0;border-bottom:1px solid #ddd;} .backup-restore .backup-section .noticebox {margin:1em auto;width:60%;text-align:center;} .backup-restore .backup-section .backup-sub-section {margin:0 25px;background-color:#f9f9f9;border:1px solid #f3f3f3;margin-bottom:1em;} .backup-restore .backup-section .backup-sub-section h3 {text-align:right;border-bottom:1px solid #DDD;padding:5px 86% 5px 6px;margin:0;background-color:#e9e9e9;} .backup-restore .backup-section.settings-section .detail-pair {margin:0;padding:0;width:50%;display:inline-block;} .backup-restore .backup-section.settings-section .detail-pair .detail-pair-label {width:65%;} .backup-restore .backup-section.settings-section .detail-pair .detail-pair-value {width:25%;} .backup-restore .activitytable {width:60%;min-width:500px;} .backup-restore .activitytable .modulename {width:100px;} .backup-restore .activitytable .moduleincluded {width:50px;} .backup-restore .activitytable .userinfoincluded {width:50px;} .backup-restore .detail-pair {} .backup-restore .detail-pair-label {display:inline-block;width:25%;padding:8px;margin:0;text-align:right;font-weight:bold;color:#444;vertical-align:top;} .backup-restore .detail-pair-value {display:inline-block;width:65%;padding:8px;margin:0;} .backup-restore .detail-pair-value > .sub-detail {display:block;color:#1580B6;margin-left:2em;font-size:90%;font-style: italic;} .backup-restore > .singlebutton {text-align:right;} .path-backup .mform .fgroup .proceedbutton {float:right;margin-right:1%;} .restore-course-search .rcs-results {width:70%;min-width:400px;border:1px solid #ddd;margin:5px 0;} .restore-course-search .rcs-results table {width:100%;margin:0;border-width:0;} .restore-course-search .rcs-results table .no-overflow {max-width:600px;} .restore-course-search .rcs-results .paging {text-align:left;margin:0;background-color:#eee;padding:3px;} .restore-course-category .rcs-results {width:70%;min-width:400px;border:1px solid #ddd;margin:5px 0;} .restore-course-category .rcs-results table {width:100%;margin:0;border-width:0;} .restore-course-category .rcs-results table .no-overflow {max-width:600px;} .restore-course-category .rcs-results .paging {text-align:left;margin:0;background-color:#eee;padding:3px;} .corelightbox {background-color:#CCC;position:absolute;top:0;left:0;width:100%;height:100%;text-align:center;} .corelightbox img {position:fixed;top:50%; left: 50%;} /** * IE - Overide for RTL layout */ .ie.dir-rtl .mform .fitem .felement {margin-right:0;text-align:right;float:right;} .mod-indent-1 {margin-left:30px;} .mod-indent-2 {margin-left:60px;} .mod-indent-3 {margin-left:90px;} .mod-indent-4 {margin-left:120px;} .mod-indent-5 {margin-left:150px;} .mod-indent-6 {margin-left:180px;} .mod-indent-7 {margin-left:210px;} .mod-indent-8 {margin-left:240px;} .mod-indent-9 {margin-left:270px;} .mod-indent-10 {margin-left:300px;} .mod-indent-11 {margin-left:330px;} .mod-indent-12 {margin-left:360px;} .mod-indent-13 {margin-left:390px;} .mod-indent-14 {margin-left:420px;} .mod-indent-15, .mod-indent-huge {margin-left:420px;} .dir-rtl .mod-indent-1 {margin-right:30px;margin-left:0;} .dir-rtl .mod-indent-2 {margin-right:60px;margin-left:0;} .dir-rtl .mod-indent-3 {margin-right:90px;margin-left:0;} .dir-rtl .mod-indent-4 {margin-right:120px;margin-left:0;} .dir-rtl .mod-indent-5 {margin-right:150px;margin-left:0;} .dir-rtl .mod-indent-6 {margin-right:180px;margin-left:0;} .dir-rtl .mod-indent-7 {margin-right:210px;margin-left:0;} .dir-rtl .mod-indent-8 {margin-right:240px;margin-left:0;} .dir-rtl .mod-indent-9 {margin-right:270px;margin-left:0;} .dir-rtl .mod-indent-10 {margin-right:300px;margin-left:0;} .dir-rtl .mod-indent-11 {margin-right:330px;margin-left:0;} .dir-rtl .mod-indent-12 {margin-right:360px;margin-left:0;} .dir-rtl .mod-indent-13 {margin-right:390px;margin-left:0;} .dir-rtl .mod-indent-14 {margin-right:420px;margin-left:0;} .dir-rtl .mod-indent-15, .dir-rtl .mod-indent-huge {margin-right:420px;margin-left:0;} .dir-rtl .mform .fitem .felement {margin-right: 16%;margin-left:auto;text-align: right;} .dir-rtl .mform .fitem .felement input[name=email], .dir-rtl .mform .fitem .felement input[name=email2], .dir-rtl .mform .fitem .felement input[name=url], .dir-rtl .mform .fitem .felement input[name=idnumber], .dir-rtl .mform .fitem .felement input[name=phone1], .dir-rtl .mform .fitem .felement input[name=phone2] {text-align: left; direction: ltr;} /* Audio player size in 'block' mode (can only change width, height is hardcoded in JS) */ .resourcecontent .mediaplugin_mp3 object {height:25px; width: 600px} .resourcecontent audio.mediaplugin_html5audio {width: 600px} /** Large resource images should avoid hidden overflow **/ .resourceimage {max-width: 100%;} /* Audio player size in 'inline' mode (can only change width, as above) */ .mediaplugin_mp3 object {height:15px;width:300px} audio.mediaplugin_html5audio {width: 300px} /* TinyMCE moodle media preview frame should not have padding */ .core_media_preview.pagelayout-embedded #content {padding:0;} .core_media_preview.pagelayout-embedded #maincontent {height:0;} .core_media_preview.pagelayout-embedded .mediaplugin {margin:0;} /* Fix for SubScript & SuperScript ------------------------------*/ sub {vertical-align: sub;} sup {vertical-align: super;} /** Fix YUI 2 Treeview for Right to left languages **/ .dir-rtl .ygtvtn, .dir-rtl .ygtvtm, .dir-rtl .ygtvtmh, .dir-rtl .ygtvtmhh, .dir-rtl .ygtvtp, .dir-rtl .ygtvtph, .dir-rtl .ygtvtphh, .dir-rtl .ygtvln, .dir-rtl .ygtvlm, .dir-rtl .ygtvlmh, .dir-rtl .ygtvlmhh, .dir-rtl .ygtvlp, .dir-rtl .ygtvlph, .dir-rtl .ygtvlphh, .dir-rtl .ygtvdepthcell, .dir-rtl .ygtvok, .dir-rtl .ygtvok:hover, .dir-rtl .ygtvcancel, .dir-rtl .ygtvcancel:hover {width:18px; height:22px; background-image:url([[pix:theme|yui2-treeview-sprite-rtl]]); background-repeat: no-repeat; cursor:pointer;} .dir-rtl .ygtvtn {background-position: 0 -5600px;} .dir-rtl .ygtvtm {background-position: 0 -4000px;} .dir-rtl .ygtvtmh, .dir-rtl .ygtvtmhh {background-position: 0 -4800px;} .dir-rtl .ygtvtp {background-position: 0 -6400px;} .dir-rtl .ygtvtph, .dir-rtl .ygtvtphh {background-position: 0 -7200px;} .dir-rtl .ygtvln {background-position: 0 -1600px;} .dir-rtl .ygtvlm {background-position: 0 0;} .dir-rtl .ygtvlmh, .dir-rtl .ygtvlmhh {background-position: 0 -800px;} .dir-rtl .ygtvlp {background-position: 0 -2400px;} .dir-rtl .ygtvlph, .dir-rtl .ygtvlphh {background-position: 0 -3200px} .dir-rtl .ygtvdepthcell {background-position: 0 -8000px;} .dir-rtl .ygtvok {background-position: 0 -8800px;} .dir-rtl .ygtvok:hover {background-position: 0 -8844px;} .dir-rtl .ygtvcancel {background-position: 0 -8822px;} .dir-rtl .ygtvcancel:hover {background-position: 0 -8866px;} .dir-rtl .file-picker .yui-layout-unit-left {left:500px !important;} .dir-rtl .file-picker .yui-layout-unit-center {left:0px !important;} .dir-rtl.yui-skin-sam .yui-panel .hd {text-align:left;} .dir-rtl .yui-skin-sam .yui-layout .yui-layout-unit div.yui-layout-bd {text-align:right;} /** Fix TinyMCE editor right to left **/ .dir-rtl .clearlooks2.ie9 .mceAlert .mceMiddle span,.dir-rtl .clearlooks2 .mceConfirm .mceMiddle span {top: 44px;} .dir-rtl .o2k7Skin table, .dir-rtl .o2k7Skin tbody, .dir-rtl .o2k7Skin a, .dir-rtl .o2k7Skin img, .dir-rtl .o2k7Skin tr, .dir-rtl .o2k7Skin div, .dir-rtl .o2k7Skin td, .dir-rtl .o2k7Skin iframe, .dir-rtl .o2k7Skin span, .dir-rtl .o2k7Skin *, .dir-rtl .o2k7Skin .mceText, .dir-rtl .o2k7Skin .mceListBox .mceText {text-align:right;} .path-rating .ratingtable {width:100%;margin-bottom:1em;} .path-rating .ratingtable th.rating {width:100%;} .path-rating .ratingtable td.rating, .path-rating .ratingtable td.time {white-space:nowrap; text-align:center;} /* Fix for ordered and unordered list in course topic summary & course weekly summary */ .course-content ul.weeks .content .summary ul, .course-content ul.topics .content .summary ul {list-style: disc outside none;} .course-content ul.weeks .content .summary ol, .course-content ul.topics .content .summary ol {list-style: decimal outside none;} .dir-rtl #adminsettings #id_s__pathtodu, .dir-rtl #adminsettings #id_s__aspellpath, .dir-rtl #adminsettings #id_s__pathtodot, .dir-rtl #adminsettings #id_s__supportemail, .dir-rtl #adminsettings #id_s__supportpage, .dir-rtl #adminsettings #id_s__sessioncookie, .dir-rtl #adminsettings #id_s__sessioncookiepath, .dir-rtl #adminsettings #id_s__sessioncookiedomain, .dir-rtl #adminsettings #id_s__proxyhost, .dir-rtl #adminsettings #id_s__proxyuser, .dir-rtl #adminsettings #id_s__proxypassword, .dir-rtl #adminsettings #id_s__proxybypass, .dir-rtl #adminsettings #id_s__jabberhost, .dir-rtl #adminsettings #id_s__jabberserver, .dir-rtl #adminsettings #id_s__jabberusername, .dir-rtl #adminsettings #id_s__jabberpassword, .dir-rtl #adminsettings #id_s__additionalhtmlhead, .dir-rtl #adminsettings #id_s__additionalhtmltopofbody, .dir-rtl #adminsettings #id_s__additionalhtmlfooter, .dir-rtl #adminsettings #id_s__docroot, .dir-rtl #adminsettings #id_s__filter_tex_latexpreamble, .dir-rtl #adminsettings #id_s__filter_tex_latexbackground, .dir-rtl #adminsettings #id_s__filter_tex_pathlatex, .dir-rtl #adminsettings #id_s__filter_tex_pathdvips, .dir-rtl #adminsettings #id_s__filter_tex_pathconvert, .dir-rtl #adminsettings #id_s__blockedip, .dir-rtl #adminsettings #id_s__pathtoclam, .dir-rtl #adminsettings #id_s__quarantinedir, .dir-rtl #adminsettings #id_s__sitepolicy, .dir-rtl #adminsettings #id_s__sitepolicyguest, .dir-rtl #adminsettings #id_s__cronremotepassword, .dir-rtl #adminsettings #id_s__allowedip, .dir-rtl #adminsettings #id_s__blockedip, .dir-rtl #adminsettings #id_s_enrol_meta_nosyncroleids, .dir-rtl #adminsettings #id_s_enrol_ldap_host_url, .dir-rtl #adminsettings #id_s_enrol_ldap_ldapencoding, .dir-rtl #adminsettings #id_s_enrol_ldap_bind_dn, .dir-rtl #adminsettings #id_s_enrol_ldap_bind_pw, .dir-rtl #adminsettings #admin-emoticons .form-text, .dir-rtl #adminsettings #admin-role_mapping input[type=text], .dir-rtl #adminsettings #id_s_enrol_paypal_paypalbusiness, .dir-rtl #adminsettings #id_s_enrol_flatfile_location, #page-admin-setting-enrolsettingsflatfile.dir-rtl input[type=text], #page-admin-setting-enrolsettingsdatabase.dir-rtl input[type=text], #page-admin-auth-db.dir-rtl input[type=text] {direction: ltr;} #page-admin-setting-enrolsettingsflatfile.dir-rtl .informationbox {direction: ltr;text-align: left;} #page-admin-grade-edit-scale-edit.dir-rtl .error input#id_name {margin-right: 170px;} .initialbar a {padding-right: 2px;} /** * Chooser Dialogue * * This CSS belong to the chooser dialogue which should work both with, and * without javascript enabled */ /* Hide the dialog and it's title */ .chooserdialoguebody, .choosertitle { display:none; } .moodle-dialogue-base .moodle-dialogue { background: none!important; border: 0 none!important; } .chooserdialogue .moodle-dialogue-wrap { height: auto; background-color: #FFFFFF; border: 1px solid #CCCCCC!important; border-radius:10px; box-shadow: 5px 5px 20px 0px #666666; -webkit-box-shadow: 5px 5px 20px 0px #666666; -moz-box-shadow: 5px 5px 20px 0px #666666; } .chooserdialogue .moodle-dialogue-hd { font-size:12px!important; font-weight: normal!important; letter-spacing: 1px; color:#333333!important; text-align: center!important; text-shadow: 1px 1px 1px #FFFFFF; padding:5px 5px 5px 5px; border-radius: 10px 10px 0px 0px; border-bottom: 1px solid #BBBBBB!important; background: #CCCCCC!important; background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#CCCCCC))!important; background: -moz-linear-gradient(top, #FFFFFF, #CCCCCC)!important; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#CCCCCC')!important; filter: dropshadow(color=#FFFFFF, offx=1, offy=1); } /* Activity Chooser "Close" button */ .dir-rtl .moodle-dialogue-base .closebutton {float: left;} /* Question Bank - Question Chooser "Close" button */ #page-question-edit.dir-rtl a.container-close {right:auto;left:6px;} .chooserdialogue .moodle-dialogue-bd { font-size: 12px; color: #555555; overflow: auto; padding: 0px; background: #F2F2F2; border-bottom-left-radius: 10px; border-bottom-right-radius: 10px; } /* Center the submit buttons within the area */ .choosercontainer #chooseform .submitbuttons { margin: 0.7em 0; text-align: center; } .choosercontainer #chooseform .submitbuttons input { min-width: 100px; margin: 0px 0.5em; } /* Various settings for the options area */ .choosercontainer #chooseform .options { position: relative; border-bottom: 1px solid #BBBBBB; } /* Only set these options if we're showing the js container */ .jsenabled .choosercontainer #chooseform .alloptions { max-height: 550px; overflow-x: hidden; overflow-y: auto; max-width: 20.3em; box-shadow: inset 0px 0px 30px 0px #CCCCCC; -webkit-box-shadow: inset 0px 0px 30px 0px #CCCCCC; -moz-box-shadow: inset 0px 0px 30px 0px #CCCCCC; } .dir-rtl.jsenabled .choosercontainer #chooseform .alloptions { max-width: 18.3em; } /* Settings for option rows and option subtypes */ .choosercontainer #chooseform .moduletypetitle, .choosercontainer #chooseform .option, .choosercontainer #chooseform .nonoption { margin-bottom: 0; padding: 0 1.6em 0 1.6em; } .choosercontainer #chooseform .moduletypetitle { text-transform: uppercase; padding-top: 1.2em; padding-bottom: 0.4em; } .choosercontainer #chooseform .option .typename, .choosercontainer #chooseform .option span.modicon img.icon, .choosercontainer #chooseform .nonoption .typename, .choosercontainer #chooseform .nonoption span.modicon img.icon { padding: 0 0 0 0.5em; } .dir-rtl .choosercontainer #chooseform .option .typename, .dir-rtl .choosercontainer #chooseform .option span.modicon img.icon, .dir-rtl .choosercontainer #chooseform .nonoption .typename, .dir-rtl .choosercontainer #chooseform .nonoption span.modicon img.icon { padding: 0 0.5em 0 0; } .choosercontainer #chooseform .option span.modicon img.icon, .choosercontainer #chooseform .nonoption span.modicon img.icon { height: 24px; width: 24px; } .choosercontainer #chooseform .option input[type=radio], .choosercontainer #chooseform .option span.typename, .choosercontainer #chooseform .option span.modicon { vertical-align: middle; } .choosercontainer #chooseform .option label { display: block; padding: 0.3em 0 0.1em 0; border-bottom: 1px solid #FFFFFF; } .choosercontainer #chooseform .nonoption { padding-left: 2.7em; padding-top: 0.3em; padding-bottom: 0.1em; } .dir-rtl .choosercontainer #chooseform .nonoption { padding-right: 2.7em; padding-left: 0; } .choosercontainer #chooseform .subtype { margin-bottom: 0; padding: 0 1.6em 0 3.2em; } .dir-rtl .choosercontainer #chooseform .subtype { padding: 0 3.2em 0 1.6em; } .choosercontainer #chooseform .subtype .typename { margin: 0 0 0 0.2em; } .dir-rtl .choosercontainer #chooseform .subtype .typename { margin: 0 0.2em 0 0; } /* The instruction/help area */ .jsenabled .choosercontainer #chooseform .instruction, .jsenabled .choosercontainer #chooseform .typesummary { display: none; position: absolute; top: 0px; right: 0px; bottom: 0px; left: 20.3em; margin: 0; padding: 1.6em; background-color: #FFFFFF; overflow-x: hidden; overflow-y: auto; max-height: 550px; line-height: 2em; } .dir-rtl.jsenabled .choosercontainer #chooseform .instruction, .dir-rtl.jsenabled .choosercontainer #chooseform .typesummary { left: 0px; right: 18.5em; border-right: 1px solid grey; } /* Selected option settings */ .jsenabled .choosercontainer #chooseform .instruction, .choosercontainer #chooseform .selected .typesummary { display: block; } .choosercontainer #chooseform .selected { background-color: #FFFFFF; box-shadow: 0px 0px 10px 0px #CCCCCC; -webkit-box-shadow: 0px 0px 10px 0px #CCCCCC; -moz-box-shadow: 0px 0px 10px 0px #CCCCCC; } .section-modchooser-link img.smallicon { padding-right: 3px; } .dir-rtl .section-modchooser-link img.smallicon { padding-left: 3px; padding-right: 0;} /* Install Process' text fields Forms, should always be justified to the left */ form#installform #id_wwwroot,form#installform #id_dirroot ,form#installform #id_dataroot, form#installform #id_dbhost, form#installform #id_dbname, form#installform #id_dbuser, form#installform #id_dbpass, form#installform #id_prefix {direction: ltr;} html[dir=rtl] .breadcrumb, html[dir=rtl] .headermain, html[dir=rtl] #page-header {float: right;} html[dir=rtl] .formrow label.formlabel { float:right; } html[dir=rtl] .configphp {direction:ltr;text-align:left;} table.flexible .r0, table.generaltable .r0 {background-color: #F0F0F0;} table.flexible .r1, table.generaltable .r1 {background-color: #FAFAFA;}
ualberta-eclass/moodle-local_contextadmin
theme/base/style/core.css
CSS
gpl-3.0
45,444
# -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-07-11 13:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('parlamentares', '0003_auto_20170707_1656'), ] operations = [ migrations.AlterField( model_name='mandato', name='data_inicio_mandato', field=models.DateField(blank=True, null=True, verbose_name='Início do Mandato'), ), ]
cmjatai/cmj
sapl/parlamentares/migrations/0004_auto_20170711_1305.py
Python
gpl-3.0
513
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "InformationElements" * found in "../asn/InformationElements.asn" * `asn1c -fcompound-names -fnative-types` */ #include "GANSSTimeModelsList.h" static asn_per_constraints_t asn_PER_type_GANSSTimeModelsList_constr_1 = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 3, 3, 1, 7 } /* (SIZE(1..7)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_GANSSTimeModelsList_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)), 0, &asn_DEF_UE_Positioning_GANSS_TimeModel, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "" }, }; static ber_tlv_tag_t asn_DEF_GANSSTimeModelsList_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_SET_OF_specifics_t asn_SPC_GANSSTimeModelsList_specs_1 = { sizeof(struct GANSSTimeModelsList), offsetof(struct GANSSTimeModelsList, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_GANSSTimeModelsList = { "GANSSTimeModelsList", "GANSSTimeModelsList", SEQUENCE_OF_free, SEQUENCE_OF_print, SEQUENCE_OF_constraint, SEQUENCE_OF_decode_ber, SEQUENCE_OF_encode_der, SEQUENCE_OF_decode_xer, SEQUENCE_OF_encode_xer, SEQUENCE_OF_decode_uper, SEQUENCE_OF_encode_uper, 0, /* Use generic outmost tag fetcher */ asn_DEF_GANSSTimeModelsList_tags_1, sizeof(asn_DEF_GANSSTimeModelsList_tags_1) /sizeof(asn_DEF_GANSSTimeModelsList_tags_1[0]), /* 1 */ asn_DEF_GANSSTimeModelsList_tags_1, /* Same as above */ sizeof(asn_DEF_GANSSTimeModelsList_tags_1) /sizeof(asn_DEF_GANSSTimeModelsList_tags_1[0]), /* 1 */ &asn_PER_type_GANSSTimeModelsList_constr_1, asn_MBR_GANSSTimeModelsList_1, 1, /* Single element */ &asn_SPC_GANSSTimeModelsList_specs_1 /* Additional specs */ };
BramBonne/snoopsnitch-pcapinterface
contrib/libosmo-asn1-rrc/src/GANSSTimeModelsList.c
C
gpl-3.0
1,855
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 DialConjure(ctx context.Context, cjSession *ConjureSession, registrationMethod Registrar) (net.Conn, error) { if cjSession == nil { return nil, fmt.Errorf("No Session Provided") } cjSession.setV6Support(both) // 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()) 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) // 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(), } 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 { if p == nil { continue } 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 )
efryntov/psiphon-tunnel-core
vendor/github.com/refraction-networking/gotapdance/tapdance/conjure.go
GO
gpl-3.0
33,573
import java.util.Scanner; public class Hacktoberfest { public static void main(String[] args) { int i,num,m=0,flag=0; Scanner sc = new Scanner(System.in); System.out.println("Enter the number to be checked"); num = sc.nextInt(); for(i=2;i<=num/2;i++) { if(num%i==0) { System.out.println("Number is not prime"); flag=1; break; } } if(flag==0) System.out.println("Number is prime"); } }
hacktoberfest17/programming
numbers/is_prime/java/is_prime.java
Java
gpl-3.0
498
<?php /** * Piwik - free/libre analytics platform * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ namespace Piwik\Tests\System; use Piwik\Common; use Piwik\Db; use Piwik\Tests\Fixtures\OneVisitorTwoVisits; use Piwik\Tests\Framework\TestCase\SystemTestCase; /** * The tracker inserts actions in separate SQL queries which can cause * duplicate actions to be in the DB (actions w/ the same name, hash + type, but * different idaction). The tracker will delete duplicate actions, but * if for some reason the tracker fails before the DELETE occurs, there can be * stray duplicate actions. This test is there to ensure reports are not affected * by duplicate action entries. * * @group Core * @group DuplicateActionsTest */ class DuplicateActionsTest extends SystemTestCase { /** * @var OneVisitorTwoVisits */ public static $fixture = null; // initialized below class public static function setUpBeforeClass() { parent::setUpBeforeClass(); // add duplicates for every action $table = Common::prefixTable('log_action'); foreach (Db::fetchAll("SELECT * FROM $table") as $row) { $insertSql = "INSERT INTO $table (name, type, hash, url_prefix) VALUES (?, ?, CRC32(?), ?)"; Db::query($insertSql, array($row['name'], $row['type'], $row['name'], $row['url_prefix'])); } } /** * @dataProvider getApiForTesting */ public function test_PiwikApiWorks_WhenDuplicateActionsExistInDb($api, $params) { $this->runApiTests($api, $params); } public function getApiForTesting() { $idSite = self::$fixture->idSite; $dateTime = self::$fixture->dateTime; $api = array('VisitsSummary', 'Actions', 'Contents', 'Events'); return array( array($api, array('idSite' => $idSite, 'periods' => 'day', 'date' => $dateTime, 'compareAgainst' => 'OneVisitorTwoVisits', 'otherRequestParameters' => array( 'hideColumns' => OneVisitorTwoVisits::getValueForHideColumns(), ) )) ); } } DuplicateActionsTest::$fixture = new OneVisitorTwoVisits(); DuplicateActionsTest::$fixture->excludeMozilla = true;
mneudert/piwik
tests/PHPUnit/System/DuplicateActionsTest.php
PHP
gpl-3.0
2,452
/* * 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. */ /* * $Id$ */ package org.apache.xalan.trace; /** * Extends TraceListenerEx2 but adds extensions trace events. * @xsl.usage advanced */ public interface TraceListenerEx3 extends TraceListenerEx2 { /** * Method that is called when an extension event occurs. * The method is blocking. It must return before processing continues. * * @param ee the extension event. */ public void extension(ExtensionEvent ee); /** * Method that is called when the end of an extension event occurs. * The method is blocking. It must return before processing continues. * * @param ee the extension event. */ public void extensionEnd(ExtensionEvent ee); }
srnsw/xena
xena/ext/src/xalan-j_2_7_1/src/org/apache/xalan/trace/TraceListenerEx3.java
Java
gpl-3.0
1,521
/* * Copyright (C) 2007-2015 Hypertable, Inc. * * This file is part of Hypertable. * * Hypertable 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; version 3 of the * License, or any later version. * * Hypertable is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <Common/Compat.h> #include "OperationStatus.h" #include "Utility.h" #include <Common/Error.h> #include <Common/Serialization.h> #include <Common/Status.h> #include <Common/StatusPersister.h> #include <Common/StringExt.h> using namespace Hypertable; using namespace Hypertable::Lib::Master; OperationStatus::OperationStatus(ContextPtr &context, EventPtr &event) : OperationEphemeral(context, event, MetaLog::EntityType::OPERATION_STATUS) { HT_INFOF("Status-%lld", (Lld)header.id); } void OperationStatus::execute() { Status status; Timer timer(m_event->header.timeout_ms, true); Utility::status(m_context, timer, status); m_params.set_status(status); complete_ok(); } const String OperationStatus::name() { return "OperationStatus"; } const String OperationStatus::label() { return String("Status"); } size_t OperationStatus::encoded_result_length() const { return 4 + m_params.encoded_length(); } /// @details /// Encoding is as follows: /// <table> /// <tr> /// <th>Encoding</th><th>Description</th> /// </tr> /// <tr> /// <td>i32</td><td>Error code (Error::OK)</td> /// </tr> /// <tr> /// <td>Response::Parameters::Status</td><td>Response parameters</td> /// </tr> /// </table> void OperationStatus::encode_result(uint8_t **bufp) const { Serialization::encode_i32(bufp, Error::OK); m_params.encode(bufp); }
nkhuyu/hypertable
src/cc/Hypertable/Master/OperationStatus.cc
C++
gpl-3.0
2,157
""" commands.requires ================= This module manages the logic of resolving command permissions and requirements. This includes rules which override those requirements, as well as custom checks which can be overridden, and some special checks like bot permissions checks. """ import asyncio import enum import inspect from collections import ChainMap from typing import ( TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, List, Mapping, Optional, Tuple, TypeVar, Union, ) import discord from discord.ext.commands import check from .errors import BotMissingPermissions if TYPE_CHECKING: from .commands import Command from .context import Context _CommandOrCoro = TypeVar("_CommandOrCoro", Callable[..., Awaitable[Any]], Command) __all__ = [ "CheckPredicate", "DM_PERMS", "GlobalPermissionModel", "GuildPermissionModel", "PermissionModel", "PrivilegeLevel", "PermState", "Requires", "permissions_check", "bot_has_permissions", "bot_in_a_guild", "has_permissions", "has_guild_permissions", "is_owner", "guildowner", "guildowner_or_permissions", "admin", "admin_or_permissions", "mod", "mod_or_permissions", "transition_permstate_to", "PermStateTransitions", "PermStateAllowedStates", ] _T = TypeVar("_T") GlobalPermissionModel = Union[ discord.User, discord.VoiceChannel, discord.TextChannel, discord.CategoryChannel, discord.Role, discord.Guild, ] GuildPermissionModel = Union[ discord.Member, discord.VoiceChannel, discord.TextChannel, discord.CategoryChannel, discord.Role, discord.Guild, ] PermissionModel = Union[GlobalPermissionModel, GuildPermissionModel] CheckPredicate = Callable[["Context"], Union[Optional[bool], Awaitable[Optional[bool]]]] # Here we are trying to model DM permissions as closely as possible. The only # discrepancy I've found is that users can pin messages, but they cannot delete them. # This means manage_messages is only half True, so it's left as False. # This is also the same as the permissions returned when `permissions_for` is used in DM. DM_PERMS = discord.Permissions.none() DM_PERMS.update( add_reactions=True, attach_files=True, embed_links=True, external_emojis=True, mention_everyone=True, read_message_history=True, read_messages=True, send_messages=True, ) class PrivilegeLevel(enum.IntEnum): """Enumeration for special privileges.""" # Maintainer Note: do NOT re-order these. # Each privilege level also implies access to the ones before it. # Inserting new privilege levels at a later point is fine if that is considered. NONE = enum.auto() """No special privilege level.""" MOD = enum.auto() """User has the mod role.""" ADMIN = enum.auto() """User has the admin role.""" GUILD_OWNER = enum.auto() """User is the guild level.""" BOT_OWNER = enum.auto() """User is a bot owner.""" @classmethod async def from_ctx(cls, ctx: "Context") -> "PrivilegeLevel": """Get a command author's PrivilegeLevel based on context.""" if await ctx.bot.is_owner(ctx.author): return cls.BOT_OWNER elif ctx.guild is None: return cls.NONE elif ctx.author == ctx.guild.owner: return cls.GUILD_OWNER # The following is simply an optimised way to check if the user has the # admin or mod role. guild_settings = ctx.bot._config.guild(ctx.guild) member_snowflakes = ctx.author._roles # DEP-WARN for snowflake in await guild_settings.admin_role(): if member_snowflakes.has(snowflake): # DEP-WARN return cls.ADMIN for snowflake in await guild_settings.mod_role(): if member_snowflakes.has(snowflake): # DEP-WARN return cls.MOD return cls.NONE def __repr__(self) -> str: return f"<{self.__class__.__name__}.{self.name}>" class PermState(enum.Enum): """Enumeration for permission states used by rules.""" ACTIVE_ALLOW = enum.auto() """This command has been actively allowed, default user checks should be ignored. """ NORMAL = enum.auto() """No overrides have been set for this command, make determination from default user checks. """ PASSIVE_ALLOW = enum.auto() """There exists a subcommand in the `ACTIVE_ALLOW` state, continue down the subcommand tree until we either find it or realise we're on the wrong branch. """ CAUTIOUS_ALLOW = enum.auto() """This command has been actively denied, but there exists a subcommand in the `ACTIVE_ALLOW` state. This occurs when `PASSIVE_ALLOW` and `ACTIVE_DENY` are combined. """ ACTIVE_DENY = enum.auto() """This command has been actively denied, terminate the command chain. """ # The below are valid states, but should not be transitioned to # They should be set if they apply. ALLOWED_BY_HOOK = enum.auto() """This command has been actively allowed by a permission hook. check validation swaps this out, but the information may be useful to developers. It is treated as `ACTIVE_ALLOW` for the current command and `PASSIVE_ALLOW` for subcommands.""" DENIED_BY_HOOK = enum.auto() """This command has been actively denied by a permission hook check validation swaps this out, but the information may be useful to developers. It is treated as `ACTIVE_DENY` for the current command and any subcommands.""" @classmethod def from_bool(cls, value: Optional[bool]) -> "PermState": """Get a PermState from a bool or ``NoneType``.""" if value is True: return cls.ACTIVE_ALLOW elif value is False: return cls.ACTIVE_DENY else: return cls.NORMAL def __repr__(self) -> str: return f"<{self.__class__.__name__}.{self.name}>" # Here we're defining how we transition between states. # The dict is in the form: # previous state -> this state -> Tuple[override, next state] # "override" is a bool describing whether or not the command should be # invoked. It can be None, in which case the default permission checks # will be used instead. # There is also one case where the "next state" is dependent on the # result of the default permission checks - the transition from NORMAL # to PASSIVE_ALLOW. In this case "next state" is a dict mapping the # permission check results to the actual next state. TransitionResult = Tuple[Optional[bool], Union[PermState, Dict[bool, PermState]]] TransitionDict = Dict[PermState, Dict[PermState, TransitionResult]] PermStateTransitions: TransitionDict = { PermState.ACTIVE_ALLOW: { PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), PermState.NORMAL: (True, PermState.ACTIVE_ALLOW), PermState.PASSIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), PermState.CAUTIOUS_ALLOW: (True, PermState.CAUTIOUS_ALLOW), PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY), }, PermState.NORMAL: { PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), PermState.NORMAL: (None, PermState.NORMAL), PermState.PASSIVE_ALLOW: (True, {True: PermState.NORMAL, False: PermState.PASSIVE_ALLOW}), PermState.CAUTIOUS_ALLOW: (True, PermState.CAUTIOUS_ALLOW), PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY), }, PermState.PASSIVE_ALLOW: { PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), PermState.NORMAL: (False, PermState.NORMAL), PermState.PASSIVE_ALLOW: (True, PermState.PASSIVE_ALLOW), PermState.CAUTIOUS_ALLOW: (True, PermState.CAUTIOUS_ALLOW), PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY), }, PermState.CAUTIOUS_ALLOW: { PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), PermState.NORMAL: (False, PermState.ACTIVE_DENY), PermState.PASSIVE_ALLOW: (True, PermState.CAUTIOUS_ALLOW), PermState.CAUTIOUS_ALLOW: (True, PermState.CAUTIOUS_ALLOW), PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY), }, PermState.ACTIVE_DENY: { # We can only start from ACTIVE_DENY if it is set on a cog. PermState.ACTIVE_ALLOW: (True, PermState.ACTIVE_ALLOW), # Should never happen PermState.NORMAL: (False, PermState.ACTIVE_DENY), PermState.PASSIVE_ALLOW: (False, PermState.ACTIVE_DENY), # Should never happen PermState.CAUTIOUS_ALLOW: (False, PermState.ACTIVE_DENY), # Should never happen PermState.ACTIVE_DENY: (False, PermState.ACTIVE_DENY), }, } PermStateAllowedStates = ( PermState.ACTIVE_ALLOW, PermState.PASSIVE_ALLOW, PermState.CAUTIOUS_ALLOW, ) def transition_permstate_to(prev: PermState, next_state: PermState) -> TransitionResult: # Transforms here are used so that the # informational ALLOWED_BY_HOOK/DENIED_BY_HOOK # remain, while retaining the behavior desired. if prev is PermState.ALLOWED_BY_HOOK: # As hook allows are extremely granular, # we don't want this to allow every subcommand prev = PermState.PASSIVE_ALLOW elif prev is PermState.DENIED_BY_HOOK: # However, denying should deny every subcommand prev = PermState.ACTIVE_DENY return PermStateTransitions[prev][next_state] class Requires: """This class describes the requirements for executing a specific command. The permissions described include both bot permissions and user permissions. Attributes ---------- checks : List[Callable[[Context], Union[bool, Awaitable[bool]]]] A list of checks which can be overridden by rules. Use `Command.checks` if you would like them to never be overridden. privilege_level : PrivilegeLevel The required privilege level (bot owner, admin, etc.) for users to execute the command. Can be ``None``, in which case the `user_perms` will be used exclusively, otherwise, for levels other than bot owner, the user can still run the command if they have the required `user_perms`. ready_event : asyncio.Event Event for when this Requires object has had its rules loaded. If permissions is loaded, this should be set when permissions has finished loading rules into this object. If permissions is not loaded, it should be set as soon as the command or cog is added. user_perms : Optional[discord.Permissions] The required permissions for users to execute the command. Can be ``None``, in which case the `privilege_level` will be used exclusively, otherwise, it will pass whether the user has the required `privilege_level` _or_ `user_perms`. bot_perms : discord.Permissions The required bot permissions for a command to be executed. This is not overrideable by other conditions. """ DEFAULT: ClassVar[str] = "default" """The key for the default rule in a rules dict.""" GLOBAL: ClassVar[int] = 0 """Should be used in place of a guild ID when setting/getting global rules. """ def __init__( self, privilege_level: Optional[PrivilegeLevel], user_perms: Union[Dict[str, bool], discord.Permissions, None], bot_perms: Union[Dict[str, bool], discord.Permissions], checks: List[CheckPredicate], ): self.checks: List[CheckPredicate] = checks self.privilege_level: Optional[PrivilegeLevel] = privilege_level self.ready_event = asyncio.Event() if isinstance(user_perms, dict): self.user_perms: Optional[discord.Permissions] = discord.Permissions.none() _validate_perms_dict(user_perms) self.user_perms.update(**user_perms) else: self.user_perms = user_perms if isinstance(bot_perms, dict): self.bot_perms: discord.Permissions = discord.Permissions.none() _validate_perms_dict(bot_perms) self.bot_perms.update(**bot_perms) else: self.bot_perms = bot_perms self._global_rules: _RulesDict = _RulesDict() self._guild_rules: _IntKeyDict[_RulesDict] = _IntKeyDict[_RulesDict]() @staticmethod def get_decorator( privilege_level: Optional[PrivilegeLevel], user_perms: Optional[Dict[str, bool]] ) -> Callable[["_CommandOrCoro"], "_CommandOrCoro"]: if not user_perms: user_perms = None def decorator(func: "_CommandOrCoro") -> "_CommandOrCoro": if inspect.iscoroutinefunction(func): func.__requires_privilege_level__ = privilege_level func.__requires_user_perms__ = user_perms else: func.requires.privilege_level = privilege_level if user_perms is None: func.requires.user_perms = None else: _validate_perms_dict(user_perms) assert func.requires.user_perms is not None func.requires.user_perms.update(**user_perms) return func return decorator def get_rule(self, model: Union[int, str, PermissionModel], guild_id: int) -> PermState: """Get the rule for a particular model. Parameters ---------- model : Union[int, str, PermissionModel] The model to get the rule for. `str` is only valid for `Requires.DEFAULT`. guild_id : int The ID of the guild for the rule's scope. Set to `Requires.GLOBAL` for a global rule. If a global rule is set for a model, it will be preferred over the guild rule. Returns ------- PermState The state for this rule. See the `PermState` class for an explanation. """ if not isinstance(model, (str, int)): model = model.id rules: Mapping[Union[int, str], PermState] if guild_id: rules = ChainMap(self._global_rules, self._guild_rules.get(guild_id, _RulesDict())) else: rules = self._global_rules return rules.get(model, PermState.NORMAL) def set_rule(self, model_id: Union[str, int], rule: PermState, guild_id: int) -> None: """Set the rule for a particular model. Parameters ---------- model_id : Union[str, int] The model to add a rule for. `str` is only valid for `Requires.DEFAULT`. rule : PermState Which state this rule should be set as. See the `PermState` class for an explanation. guild_id : int The ID of the guild for the rule's scope. Set to `Requires.GLOBAL` for a global rule. """ if guild_id: rules = self._guild_rules.setdefault(guild_id, _RulesDict()) else: rules = self._global_rules if rule is PermState.NORMAL: rules.pop(model_id, None) else: rules[model_id] = rule def clear_all_rules(self, guild_id: int, *, preserve_default_rule: bool = True) -> None: """Clear all rules of a particular scope. Parameters ---------- guild_id : int The guild ID to clear rules for. If set to `Requires.GLOBAL`, this will clear all global rules and leave all guild rules untouched. Other Parameters ---------------- preserve_default_rule : bool Whether to preserve the default rule or not. This defaults to being preserved """ if guild_id: rules = self._guild_rules.setdefault(guild_id, _RulesDict()) else: rules = self._global_rules default = rules.get(self.DEFAULT, None) rules.clear() if default is not None and preserve_default_rule: rules[self.DEFAULT] = default def reset(self) -> None: """Reset this Requires object to its original state. This will clear all rules, including defaults. It also resets the `Requires.ready_event`. """ self._guild_rules.clear() # pylint: disable=no-member self._global_rules.clear() # pylint: disable=no-member self.ready_event.clear() async def verify(self, ctx: "Context") -> bool: """Check if the given context passes the requirements. This will check the bot permissions, overrides, user permissions and privilege level. Parameters ---------- ctx : "Context" The invocation context to check with. Returns ------- bool ``True`` if the context passes the requirements. Raises ------ BotMissingPermissions If the bot is missing required permissions to run the command. CommandError Propagated from any permissions checks. """ if not self.ready_event.is_set(): await self.ready_event.wait() await self._verify_bot(ctx) # Owner should never be locked out of commands for user permissions. if await ctx.bot.is_owner(ctx.author): return True # Owner-only commands are non-overrideable, and we already checked for owner. if self.privilege_level is PrivilegeLevel.BOT_OWNER: return False hook_result = await ctx.bot.verify_permissions_hooks(ctx) if hook_result is not None: return hook_result return await self._transition_state(ctx) async def _verify_bot(self, ctx: "Context") -> None: if ctx.guild is None: bot_user = ctx.bot.user else: bot_user = ctx.guild.me cog = ctx.cog if cog and await ctx.bot.cog_disabled_in_guild(cog, ctx.guild): raise discord.ext.commands.DisabledCommand() bot_perms = ctx.channel.permissions_for(bot_user) if not (bot_perms.administrator or bot_perms >= self.bot_perms): raise BotMissingPermissions(missing=self._missing_perms(self.bot_perms, bot_perms)) async def _transition_state(self, ctx: "Context") -> bool: should_invoke, next_state = self._get_transitioned_state(ctx) if should_invoke is None: # NORMAL invocation, we simply follow standard procedure should_invoke = await self._verify_user(ctx) elif isinstance(next_state, dict): # NORMAL to PASSIVE_ALLOW; should we proceed as normal or transition? # We must check what would happen normally, if no explicit rules were set. would_invoke = self._get_would_invoke(ctx) if would_invoke is None: would_invoke = await self._verify_user(ctx) next_state = next_state[would_invoke] assert isinstance(next_state, PermState) ctx.permission_state = next_state return should_invoke def _get_transitioned_state(self, ctx: "Context") -> TransitionResult: prev_state = ctx.permission_state cur_state = self._get_rule_from_ctx(ctx) return transition_permstate_to(prev_state, cur_state) def _get_would_invoke(self, ctx: "Context") -> Optional[bool]: default_rule = PermState.NORMAL if ctx.guild is not None: default_rule = self.get_rule(self.DEFAULT, guild_id=ctx.guild.id) if default_rule is PermState.NORMAL: default_rule = self.get_rule(self.DEFAULT, self.GLOBAL) if default_rule == PermState.ACTIVE_DENY: return False elif default_rule == PermState.ACTIVE_ALLOW: return True else: return None async def _verify_user(self, ctx: "Context") -> bool: checks_pass = await self._verify_checks(ctx) if checks_pass is False: return False if self.user_perms is not None: user_perms = ctx.channel.permissions_for(ctx.author) if user_perms.administrator or user_perms >= self.user_perms: return True if self.privilege_level is not None: privilege_level = await PrivilegeLevel.from_ctx(ctx) if privilege_level >= self.privilege_level: return True return False def _get_rule_from_ctx(self, ctx: "Context") -> PermState: author = ctx.author guild = ctx.guild if ctx.guild is None: # We only check the user for DM channels rule = self._global_rules.get(author.id) if rule is not None: return rule return self.get_rule(self.DEFAULT, self.GLOBAL) rules_chain = [self._global_rules] guild_rules = self._guild_rules.get(ctx.guild.id) if guild_rules: rules_chain.append(guild_rules) channels = [] if author.voice is not None: channels.append(author.voice.channel) channels.append(ctx.channel) category = ctx.channel.category if category is not None: channels.append(category) # We want author roles sorted highest to lowest, and exclude the @everyone role author_roles = reversed(author.roles[1:]) model_chain = [author, *channels, *author_roles, guild] for rules in rules_chain: for model in model_chain: rule = rules.get(model.id) if rule is not None: return rule del model_chain[-1] # We don't check for the guild in guild rules default_rule = self.get_rule(self.DEFAULT, guild.id) if default_rule is PermState.NORMAL: default_rule = self.get_rule(self.DEFAULT, self.GLOBAL) return default_rule async def _verify_checks(self, ctx: "Context") -> bool: if not self.checks: return True return await discord.utils.async_all(check(ctx) for check in self.checks) @staticmethod def _get_perms_for(ctx: "Context", user: discord.abc.User) -> discord.Permissions: if ctx.guild is None: return DM_PERMS else: return ctx.channel.permissions_for(user) @classmethod def _get_bot_perms(cls, ctx: "Context") -> discord.Permissions: return cls._get_perms_for(ctx, ctx.guild.me if ctx.guild else ctx.bot.user) @staticmethod def _missing_perms( required: discord.Permissions, actual: discord.Permissions ) -> discord.Permissions: # Explained in set theory terms: # Assuming R is the set of required permissions, and A is # the set of the user's permissions, the set of missing # permissions will be equal to R \ A, i.e. the relative # complement/difference of A with respect to R. relative_complement = required.value & ~actual.value return discord.Permissions(relative_complement) @staticmethod def _member_as_user(member: discord.abc.User) -> discord.User: if isinstance(member, discord.Member): # noinspection PyProtectedMember return member._user return member def __repr__(self) -> str: return ( f"<Requires privilege_level={self.privilege_level!r} user_perms={self.user_perms!r} " f"bot_perms={self.bot_perms!r}>" ) # check decorators def permissions_check(predicate: CheckPredicate): """An overwriteable version of `discord.ext.commands.check`. This has the same behaviour as `discord.ext.commands.check`, however this check can be ignored if the command is allowed through a permissions cog. """ def decorator(func: "_CommandOrCoro") -> "_CommandOrCoro": if hasattr(func, "requires"): func.requires.checks.append(predicate) else: if not hasattr(func, "__requires_checks__"): func.__requires_checks__ = [] # noinspection PyUnresolvedReferences func.__requires_checks__.append(predicate) return func return decorator def has_guild_permissions(**perms): """Restrict the command to users with these guild permissions. This check can be overridden by rules. """ _validate_perms_dict(perms) def predicate(ctx): return ctx.guild and ctx.author.guild_permissions >= discord.Permissions(**perms) return permissions_check(predicate) def bot_has_permissions(**perms: bool): """Complain if the bot is missing permissions. If the user tries to run the command, but the bot is missing the permissions, it will send a message describing which permissions are missing. This check cannot be overridden by rules. """ def decorator(func: "_CommandOrCoro") -> "_CommandOrCoro": if asyncio.iscoroutinefunction(func): func.__requires_bot_perms__ = perms else: _validate_perms_dict(perms) func.requires.bot_perms.update(**perms) return func return decorator def bot_in_a_guild(): """Deny the command if the bot is not in a guild.""" async def predicate(ctx): return len(ctx.bot.guilds) > 0 return check(predicate) def has_permissions(**perms: bool): """Restrict the command to users with these permissions. This check can be overridden by rules. """ if perms is None: raise TypeError("Must provide at least one keyword argument to has_permissions") return Requires.get_decorator(None, perms) def is_owner(): """Restrict the command to bot owners. This check cannot be overridden by rules. """ return Requires.get_decorator(PrivilegeLevel.BOT_OWNER, {}) def guildowner_or_permissions(**perms: bool): """Restrict the command to the guild owner or users with these permissions. This check can be overridden by rules. """ return Requires.get_decorator(PrivilegeLevel.GUILD_OWNER, perms) def guildowner(): """Restrict the command to the guild owner. This check can be overridden by rules. """ return guildowner_or_permissions() def admin_or_permissions(**perms: bool): """Restrict the command to users with the admin role or these permissions. This check can be overridden by rules. """ return Requires.get_decorator(PrivilegeLevel.ADMIN, perms) def admin(): """Restrict the command to users with the admin role. This check can be overridden by rules. """ return admin_or_permissions() def mod_or_permissions(**perms: bool): """Restrict the command to users with the mod role or these permissions. This check can be overridden by rules. """ return Requires.get_decorator(PrivilegeLevel.MOD, perms) def mod(): """Restrict the command to users with the mod role. This check can be overridden by rules. """ return mod_or_permissions() class _IntKeyDict(Dict[int, _T]): """Dict subclass which throws TypeError when a non-int key is used.""" get: Callable setdefault: Callable def __getitem__(self, key: Any) -> _T: if not isinstance(key, int): raise TypeError("Keys must be of type `int`") return super().__getitem__(key) # pylint: disable=no-member def __setitem__(self, key: Any, value: _T) -> None: if not isinstance(key, int): raise TypeError("Keys must be of type `int`") return super().__setitem__(key, value) # pylint: disable=no-member class _RulesDict(Dict[Union[int, str], PermState]): """Dict subclass which throws a TypeError when an invalid key is used.""" get: Callable setdefault: Callable def __getitem__(self, key: Any) -> PermState: if key != Requires.DEFAULT and not isinstance(key, int): raise TypeError(f'Expected "{Requires.DEFAULT}" or int key, not "{key}"') return super().__getitem__(key) # pylint: disable=no-member def __setitem__(self, key: Any, value: PermState) -> None: if key != Requires.DEFAULT and not isinstance(key, int): raise TypeError(f'Expected "{Requires.DEFAULT}" or int key, not "{key}"') return super().__setitem__(key, value) # pylint: disable=no-member def _validate_perms_dict(perms: Dict[str, bool]) -> None: invalid_keys = set(perms.keys()) - set(discord.Permissions.VALID_FLAGS) if invalid_keys: raise TypeError(f"Invalid perm name(s): {', '.join(invalid_keys)}") for perm, value in perms.items(): if value is not True: # We reject any permission not specified as 'True', since this is the only value which # makes practical sense. raise TypeError(f"Permission {perm} may only be specified as 'True', not {value}")
palmtree5/Red-DiscordBot
redbot/core/commands/requires.py
Python
gpl-3.0
28,973
/* ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio 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. */ /** * @file hal_crypto.h * @brief Cryptographic Driver macros and structures. * * @addtogroup CRYPTO * @{ */ #ifndef HAL_CRYPTO_H #define HAL_CRYPTO_H #if (HAL_USE_CRY == TRUE) || defined(__DOXYGEN__) /*===========================================================================*/ /* Driver constants. */ /*===========================================================================*/ /*===========================================================================*/ /* Driver pre-compile time settings. */ /*===========================================================================*/ /** * @brief Enables the SW fall-back of the cryptographic driver. * @details When enabled, this option, activates a fall-back software * implementation for algorithms not supported by the underlying * hardware. * @note Fall-back implementations may not be present for all algorithms. */ #if !defined(HAL_CRY_USE_FALLBACK) || defined(__DOXYGEN__) #define HAL_CRY_USE_FALLBACK FALSE #endif /** * @brief Makes the driver forcibly use the fall-back implementations. * @note If enabled then the LLD driver is not included at all. */ #if !defined(HAL_CRY_ENFORCE_FALLBACK) || defined(__DOXYGEN__) #define HAL_CRY_ENFORCE_FALLBACK FALSE #endif /*===========================================================================*/ /* Derived constants and error checks. */ /*===========================================================================*/ #if HAL_CRY_ENFORCE_FALLBACK == TRUE #undef HAL_CRY_USE_FALLBACK #define HAL_CRY_USE_FALLBACK TRUE #endif /*===========================================================================*/ /* Driver data structures and types. */ /*===========================================================================*/ /** * @brief Size, in bits, of a crypto field or message. * @note It is assumed, for simplicity, that this type is equivalent to * a @p size_t. */ typedef size_t bitsize_t; /** * @brief Driver state machine possible states. */ typedef enum { CRY_UNINIT = 0, /**< Not initialized. */ CRY_STOP = 1, /**< Stopped. */ CRY_READY = 2 /**< Ready. */ } crystate_t; /** * @brief Driver error codes. */ typedef enum { CRY_NOERROR = 0, /**< No error. */ CRY_ERR_INV_ALGO = 1, /**< Invalid cypher/mode. */ CRY_ERR_INV_KEY_SIZE = 2, /**< Invalid key size. */ CRY_ERR_INV_KEY_TYPE = 3, /**< Invalid key type. */ CRY_ERR_INV_KEY_ID = 4, /**< Invalid key identifier. */ CRY_ERR_AUTH_FAILED = 5, /**< Failed authentication. */ CRY_ERR_OP_FAILURE = 6 /**< Failed operation. */ } cryerror_t; /** * @brief Type of an algorithm identifier. * @note It is only used to determine the key required for operations. */ typedef enum { cry_algo_none = 0, cry_algo_aes, /**< AES 128, 192, 256 bits. */ cry_algo_des, /**< DES 56, TDES 112, 168 bits.*/ cry_algo_hmac /**< HMAC variable size. */ } cryalgorithm_t; #if HAL_CRY_ENFORCE_FALLBACK == FALSE /* Use the defined low level driver.*/ #include "hal_crypto_lld.h" #if !defined(CRY_LLD_SUPPORTS_AES) || \ !defined(CRY_LLD_SUPPORTS_AES_ECB) || \ !defined(CRY_LLD_SUPPORTS_AES_CBC) || \ !defined(CRY_LLD_SUPPORTS_AES_CFB) || \ !defined(CRY_LLD_SUPPORTS_AES_CTR) || \ !defined(CRY_LLD_SUPPORTS_AES_GCM) || \ !defined(CRY_LLD_SUPPORTS_DES) || \ !defined(CRY_LLD_SUPPORTS_DES_ECB) || \ !defined(CRY_LLD_SUPPORTS_DES_CBC) || \ !defined(CRY_LLD_SUPPORTS_SHA1) || \ !defined(CRY_LLD_SUPPORTS_SHA256) || \ !defined(CRY_LLD_SUPPORTS_SHA512) || \ !defined(CRY_LLD_SUPPORTS_HMAC_SHA256) || \ !defined(CRY_LLD_SUPPORTS_HMAC_SHA512) #error "CRYPTO LLD does not export the required switches" #endif #else /* HAL_CRY_ENFORCE_FALLBACK == TRUE */ /* No LLD at all, using the standalone mode.*/ #define CRY_LLD_SUPPORTS_AES FALSE #define CRY_LLD_SUPPORTS_AES_ECB FALSE #define CRY_LLD_SUPPORTS_AES_CBC FALSE #define CRY_LLD_SUPPORTS_AES_CFB FALSE #define CRY_LLD_SUPPORTS_AES_CTR FALSE #define CRY_LLD_SUPPORTS_AES_GCM FALSE #define CRY_LLD_SUPPORTS_DES FALSE #define CRY_LLD_SUPPORTS_DES_ECB FALSE #define CRY_LLD_SUPPORTS_DES_CBC FALSE #define CRY_LLD_SUPPORTS_SHA1 FALSE #define CRY_LLD_SUPPORTS_SHA256 FALSE #define CRY_LLD_SUPPORTS_SHA512 FALSE #define CRY_LLD_SUPPORTS_HMAC_SHA256 FALSE #define CRY_LLD_SUPPORTS_HMAC_SHA512 FALSE typedef uint_fast8_t crykey_t; typedef struct CRYDriver CRYDriver; typedef struct { uint32_t dummy; } CRYConfig; struct CRYDriver { crystate_t state; const CRYConfig *config; }; #endif /* HAL_CRY_ENFORCE_FALLBACK == TRUE */ /* The fallback header is included only if required by settings.*/ #if HAL_CRY_USE_FALLBACK == TRUE #include "hal_crypto_fallback.h" #endif #if (HAL_CRY_USE_FALLBACK == FALSE) && (CRY_LLD_SUPPORTS_SHA1 == FALSE) /* Stub @p SHA1Context structure type declaration. It is not provided by the LLD and the fallback is not enabled.*/ typedef struct { uint32_t dummy; } SHA1Context; #endif #if (HAL_CRY_USE_FALLBACK == FALSE) && (CRY_LLD_SUPPORTS_SHA256 == FALSE) /* Stub @p SHA256Context structure type declaration. It is not provided by the LLD and the fallback is not enabled.*/ typedef struct { uint32_t dummy; } SHA256Context; #endif #if (HAL_CRY_USE_FALLBACK == FALSE) && (CRY_LLD_SUPPORTS_SHA512 == FALSE) /* Stub @p SHA512Context structure type declaration. It is not provided by the LLD and the fallback is not enabled.*/ typedef struct { uint32_t dummy; } SHA512Context; #endif #if (HAL_CRY_USE_FALLBACK == FALSE) && (CRY_LLD_SUPPORTS_HMAC_SHA256 == FALSE) /* Stub @p HMACSHA256Context structure type declaration. It is not provided by the LLD and the fallback is not enabled.*/ typedef struct { uint32_t dummy; } HMACSHA256Context; #endif #if (HAL_CRY_USE_FALLBACK == FALSE) && (CRY_LLD_SUPPORTS_HMAC_SHA512 == FALSE) /* Stub @p HMACSHA512Context structure type declaration. It is not provided by the LLD and the fallback is not enabled.*/ typedef struct { uint32_t dummy; } HMACSHA512Context; #endif /*===========================================================================*/ /* Driver macros. */ /*===========================================================================*/ /** * @name Low level driver helper macros * @{ */ /** @} */ /*===========================================================================*/ /* External declarations. */ /*===========================================================================*/ #ifdef __cplusplus extern "C" { #endif void cryInit(void); void cryObjectInit(CRYDriver *cryp); void cryStart(CRYDriver *cryp, const CRYConfig *config); void cryStop(CRYDriver *cryp); cryerror_t cryLoadAESTransientKey(CRYDriver *cryp, size_t size, const uint8_t *keyp); cryerror_t cryEncryptAES(CRYDriver *cryp, crykey_t key_id, const uint8_t *in, uint8_t *out); cryerror_t cryDecryptAES(CRYDriver *cryp, crykey_t key_id, const uint8_t *in, uint8_t *out); cryerror_t cryEncryptAES_ECB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out); cryerror_t cryDecryptAES_ECB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out); cryerror_t cryEncryptAES_CBC(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryDecryptAES_CBC(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryEncryptAES_CFB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryDecryptAES_CFB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryEncryptAES_CTR(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryDecryptAES_CTR(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryEncryptAES_GCM(CRYDriver *cryp, crykey_t key_id, size_t auth_size, const uint8_t *auth_in, size_t text_size, const uint8_t *text_in, uint8_t *text_out, const uint8_t *iv, size_t tag_size, uint8_t *tag_out); cryerror_t cryDecryptAES_GCM(CRYDriver *cryp, crykey_t key_id, size_t auth_size, const uint8_t *auth_in, size_t text_size, const uint8_t *text_in, uint8_t *text_out, const uint8_t *iv, size_t tag_size, const uint8_t *tag_in); cryerror_t cryLoadDESTransientKey(CRYDriver *cryp, size_t size, const uint8_t *keyp); cryerror_t cryEncryptDES(CRYDriver *cryp, crykey_t key_id, const uint8_t *in, uint8_t *out); cryerror_t cryDecryptDES(CRYDriver *cryp, crykey_t key_id, const uint8_t *in, uint8_t *out); cryerror_t cryEncryptDES_ECB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out); cryerror_t cryDecryptDES_ECB(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out); cryerror_t cryEncryptDES_CBC(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t cryDecryptDES_CBC(CRYDriver *cryp, crykey_t key_id, size_t size, const uint8_t *in, uint8_t *out, const uint8_t *iv); cryerror_t crySHA1Init(CRYDriver *cryp, SHA1Context *sha1ctxp); cryerror_t crySHA1Update(CRYDriver *cryp, SHA1Context *sha1ctxp, size_t size, const uint8_t *in); cryerror_t crySHA1Final(CRYDriver *cryp, SHA1Context *sha1ctxp, uint8_t *out); cryerror_t crySHA256Init(CRYDriver *cryp, SHA256Context *sha256ctxp); cryerror_t crySHA256Update(CRYDriver *cryp, SHA256Context *sha256ctxp, size_t size, const uint8_t *in); cryerror_t crySHA256Final(CRYDriver *cryp, SHA256Context *sha256ctxp, uint8_t *out); cryerror_t crySHA512Init(CRYDriver *cryp, SHA512Context *sha512ctxp); cryerror_t crySHA512Update(CRYDriver *cryp, SHA512Context *sha512ctxp, size_t size, const uint8_t *in); cryerror_t crySHA512Final(CRYDriver *cryp, SHA512Context *sha512ctxp, uint8_t *out); cryerror_t cryLoadHMACTransientKey(CRYDriver *cryp, size_t size, const uint8_t *keyp); cryerror_t cryHMACSHA256Init(CRYDriver *cryp, HMACSHA256Context *hmacsha256ctxp); cryerror_t cryHMACSHA256Update(CRYDriver *cryp, HMACSHA256Context *hmacsha256ctxp, size_t size, const uint8_t *in); cryerror_t cryHMACSHA256Final(CRYDriver *cryp, HMACSHA256Context *hmacsha256ctxp, uint8_t *out); cryerror_t cryHMACSHA512Init(CRYDriver *cryp, HMACSHA512Context *hmacsha512ctxp); cryerror_t cryHMACSHA512Update(CRYDriver *cryp, HMACSHA512Context *hmacsha512ctxp, size_t size, const uint8_t *in); cryerror_t cryHMACSHA512Final(CRYDriver *cryp, HMACSHA512Context *hmacsha512ctxp, uint8_t *out); #ifdef __cplusplus } #endif #endif /* HAL_USE_CRYPTO == TRUE */ #endif /* HAL_CRYPTO_H */ /** @} */
char32/ChibiOS
os/hal/include/hal_crypto.h
C
gpl-3.0
16,525
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <Cocoa/Cocoa.h> @class DVTCheapReusableSubstring, DVTStringBuffer, NSMutableArray, NSString; @interface DVTCharStream : NSObject { DVTStringBuffer *_stringBuffer; NSString *_realString; DVTCheapReusableSubstring *_cheapString; NSMutableArray *_savedTokens; id _savedBottomToken; BOOL _isAtBOL; BOOL _isAtColumnZero; BOOL _BOLIsKnown; BOOL _SeenOneCharAtBOL; BOOL _SeenWhitespaceAtBOL; } //- (void).cxx_destruct; - (id)savedToken; - (BOOL)hasSavedTokens; - (void)saveToken:(id)arg1; - (id)stringWithRange:(struct _NSRange)arg1; - (unsigned long long)locationOfNewlineFrom:(unsigned long long)arg1 searchBackwards:(BOOL)arg2; - (unsigned long long)peekCharacterInSet:(id)arg1; - (unsigned short)peekCharSkippingWhitespace; - (unsigned short)peekChar; - (BOOL)isAtColumnZero; - (BOOL)isAtBOL; - (void)_computeBOL; - (unsigned short)nextCharSkippingWhitespace; - (unsigned short)nextChar; - (void)setLocation:(unsigned long long)arg1; - (unsigned long long)location; - (unsigned long long)length; - (id)string; - (void)setString:(id)arg1; - (id)initWithString:(id)arg1; @end
wbitos/WaxHelper
WaxHelper/XCHeaders/DVTCharStream.h
C
gpl-3.0
1,266
//***************************************************************************** // // bitband.c - Bit-band manipulation example. // // Copyright (c) 2013-2017 Texas Instruments Incorporated. All rights reserved. // Software License Agreement // // Texas Instruments (TI) is supplying this software for use solely and // exclusively on TI's microcontroller products. The software is owned by // TI and/or its suppliers, and is protected under applicable copyright // laws. You may not combine this software with "viral" open-source // software in order to form a larger program. // // THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS. // NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT // NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY // CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL // DAMAGES, FOR ANY REASON WHATSOEVER. // // This is part of revision 2.1.4.178 of the EK-TM4C1294XL Firmware Package. // //***************************************************************************** #include <stdint.h> #include <stdbool.h> #include "inc/hw_memmap.h" #include "inc/hw_types.h" #include "driverlib/debug.h" #include "driverlib/gpio.h" #include "driverlib/fpu.h" #include "driverlib/pin_map.h" #include "driverlib/sysctl.h" #include "driverlib/systick.h" #include "driverlib/rom.h" #include "driverlib/rom_map.h" #include "driverlib/uart.h" #include "utils/uartstdio.h" //***************************************************************************** // //! \addtogroup example_list //! <h1>Bit-Banding (bitband)</h1> //! //! This example application demonstrates the use of the bit-banding //! capabilities of the Cortex-M4F microprocessor. All of SRAM and all of the //! peripherals reside within bit-band regions, meaning that bit-banding //! operations can be applied to any of them. In this example, a variable in //! SRAM is set to a particular value one bit at a time using bit-banding //! operations (it would be more efficient to do a single non-bit-banded write; //! this simply demonstrates the operation of bit-banding). // //***************************************************************************** //**************************************************************************** // // System clock rate in Hz. // //**************************************************************************** uint32_t g_ui32SysClock; //***************************************************************************** // // The value that is to be modified via bit-banding. // //***************************************************************************** static volatile uint32_t g_ui32Value; //***************************************************************************** // // The error routine that is called if the driver library encounters an error. // //***************************************************************************** #ifdef DEBUG void __error__(char *pcFilename, uint32_t ui32Line) { while(1) { // // Hang on runtime error. // } } #endif //***************************************************************************** // // Delay for the specified number of seconds. Depending upon the current // SysTick value, the delay will be between N-1 and N seconds (i.e. N-1 full // seconds are guaranteed, along with the remainder of the current second). // //***************************************************************************** void Delay(uint32_t ui32Seconds) { // // Loop while there are more seconds to wait. // while(ui32Seconds--) { // // Wait until the SysTick value is less than 1000. // while(ROM_SysTickValueGet() > 1000) { } // // Wait until the SysTick value is greater than 1000. // while(ROM_SysTickValueGet() < 1000) { } } } //***************************************************************************** // // Configure the UART and its pins. This must be called before UARTprintf(). // //***************************************************************************** void ConfigureUART(void) { // // Enable the GPIO Peripheral used by the UART. // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); // // Enable UART0 // ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); // // Configure GPIO Pins for UART mode. // ROM_GPIOPinConfigure(GPIO_PA0_U0RX); ROM_GPIOPinConfigure(GPIO_PA1_U0TX); ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); // // Initialize the UART for console I/O. // UARTStdioConfig(0, 115200, g_ui32SysClock); } //***************************************************************************** // // This example demonstrates the use of bit-banding to set individual bits // within a word of SRAM. // //***************************************************************************** int main(void) { uint32_t ui32Errors, ui32Idx; // // Set the clocking to run directly from the crystal at 120MHz. // g_ui32SysClock = MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ | SYSCTL_OSC_MAIN | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480), 120000000); // // Initialize the UART interface. // ConfigureUART(); UARTprintf("\033[2J\033[H"); UARTprintf("Bit banding...\n"); // // Set up and enable the SysTick timer. It will be used as a reference // for delay loops. The SysTick timer period will be set up for one // second. // ROM_SysTickPeriodSet(g_ui32SysClock); ROM_SysTickEnable(); // // Set the value and error count to zero. // g_ui32Value = 0; ui32Errors = 0; // // Print the initial value to the UART. // UARTprintf("\r%08x", g_ui32Value); // // Delay for 1 second. // Delay(1); // // Set the value to 0xdecafbad using bit band accesses to each individual // bit. // for(ui32Idx = 0; ui32Idx < 32; ui32Idx++) { // // Set this bit. // HWREGBITW(&g_ui32Value, 31 - ui32Idx) = (0xdecafbad >> (31 - ui32Idx)) & 1; // // Print the current value to the UART. // UARTprintf("\r%08x", g_ui32Value); // // Delay for 1 second. // Delay(1); } // // Make sure that the value is 0xdecafbad. // if(g_ui32Value != 0xdecafbad) { ui32Errors++; } // // Make sure that the individual bits read back correctly. // for(ui32Idx = 0; ui32Idx < 32; ui32Idx++) { if(HWREGBITW(&g_ui32Value, ui32Idx) != ((0xdecafbad >> ui32Idx) & 1)) { ui32Errors++; } } // // Print out the result. // if(ui32Errors) { UARTprintf("\nErrors!\n"); } else { UARTprintf("\nSuccess!\n"); } // // Loop forever. // while(1) { } }
jhnphm/xbs_xbd
platforms/ek-tm4c129exl_16mhz/hal/tivaware/examples/boards/ek-tm4c1294xl/bitband/bitband.c
C
gpl-3.0
7,411
/********************************************************************** ** This program is part of 'MOOSE', the ** Messaging Object Oriented Simulation Environment. ** Copyright (C) 2003-2010 Upinder S. Bhalla. and NCBS ** It is made available under the terms of the ** GNU Lesser General Public License version 2.1 ** See the file COPYING.LIB for the full notice. **********************************************************************/ #include "../basecode/header.h" #include "PoolBase.h" #include "Pool.h" #include "BufPool.h" #include "lookupVolumeFromMesh.h" #define EPSILON 1e-15 const Cinfo* BufPool::initCinfo() { ////////////////////////////////////////////////////////////// // Field Definitions ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// // MsgDest Definitions ////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////// // SharedMsg Definitions ////////////////////////////////////////////////////////////// static Dinfo< BufPool > dinfo; static Cinfo bufPoolCinfo ( "BufPool", Pool::initCinfo(), 0, 0, &dinfo ); return &bufPoolCinfo; } ////////////////////////////////////////////////////////////// // Class definitions ////////////////////////////////////////////////////////////// static const Cinfo* bufPoolCinfo = BufPool::initCinfo(); BufPool::BufPool() {;} BufPool::~BufPool() {;} ////////////////////////////////////////////////////////////// // Field definitions ////////////////////////////////////////////////////////////// void BufPool::vSetN( const Eref& e, double v ) { Pool::vSetN( e, v ); Pool::vSetNinit( e, v ); } void BufPool::vSetNinit( const Eref& e, double v ) { vSetN( e, v ); } void BufPool::vSetConc( const Eref& e, double conc ) { double n = NA * conc * lookupVolumeFromMesh( e ); vSetN( e, n ); } void BufPool::vSetConcInit( const Eref& e, double conc ) { vSetConc( e, conc ); } ////////////////////////////////////////////////////////////// // MsgDest Definitions ////////////////////////////////////////////////////////////// void BufPool::vProcess( const Eref& e, ProcPtr p ) { Pool::vReinit( e, p ); } void BufPool::vReinit( const Eref& e, ProcPtr p ) { Pool::vReinit( e, p ); } ////////////////////////////////////////////////////////////// // Field Definitions //////////////////////////////////////////////////////////////
BhallaLab/moose
moose-core/kinetics/BufPool.cpp
C++
gpl-3.0
2,573
/* yesno.c -- read a yes/no response from stdin Copyright (C) 1990, 1998, 2001, 2003-2012 Free Software Foundation, Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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/>. */ #include <config.h> #include "yesno.h" #include <stdlib.h> #include <stdio.h> /* Return true if we read an affirmative line from standard input. Since this function uses stdin, it is suggested that the caller not use STDIN_FILENO directly, and also that the line atexit(close_stdin) be added to main(). */ bool yesno (void) { bool yes; #if ENABLE_NLS char *response = NULL; size_t response_size = 0; ssize_t response_len = getline (&response, &response_size, stdin); if (response_len <= 0) yes = false; else { response[response_len - 1] = '\0'; yes = (0 < rpmatch (response)); } free (response); #else /* Test against "^[yY]", hardcoded to avoid requiring getline, regex, and rpmatch. */ int c = getchar (); yes = (c == 'y' || c == 'Y'); while (c != '\n' && c != EOF) c = getchar (); #endif return yes; }
SamB/debian-coreutils
lib/yesno.c
C
gpl-3.0
1,655
/*! \file geInternal.cpp \author Michael Olsen \date 09/Dec/2004 \date 09/Dec/2004 */ #include "geInternalOS.h"
qwertyflame/koblo_software
SDK/trunk/GUIEngine/source/geInternal.cpp
C++
gpl-3.0
117
/* * Analytical calculations for sphere-tetrahedron intersections. * * See here for it's mathematical description: * https://www.quora.com/What-are-some-equations-that-you-made-up/answer/Mahmut-Akku%C5%9F * * - RedBlight * */ #include <cmath> #include "LuVector.hpp" using Vec3 = LUV::LuVector<3, double>; // Returns the solid angle of sphere cap contended by a cone. // Apex of the cone is center of the sphere. double SolidAngleCap(double apexAngle) { return 2.0 * LUV::pi * (1.0 - std::cos(apexAngle)); } // Returns the solid angle of a spherical triangle. // v1, v2, v3 are vertices of the triangle residing on a unit sphere. double SolidAngleSphtri(const Vec3& v1, const Vec3& v2, const Vec3& v3) { double ang0 = std::acos(LUV::Dot(v1, v2)); double ang1 = std::acos(LUV::Dot(v2, v3)); double ang2 = std::acos(LUV::Dot(v3, v1)); double angSum = (ang0 + ang1 + ang2) / 2.0; return 4.0 * std::atan(std::sqrt( std::tan(angSum / 2.0) * std::tan((angSum - ang0) / 2.0) * std::tan((angSum - ang1) / 2.0) * std::tan((angSum - ang2) / 2.0) )); } // Returns the volume of spherical cap. double VolumeCap(double radius, double height) { return radius * radius * height * LUV::pi * (2.0 / 3.0); } // Returns the volume of cone. double VolumeCone(double radius, double height) { return radius * radius * height * LUV::pi * (1.0 / 3.0); } // Returns the volume of tetrahedron given it's 4 vertices. double VolumeTetrahedron(const Vec3& v1, const Vec3& v2, const Vec3& v3, const Vec3& v4) { return std::abs(LUV::Dot(v1 - v4, LUV::Cross(v2 - v4, v3 - v4))) / 6.0; } // Returns the volume of triangular slice taken from a sphere. double VolumeSphtri(const Vec3& v1, const Vec3& v2, const Vec3& v3, double radius) { return SolidAngleSphtri(v1, v2, v3) * radius * radius * radius / 3.0; } /* * Observation tetrahedra (OT) are special tetrahedra constructed for analytical calculations. * OTs have right angles in many of their corners, and one of their vertices are the center of the sphere. * For this reason, their intersections with the sphere can be calculated analytically. * When 24 OTs contructed for each vertex, of each edge, of each face, of any arbitrary tetrahedron, * their combinations can be used to analytically calculate intersections of any arbitrary sphere and tetrahedron. * */ class ObservationTetrahedron { public: // Cartesian coordinates of vertices: Vec3 posR, posA, posB, posC; // Distances from posR: double lenA, lenB, lenC; // Direction of sphere-edge intersection points as radius increases: Vec3 prdA, prdB, prdC, prdD, prdE, prdF; // Some angles between lines: double angBAC, angERA, angFAE; // Max. solid angle contended by OT double solidAngleFull; // Constructor ObservationTetrahedron(const Vec3& vR, const Vec3& vA, const Vec3& vB, const Vec3& vC) { posR = vR; posA = vA; posB = vB; posC = vC; Vec3 AmR = vA - vR; Vec3 BmR = vB - vR; Vec3 CmR = vC - vR; Vec3 BmA = vB - vA; Vec3 CmA = vC - vA; Vec3 CmB = vC - vB; lenA = LUV::Length(AmR); lenB = LUV::Length(BmR); lenC = LUV::Length(CmR); prdA = AmR / lenA; prdB = BmR / lenB; prdC = CmR / lenC; prdD = BmA / LUV::Length(BmA); prdE = CmA / LUV::Length(CmA); prdF = CmB / LUV::Length(CmB); angBAC = std::acos(LUV::Dot(prdD, prdE)); solidAngleFull = SolidAngleSphtri(prdA, prdB, prdC); } // Solid angle of the sphere subtended by OT as a function of sphere radius. double GetSolidAngle(double radius) { RecalculateForRadius(radius); if (radius >= lenC) return 0; else if (radius >= lenB) return SolidAngleSphtri(dirA, dirC, dirF) - SolidAngleCap(angERA) * angFAE / (2.0 * LUV::pi); else if (radius >= lenA) return solidAngleFull - SolidAngleCap(angERA) * angBAC / (2.0 * LUV::pi); return solidAngleFull; } // Surface area of the sphere subtended by OT as a function of sphere radius. double GetSurfaceArea(double radius) { return GetSolidAngle(radius) * radius * radius; } // Volume of OT-sphere intersection, as a function of sphere radius. double GetVolume(double radius) { RecalculateForRadius(radius); if (radius >= lenC) return VolumeTetrahedron(posR, posA, posB, posC); else if (radius >= lenB) return VolumeSphtri(dirA, dirC, dirF, radius) - ( VolumeCap(radius, LUV::Length(prpA - posA)) - VolumeCone(prlE, lenA) ) * angFAE / (2.0 * LUV::pi) + VolumeTetrahedron(posR, posA, posB, prpF); else if (radius >= lenA) return VolumeSphtri(dirA, dirB, dirC, radius) - ( VolumeCap(radius, LUV::Length(prpA - posA)) - VolumeCone(prlE, lenA) ) * angBAC / (2.0 * LUV::pi); return VolumeSphtri(dirA, dirB, dirC, radius); } private: // Angles of RBF triangle double angRBF, angBFR, angFRB; // Distance of sphere-edge intersections: double prlA, prlB, prlC, prlD, prlE, prlF; //R->A, R->B, R->C, A->B, A->C, B->C // Positions of sphere-edge intersections: Vec3 prpA, prpB, prpC, prpD, prpE, prpF; // Positions relative to posR: // All have the length = radius Vec3 vecA, vecB, vecC, vecD, vecE, vecF; // Directions from posR: Vec3 dirA, dirB, dirC, dirD, dirE, dirF; // OT vertices are not actually dependent on the radius of the sphere, only the center. // But some values need to be calculated for each radius. void RecalculateForRadius(double radius) { angRBF = std::acos(LUV::Dot(posR - posB, posC - posB)); angBFR = std::asin(lenB * std::sin(angRBF) / radius); angFRB = LUV::pi - (angRBF + angBFR); prlA = radius; prlB = radius; prlC = radius; prlD = std::sqrt(radius * radius - lenA * lenA); prlE = prlD; prlF = lenB * std::sin(angFRB) / sin(angBFR); prpA = posR + prdA * prlA; prpB = posR + prdB * prlB; prpC = posR + prdC * prlC; prpD = posA + prdD * prlD; prpE = posA + prdE * prlE; prpF = posB + prdF * prlF; vecA = prpA - posR; vecB = prpB - posR; vecC = prpC - posR; vecD = prpD - posR; vecE = prpE - posR; vecF = prpF - posR; dirA = vecA / LUV::Length(vecA); dirB = vecB / LUV::Length(vecB); dirC = vecC / LUV::Length(vecC); dirD = vecD / LUV::Length(vecD); dirE = vecE / LUV::Length(vecE); dirF = vecF / LUV::Length(vecF); angERA = std::acos(LUV::Dot(dirE, dirA)); Vec3 vecAF = prpF - posA; Vec3 vecAE = prpE - posA; angFAE = std::acos(LUV::Dot(vecAF, vecAE) / (LUV::Length(vecAF) * LUV::Length(vecAE))); } }; // Main class for the intersection. class SphereTetrahedronIntersection { public: // Constructor, // vecTetA..D are vertices of the tetrahedron. // vecSphCenter is the center of the sphere. SphereTetrahedronIntersection(const Vec3& vecTetA, const Vec3& vecTetB, const Vec3& vecTetC, const Vec3& vecTetD, const Vec3& vecSphCenter) { // Adding OTs for each face of the tetrahedron. AddOtForFace(vecTetA, vecTetB, vecTetC, vecTetD, vecSphCenter); AddOtForFace(vecTetB, vecTetC, vecTetD, vecTetA, vecSphCenter); AddOtForFace(vecTetC, vecTetD, vecTetA, vecTetB, vecSphCenter); AddOtForFace(vecTetD, vecTetA, vecTetB, vecTetC, vecSphCenter); // Calculating OT signs. for (int idf = 0; idf < 4; ++idf) for (int idl = 0; idl < 3; ++idl) { int ids = 3 * idf + idl; int idp = 2 * ids; int idm = idp + 1; obsTetSgn.push_back( LUV::Dot(obsTet[idp].prdA, dirN[idf]) * LUV::Dot(obsTet[idp].prdF, dirL[ids]) * LUV::Dot(obsTet[idp].prdD, dirU[ids]) ); obsTetSgn.push_back( -1 * LUV::Dot(obsTet[idm].prdA, dirN[idf]) * LUV::Dot(obsTet[idm].prdF, dirL[ids]) * LUV::Dot(obsTet[idm].prdD, dirU[ids]) ); } } // Solid angle subtended by tetrahedron, as a function of sphere radius. double GetSolidAngle(double radius) { double solidAngle = 0; for (int idx = 0; idx < 24; ++idx) { double solidAngleOt = obsTet[idx].GetSolidAngle(radius) * obsTetSgn[idx]; solidAngle += std::isnan(solidAngleOt) ? 0 : solidAngleOt; } return solidAngle; } // Surface area subtended by tetrahedron, as a function of sphere radius. double GetSurfaceArea(double radius) { return GetSolidAngle(radius) * radius * radius; } // Sphere-tetrahedron intersection volume, as a function of sphere radius. double GetVolume(double radius) { double volume = 0; for (int idx = 0; idx < 24; ++idx) { double volumeOt = obsTet[idx].GetVolume(radius) * obsTetSgn[idx]; volume += std::isnan(volumeOt) ? 0 : volumeOt; } return volume; } private: std::vector<ObservationTetrahedron> obsTet; //24 in total std::vector<double> obsTetSgn; std::vector<Vec3> dirN; std::vector<Vec3> dirU; std::vector<Vec3> dirL; void AddOtForEdge(const Vec3& vecM, const Vec3& vecP, const Vec3& vecT, const Vec3& vecR) { Vec3 PmM = vecP - vecM; dirL.push_back(PmM / LUV::Length(PmM)); Vec3 vecU = vecT - LUV::ProjLine(vecT, vecM, vecP); dirU.push_back(vecU / LUV::Length(vecU)); Vec3 vecA = LUV::ProjPlane(vecR, vecM, LUV::PlaneNormal(vecM, vecP, vecT)); Vec3 vecB = LUV::ProjLine(vecA, vecM, vecP); obsTet.push_back(ObservationTetrahedron(vecR, vecA, vecB, vecP)); obsTet.push_back(ObservationTetrahedron(vecR, vecA, vecB, vecM)); } void AddOtForFace(const Vec3& vecA, const Vec3& vecB, const Vec3& vecC, const Vec3& vecU, const Vec3& vecR) { Vec3 vecN = vecU - LUV::ProjPlane(vecU, vecA, LUV::PlaneNormal(vecA, vecB, vecC)); dirN.push_back(vecN / LUV::Length(vecN)); AddOtForEdge(vecA, vecB, vecC, vecR); AddOtForEdge(vecB, vecC, vecA, vecR); AddOtForEdge(vecC, vecA, vecB, vecR); } }; // An example usage... int main() { // Tetrahedron with a volume of 1000 Vec3 vecTetA(0, 0, 0); Vec3 vecTetB(10, 0, 0); Vec3 vecTetC(0, 20, 0); Vec3 vecTetD(0, 0, 30); // Center of the sphere Vec3 vecSphCenter(0, 0, 0); // Intersection class SphereTetrahedronIntersection testIntersection(vecTetA, vecTetB, vecTetC, vecTetD, vecSphCenter); // Demonstrating that numerical integral of surface area is equal to analytical calculation of volume: int stepCount = 10000; double radiusStart = 0; double radiusEnd = 30; double radiusDelta = (radiusEnd - radiusStart) / stepCount; double volumeNumerical = 0; for (double radius = radiusStart; radius < radiusEnd; radius += radiusDelta) volumeNumerical += testIntersection.GetSurfaceArea(radius) * radiusDelta; double volumeAnalytical = testIntersection.GetVolume(radiusEnd); // These 2 values must be almost equal: std::cout << volumeAnalytical << ", " << volumeNumerical << std::endl; return 0; }
OpenGenus/cosmos
code/computational_geometry/src/sphere_tetrahedron_intersection/sphere_tetrahedron_intersection.cpp
C++
gpl-3.0
12,009
{ "module_name": "Файлы", "new_folder": "Создать новую папку", "ajax_failed": "Ошибка во время запроса к серверу", "total_files": "Всего файлов", "dir_not_exists": "Папка не существует", "level_up": "На уровень вверх", "save": "Сохранить", "cancel": "Отмена", "invalid_dir_syntax": "Неверное имя папки", "dir_already_exists": "Папка уже существует", "newdir_success": "Новая папка успешно создана", "delete": "Удалить", "delete_success": "Удаление успешно завершено", "delete_confirm": "Вы действительно хотить удалить данный файл(ы)/папку(и)?", "no_files": "В текущей папке нет файлов.", "invalid_request": "Неверный запрос", "copy": "Копировать", "cut": "Вырезать", "paste": "Вставить", "clipboard_copy_success": "Скопировано в буфер обмена", "clipboard_cut_success": "Вырезано в буфер обмена", "cannot_paste_to_source_dir": "Нельзя вставить в исходную папку", "cannot_paste_to_itself": "Нельзя вставить в исходный документ", "paste_success": "Вставка успешно завершена", "paste_error": "Ошибка при вставке", "invalid_dir": "Неверная папка", "dir_or_file_not_exists": "Файл или папка не существует", "unauth": "У вас отсутствуют права для доступа к панели управления", "level_down": "Сменить папку", "clipboard_files": "Файлы буфера обмена", "current_folder": "Текущая папка", "loading_files_data": "Загрузка данных с сервера...", "some_files_not_deleted": "Некоторые файлы или папки не могут быть удалены", "upload": "Загрузка файла(ов)", "drag_and_drop_files_here": "Перетащите файлы сюда (если данная функция поддерживается браузером)", "uploadbtn": "Загрузка", "clearupload": "Очистить список", "addfiles": "Добавить файл(ы)", "close": "Закрыть", "file_too_big": "Файл слишком большой для загрузки", "rename": "Переименовать", "rename_file": "Переименовать", "invalid_filename_syntax": "Неверное имя файла", "rename_success": "Переименование успешно выполнено", "cannot_rename_same": "Файл или папка с таким именем уже существуют", "refresh": "Обновить", "download": "Загрузить", "download_error": "Ошибка загрузки", "unzip": "Распаковать архив", "unzip_error": "Ошибка во время распковки файла(ов)", "unzip_success": "Распаковка успешно выполнена", "newfile": "Новый текстовый файл", "new_filename": "Имя файла", "editfile": "Редактирование текстового файла", "upload_auto_start": "Автоматически начать загрузку при добавлении файлов", "link": "Ссылка на выбранный файл" }
edouardkombo/taracotjs
modules/files/lang/ru.js
JavaScript
gpl-3.0
3,544
/* * This file is part of APRIL-ANN toolkit (A * Pattern Recognizer In Lua with Artificial Neural Networks). * * Copyright 2012, Francisco Zamora-Martinez * * The APRIL-ANN toolkit is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ //BIND_HEADER_H #include "referenced_vector.h" #include "matrixFloat.h" #include "utilLua.h" #include "bind_matrix.h" using AprilUtils::ReferencedVectorFloat; using AprilUtils::ReferencedVectorUint; //BIND_END //BIND_LUACLASSNAME ReferencedVectorFloat util.vector_float //BIND_CPP_CLASS ReferencedVectorFloat //BIND_CONSTRUCTOR ReferencedVectorFloat { int initial_size; LUABIND_CHECK_ARGN(<=, 1); LUABIND_GET_OPTIONAL_PARAMETER(1,int,initial_size,1024); ReferencedVectorFloat *obj = new ReferencedVectorFloat(); obj->reserve(initial_size); LUABIND_RETURN(ReferencedVectorFloat, obj); } //BIND_END //BIND_METHOD ReferencedVectorFloat size { LUABIND_CHECK_ARGN(==, 0); LUABIND_RETURN(int, (int)obj->size()); } //BIND_END //BIND_METHOD ReferencedVectorFloat get { LUABIND_CHECK_ARGN(==, 1); uint idx; LUABIND_GET_PARAMETER(1, uint, idx); if (idx > obj->size()) LUABIND_FERROR2("Incorrect index, found %d, maximum size %d\n", idx, obj->size()); LUABIND_RETURN(float, (*obj)[idx-1]); } //BIND_END //BIND_METHOD ReferencedVectorFloat set { LUABIND_CHECK_ARGN(==, 2); uint idx; float value; LUABIND_GET_PARAMETER(1, uint, idx); LUABIND_GET_PARAMETER(2, float, value); if (idx > obj->size()) LUABIND_FERROR2("Incorrect index, found %d, maximum size %d\n", idx, obj->size()); (*obj)[idx-1] = value; } //BIND_END //BIND_METHOD ReferencedVectorFloat push_back { LUABIND_CHECK_ARGN(==, 1); float value; LUABIND_GET_PARAMETER(1, float, value); obj->push_back(value); } //BIND_END //BIND_METHOD ReferencedVectorFloat toMatrix { // LUABIND_CHECK_ARGN(<=, 1); // bool reuse_vector; // LUABIND_GET_OPTIONAL_PARAMETER(1,bool,reuse_vector,true); int dim = (int)obj->size(); MatrixFloat *mat; // if (reuse_vector) { // float *internal_data = obj->release_internal_vector(); // mat = new MatrixFloat(1,&dim,internal_data); // } else { mat = new MatrixFloat(1,&dim); MatrixFloat::iterator it(mat->begin()); for (int i=0; i<dim;++i, ++it) { *it = (*obj)[i]; } // } LUABIND_RETURN(MatrixFloat,mat); } //BIND_END ////////////////////////////////////////////////////////////////////// //BIND_LUACLASSNAME ReferencedVectorUint util.vector_uint //BIND_CPP_CLASS ReferencedVectorUint //BIND_CONSTRUCTOR ReferencedVectorUint { int initial_size; LUABIND_CHECK_ARGN(<=, 1); LUABIND_GET_OPTIONAL_PARAMETER(1,int,initial_size,1024); ReferencedVectorUint *obj = new ReferencedVectorUint(); obj->reserve(initial_size); LUABIND_RETURN(ReferencedVectorUint, obj); } //BIND_END //BIND_METHOD ReferencedVectorUint size { LUABIND_CHECK_ARGN(==, 0); LUABIND_RETURN(int, (int)obj->size()); } //BIND_END //BIND_METHOD ReferencedVectorUint get { LUABIND_CHECK_ARGN(==, 1); uint idx; LUABIND_GET_PARAMETER(1, uint, idx); if (idx > obj->size()) LUABIND_FERROR2("Incorrect index, found %d, maximum size %d\n", idx, obj->size()); LUABIND_RETURN(uint, (*obj)[idx-1]); } //BIND_END //BIND_METHOD ReferencedVectorUint set { LUABIND_CHECK_ARGN(==, 2); uint idx, value; LUABIND_GET_PARAMETER(1, uint, idx); LUABIND_GET_PARAMETER(2, uint, value); if (idx > obj->size()) LUABIND_FERROR2("Incorrect index, found %d, maximum size %d\n", idx, obj->size()); (*obj)[idx-1] = value; } //BIND_END //BIND_METHOD ReferencedVectorUint push_back { LUABIND_CHECK_ARGN(==, 1); double value; LUABIND_GET_PARAMETER(1, double, value); obj->push_back(value); } //BIND_END //BIND_METHOD ReferencedVectorUint toMatrix { // este metodo no hace falta, lo pongo para testear LUABIND_CHECK_ARGN(==, 0); int dim = (int)obj->size(); MatrixFloat *mat = new MatrixFloat(1,&dim); MatrixFloat::iterator it(mat->begin()); for (int i=0; i<dim;++i, ++it) { uint32_t value = (*obj)[i]; float aux = value; uint32_t test = aux; if (value != test) LUABIND_FERROR2("vector_uint toMatrix error: %f cannot be converted to uint %u\n", aux,test); *it = aux; } LUABIND_RETURN(MatrixFloat,mat); } //BIND_END
pakozm/april-ann
packages/basics/matrix/binding/bind_referenced_vector.lua.cc
C++
gpl-3.0
4,872
/*global define*/ define([ '../Core/AssociativeArray', '../Core/Color', '../Core/ColorGeometryInstanceAttribute', '../Core/defined', '../Core/ShowGeometryInstanceAttribute', '../Scene/Primitive', './BoundingSphereState' ], function( AssociativeArray, Color, ColorGeometryInstanceAttribute, defined, ShowGeometryInstanceAttribute, Primitive, BoundingSphereState) { "use strict"; var colorScratch = new Color(); var Batch = function(primitives, translucent, appearanceType, closed) { this.translucent = translucent; this.appearanceType = appearanceType; this.closed = closed; this.primitives = primitives; this.createPrimitive = false; this.primitive = undefined; this.oldPrimitive = undefined; this.geometry = new AssociativeArray(); this.updaters = new AssociativeArray(); this.updatersWithAttributes = new AssociativeArray(); this.attributes = new AssociativeArray(); this.subscriptions = new AssociativeArray(); this.showsUpdated = new AssociativeArray(); this.itemsToRemove = []; }; Batch.prototype.add = function(updater, instance) { var id = updater.entity.id; this.createPrimitive = true; this.geometry.set(id, instance); this.updaters.set(id, updater); if (!updater.hasConstantFill || !updater.fillMaterialProperty.isConstant) { this.updatersWithAttributes.set(id, updater); } else { var that = this; this.subscriptions.set(id, updater.entity.definitionChanged.addEventListener(function(entity, propertyName, newValue, oldValue) { if (propertyName === 'isShowing') { that.showsUpdated.set(entity.id, updater); } })); } }; Batch.prototype.remove = function(updater) { var id = updater.entity.id; this.createPrimitive = this.geometry.remove(id) || this.createPrimitive; if (this.updaters.remove(id)) { this.updatersWithAttributes.remove(id); var unsubscribe = this.subscriptions.get(id); if (defined(unsubscribe)) { unsubscribe(); this.subscriptions.remove(id); } } }; Batch.prototype.update = function(time) { var isUpdated = true; var removedCount = 0; var primitive = this.primitive; var primitives = this.primitives; var attributes; var i; if (this.createPrimitive) { var geometries = this.geometry.values; var geometriesLength = geometries.length; if (geometriesLength > 0) { if (defined(primitive)) { if (!defined(this.oldPrimitive)) { this.oldPrimitive = primitive; } else { primitives.remove(primitive); } } for (i = 0; i < geometriesLength; i++) { var geometryItem = geometries[i]; var originalAttributes = geometryItem.attributes; attributes = this.attributes.get(geometryItem.id.id); if (defined(attributes)) { if (defined(originalAttributes.show)) { originalAttributes.show.value = attributes.show; } if (defined(originalAttributes.color)) { originalAttributes.color.value = attributes.color; } } } primitive = new Primitive({ asynchronous : true, geometryInstances : geometries, appearance : new this.appearanceType({ translucent : this.translucent, closed : this.closed }) }); primitives.add(primitive); isUpdated = false; } else { if (defined(primitive)) { primitives.remove(primitive); primitive = undefined; } var oldPrimitive = this.oldPrimitive; if (defined(oldPrimitive)) { primitives.remove(oldPrimitive); this.oldPrimitive = undefined; } } this.attributes.removeAll(); this.primitive = primitive; this.createPrimitive = false; } else if (defined(primitive) && primitive.ready) { if (defined(this.oldPrimitive)) { primitives.remove(this.oldPrimitive); this.oldPrimitive = undefined; } var updatersWithAttributes = this.updatersWithAttributes.values; var length = updatersWithAttributes.length; for (i = 0; i < length; i++) { var updater = updatersWithAttributes[i]; var instance = this.geometry.get(updater.entity.id); attributes = this.attributes.get(instance.id.id); if (!defined(attributes)) { attributes = primitive.getGeometryInstanceAttributes(instance.id); this.attributes.set(instance.id.id, attributes); } if (!updater.fillMaterialProperty.isConstant) { var colorProperty = updater.fillMaterialProperty.color; colorProperty.getValue(time, colorScratch); if (!Color.equals(attributes._lastColor, colorScratch)) { attributes._lastColor = Color.clone(colorScratch, attributes._lastColor); attributes.color = ColorGeometryInstanceAttribute.toValue(colorScratch, attributes.color); if ((this.translucent && attributes.color[3] === 255) || (!this.translucent && attributes.color[3] !== 255)) { this.itemsToRemove[removedCount++] = updater; } } } var show = updater.entity.isShowing && (updater.hasConstantFill || updater.isFilled(time)); var currentShow = attributes.show[0] === 1; if (show !== currentShow) { attributes.show = ShowGeometryInstanceAttribute.toValue(show, attributes.show); } } this.updateShows(primitive); } else if (defined(primitive) && !primitive.ready) { isUpdated = false; } this.itemsToRemove.length = removedCount; return isUpdated; }; Batch.prototype.updateShows = function(primitive) { var showsUpdated = this.showsUpdated.values; var length = showsUpdated.length; for (var i = 0; i < length; i++) { var updater = showsUpdated[i]; var instance = this.geometry.get(updater.entity.id); var attributes = this.attributes.get(instance.id.id); if (!defined(attributes)) { attributes = primitive.getGeometryInstanceAttributes(instance.id); this.attributes.set(instance.id.id, attributes); } var show = updater.entity.isShowing; var currentShow = attributes.show[0] === 1; if (show !== currentShow) { attributes.show = ShowGeometryInstanceAttribute.toValue(show, attributes.show); } } this.showsUpdated.removeAll(); }; Batch.prototype.contains = function(entity) { return this.updaters.contains(entity.id); }; Batch.prototype.getBoundingSphere = function(entity, result) { var primitive = this.primitive; if (!primitive.ready) { return BoundingSphereState.PENDING; } var attributes = primitive.getGeometryInstanceAttributes(entity); if (!defined(attributes) || !defined(attributes.boundingSphere) ||// (defined(attributes.show) && attributes.show[0] === 0)) { return BoundingSphereState.FAILED; } attributes.boundingSphere.clone(result); return BoundingSphereState.DONE; }; Batch.prototype.removeAllPrimitives = function() { var primitives = this.primitives; var primitive = this.primitive; if (defined(primitive)) { primitives.remove(primitive); this.primitive = undefined; this.geometry.removeAll(); this.updaters.removeAll(); } var oldPrimitive = this.oldPrimitive; if (defined(oldPrimitive)) { primitives.remove(oldPrimitive); this.oldPrimitive = undefined; } }; /** * @private */ var StaticGeometryColorBatch = function(primitives, appearanceType, closed) { this._solidBatch = new Batch(primitives, false, appearanceType, closed); this._translucentBatch = new Batch(primitives, true, appearanceType, closed); }; StaticGeometryColorBatch.prototype.add = function(time, updater) { var instance = updater.createFillGeometryInstance(time); if (instance.attributes.color.value[3] === 255) { this._solidBatch.add(updater, instance); } else { this._translucentBatch.add(updater, instance); } }; StaticGeometryColorBatch.prototype.remove = function(updater) { if (!this._solidBatch.remove(updater)) { this._translucentBatch.remove(updater); } }; StaticGeometryColorBatch.prototype.update = function(time) { var i; var updater; //Perform initial update var isUpdated = this._solidBatch.update(time); isUpdated = this._translucentBatch.update(time) && isUpdated; //If any items swapped between solid/translucent, we need to //move them between batches var itemsToRemove = this._solidBatch.itemsToRemove; var solidsToMoveLength = itemsToRemove.length; if (solidsToMoveLength > 0) { for (i = 0; i < solidsToMoveLength; i++) { updater = itemsToRemove[i]; this._solidBatch.remove(updater); this._translucentBatch.add(updater, updater.createFillGeometryInstance(time)); } } itemsToRemove = this._translucentBatch.itemsToRemove; var translucentToMoveLength = itemsToRemove.length; if (translucentToMoveLength > 0) { for (i = 0; i < translucentToMoveLength; i++) { updater = itemsToRemove[i]; this._translucentBatch.remove(updater); this._solidBatch.add(updater, updater.createFillGeometryInstance(time)); } } //If we moved anything around, we need to re-build the primitive if (solidsToMoveLength > 0 || translucentToMoveLength > 0) { isUpdated = this._solidBatch.update(time) && isUpdated; isUpdated = this._translucentBatch.update(time) && isUpdated; } return isUpdated; }; StaticGeometryColorBatch.prototype.getBoundingSphere = function(entity, result) { if (this._solidBatch.contains(entity)) { return this._solidBatch.getBoundingSphere(entity, result); } else if (this._translucentBatch.contains(entity)) { return this._translucentBatch.getBoundingSphere(entity, result); } return BoundingSphereState.FAILED; }; StaticGeometryColorBatch.prototype.removeAllPrimitives = function() { this._solidBatch.removeAllPrimitives(); this._translucentBatch.removeAllPrimitives(); }; return StaticGeometryColorBatch; });
nupic-community/nostradamIQ
nostradamIQ-landingpage/webapp/lib/cesium/1.16/Source/DataSources/StaticGeometryColorBatch.js
JavaScript
gpl-3.0
11,977
<?php /** * * ThinkUp/webapp/plugins/googleplus/tests/TestOfFacebookCrawler.php * * Copyright (c) 2011-2013 Henri Watson * * LICENSE: * * This file is part of ThinkUp (http://thinkup.com). * * ThinkUp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any * later version. * * ThinkUp 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 ThinkUp. If not, see * <http://www.gnu.org/licenses/>. * * * Test of GooglePlusCrawler * * @license http://www.gnu.org/licenses/gpl.html * @copyright 2011-2013 Henri Watson */ require_once dirname(__FILE__) . '/../../../../tests/init.tests.php'; require_once THINKUP_WEBAPP_PATH.'_lib/extlib/simpletest/autorun.php'; require_once THINKUP_WEBAPP_PATH.'_lib/extlib/simpletest/web_tester.php'; require_once THINKUP_WEBAPP_PATH.'plugins/googleplus/model/class.GooglePlusCrawler.php'; require_once THINKUP_WEBAPP_PATH.'plugins/googleplus/tests/classes/mock.GooglePlusAPIAccessor.php'; class TestOfGooglePlusCrawler extends ThinkUpUnitTestCase { /** * * @var Instance */ var $instance; /** * * @var Logger */ var $logger; public function setUp() { parent::setUp(); $this->logger = Logger::getInstance(); $r = array('id'=>1, 'network_username'=>'Gina Trapani', 'network_user_id'=>'113612142759476883204', 'network_viewer_id'=>'113612142759476883204', 'last_post_id'=>'0', 'total_posts_in_system'=>'0', 'total_replies_in_system'=>'0', 'total_follows_in_system'=>'0', 'is_archive_loaded_replies'=>'0', 'is_archive_loaded_follows'=>'0', 'crawler_last_run'=>'', 'earliest_reply_in_system'=>'', 'avg_replies_per_day'=>'2', 'is_public'=>'0', 'is_active'=>'0', 'network'=>'google+', 'last_favorite_id' => '0', 'owner_favs_in_system' => '0', 'total_posts_by_owner'=>0, 'posts_per_day'=>1, 'posts_per_week'=>1, 'percentage_replies'=>50, 'percentage_links'=>50, 'earliest_post_in_system'=>'2009-01-01 13:48:05', 'favorites_profile' => '0' ); $this->profile1_instance = new Instance($r); } private function buildData() { $builders = array(); $builders[] = FixtureBuilder::build('users', array('user_id'=>'113612142759476883204', 'network'=>'google+')); return $builders; } public function tearDown() { parent::tearDown(); $this->logger->close(); } public function testConstructor() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10); $this->assertEqual($gpc->access_token, 'fauxaccesstoken'); } public function testFetchUser() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10); $gpc->fetchUser($this->profile1_instance->network_user_id, $this->profile1_instance->network, true); $user_dao = new UserMySQLDAO(); $user = $user_dao->getUserByName('Gina Trapani', 'google+'); $this->assertTrue(isset($user)); $this->assertEqual($user->username, 'Gina Trapani'); $this->assertEqual($user->full_name, 'Gina Trapani'); $this->assertEqual($user->user_id, 1136121427); $this->assertEqual($user->location, "San Diego"); $this->assertEqual($user->description, 'ThinkUp lead developer, This Week in Google co-host, Todo.txt apps creator, founding editor of Lifehacker'); $this->assertEqual($user->url, ''); $this->assertFalse($user->is_protected); } public function testInitializeInstanceUserFreshToken() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'faux-access-token', 10); $gpc->initializeInstanceUser('ci', 'cs', 'valid_token', 'test_refresh_token', 1); $user_dao = new UserMySQLDAO(); $user = $user_dao->getUserByName('Gina Trapani', 'google+'); $this->assertTrue(isset($user)); $this->assertEqual($user->username, 'Gina Trapani'); $this->assertEqual($user->full_name, 'Gina Trapani'); $this->assertEqual($user->user_id, '113612142759476883204'); $this->assertEqual($user->location, "San Diego"); $this->assertEqual($user->description, 'ThinkUp lead developer, This Week in Google co-host, Todo.txt apps creator, founding editor of Lifehacker'); $this->assertEqual($user->url, ''); $this->assertFalse($user->is_protected); } public function testInitializeInstanceUserExpiredToken() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'faux-expired-access-token', 10); $gpc->initializeInstanceUser('ci', 'cs', 'valid_token', 'test_refresh_token', 1); $user_dao = new UserMySQLDAO(); $user = $user_dao->getUserByName('Gina Trapani', 'google+'); $this->assertTrue(isset($user)); $this->assertEqual($user->username, 'Gina Trapani'); $this->assertEqual($user->full_name, 'Gina Trapani'); $this->assertEqual($user->user_id, '113612142759476883204'); $this->assertEqual($user->location, "San Diego"); $this->assertEqual($user->description, 'ThinkUp lead developer, This Week in Google co-host, Todo.txt apps creator, founding editor of Lifehacker'); $this->assertEqual($user->url, ''); $this->assertFalse($user->is_protected); } public function testGetOAuthTokens() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10); //test getting initial token $tokens = $gpc->getOAuthTokens('ci', 'cs', 'tc1', 'authorization_code'); $this->assertEqual($tokens->access_token, 'faux-access-token'); $this->assertEqual($tokens->refresh_token, 'faux-refresh-token'); //test refreshing token $tokens = $gpc->getOAuthTokens('ci', 'cs', 'test-refresh_token1', 'refresh_token'); $this->assertEqual($tokens->access_token, 'faux-access-token'); $this->assertEqual($tokens->refresh_token, 'faux-refresh-token'); } public function testGetOAuthTokensWithAndWithoutSSL() { $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10); //test getting token with HTTPS $_SERVER['SERVER_NAME'] = 'test'; $_SERVER['HTTPS'] = 'y'; $cfg = Config::getInstance(); $cfg->setValue('site_root_path', '/'); $redirect_uri = urlencode(Utils::getApplicationURL().'account/?p=google%2B'); $tokens = $gpc->getOAuthTokens('ci', 'cs', 'tc1', 'authorization_code', $redirect_uri); $this->assertEqual($tokens->access_token, 'faux-access-token-with-https'); $this->assertEqual($tokens->refresh_token, 'faux-refresh-token-with-https'); //test getting token without HTTPS $_SERVER['HTTPS'] = null; $redirect_uri = urlencode(Utils::getApplicationURL().'account/?p=google%2B'); $tokens = $gpc->getOAuthTokens('ci', 'cs', 'tc1', 'authorization_code', $redirect_uri); $this->assertEqual($tokens->access_token, 'faux-access-token-without-https'); $this->assertEqual($tokens->refresh_token, 'faux-refresh-token-without-https'); } public function testFetchInstanceUserPosts() { $builders = self::buildData(); $gpc = new GooglePlusCrawler($this->profile1_instance, 'fauxaccesstoken', 10); $gpc->fetchInstanceUserPosts(); $post_dao = new PostMySQLDAO(); $post = $post_dao->getPost('z12is5v4snurihgdl22iiz3pjrnws3lle', 'google+', true); $this->assertIsA($post, 'Post'); $this->assertEqual($post->post_text, 'I&#39;ve got a date with the G+ API this weekend to make a ThinkUp plugin!'); $this->assertEqual($post->reply_count_cache, 24); $this->assertEqual($post->favlike_count_cache, 159); $this->assertEqual($post->retweet_count_cache, 29); $this->assertIsA($post->links[0], 'Link'); $this->assertEqual($post->links[0]->url, 'http://googleplusplatform.blogspot.com/2011/09/getting-started-on-google-api.html'); $this->assertEqual($post->links[0]->title, 'Getting Started on the Google+ API - Google+ Platform Blog'); $this->assertEqual($post->links[0]->description, 'Official source of information about the Google+ platform'); $this->assertEqual($post->links[0]->image_src, ''); //test reshare with annotation $post = $post_dao->getPost('z12pcfdr2wvyzjfff22iiz3pjrnws3lle', 'google+', true); $this->assertIsA($post, 'Post'); $this->assertEqual($post->post_text, 'Really fun episode this week.'); //test reshare without annotation $post = $post_dao->getPost('z12pxlfjxpujivy3e230t3aqawfoz1qf1', 'google+', true); $this->assertIsA($post, 'Post'); $this->assertEqual($post->post_text, ''); //now crawl on updated data and assert counts and post text get updated in database $gpc->api_accessor->setDataLocation('new_counts/'); $gpc->fetchInstanceUserPosts(); $post = $post_dao->getPost('z12is5v4snurihgdl22iiz3pjrnws3lle', 'google+', true); $this->assertEqual($post->reply_count_cache, 64); $this->assertEqual($post->favlike_count_cache, 199); $this->assertEqual($post->retweet_count_cache, 69); $this->assertEqual($post->post_text, "I&#39;ve got a date with the G+ API this weekend to make a ThinkUp plugin! Updated: New text here!"); } }
anildash/ThinkUp
webapp/plugins/googleplus/tests/TestOfGooglePlusCrawler.php
PHP
gpl-3.0
9,876
using Fomm.Controls; namespace Fomm.FileManager { partial class FileManager { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FileManager)); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.tvwFolders = new System.Windows.Forms.TreeView(); this.imlFolders = new System.Windows.Forms.ImageList(this.components); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this.lvwFiles = new System.Windows.Forms.ListView(); this.chdName = new System.Windows.Forms.ColumnHeader(); this.chdDateCreated = new System.Windows.Forms.ColumnHeader(); this.chdDateModified = new System.Windows.Forms.ColumnHeader(); this.chdSize = new System.Windows.Forms.ColumnHeader(); this.imlFiles = new System.Windows.Forms.ImageList(this.components); this.panel1 = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.panel2 = new System.Windows.Forms.Panel(); this.radByFile = new System.Windows.Forms.RadioButton(); this.radByMod = new System.Windows.Forms.RadioButton(); this.rlvOverwrites = new ReordableItemListView(); this.chdModName = new System.Windows.Forms.ColumnHeader(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.tvwFolders); this.splitContainer1.Panel1.Controls.Add(this.panel2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); this.splitContainer1.Size = new System.Drawing.Size(806, 466); this.splitContainer1.SplitterDistance = 268; this.splitContainer1.TabIndex = 0; // // tvwFolders // this.tvwFolders.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwFolders.HideSelection = false; this.tvwFolders.ImageKey = "Folder_Open.png"; this.tvwFolders.ImageList = this.imlFolders; this.tvwFolders.Location = new System.Drawing.Point(0, 28); this.tvwFolders.Name = "tvwFolders"; this.tvwFolders.SelectedImageKey = "Folder_Open.png"; this.tvwFolders.Size = new System.Drawing.Size(268, 438); this.tvwFolders.TabIndex = 0; this.tvwFolders.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvwFolders_AfterSelect); // // imlFolders // this.imlFolders.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imlFolders.ImageStream"))); this.imlFolders.TransparentColor = System.Drawing.Color.Transparent; this.imlFolders.Images.SetKeyName(0, "Folder_Open.png"); // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this.lvwFiles); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.rlvOverwrites); this.splitContainer2.Panel2.Controls.Add(this.panel1); this.splitContainer2.Size = new System.Drawing.Size(534, 466); this.splitContainer2.SplitterDistance = 168; this.splitContainer2.TabIndex = 0; // // lvwFiles // this.lvwFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.chdName, this.chdDateCreated, this.chdDateModified, this.chdSize}); this.lvwFiles.Dock = System.Windows.Forms.DockStyle.Fill; this.lvwFiles.HideSelection = false; this.lvwFiles.Location = new System.Drawing.Point(0, 0); this.lvwFiles.Name = "lvwFiles"; this.lvwFiles.Size = new System.Drawing.Size(534, 168); this.lvwFiles.SmallImageList = this.imlFiles; this.lvwFiles.TabIndex = 0; this.lvwFiles.UseCompatibleStateImageBehavior = false; this.lvwFiles.View = System.Windows.Forms.View.Details; this.lvwFiles.SelectedIndexChanged += new System.EventHandler(this.lvwFiles_SelectedIndexChanged); // // chdName // this.chdName.Text = "Name"; this.chdName.Width = 200; // // chdDateCreated // this.chdDateCreated.Text = "Date Created"; this.chdDateCreated.Width = 125; // // chdDateModified // this.chdDateModified.Text = "Date Modified"; this.chdDateModified.Width = 125; // // chdSize // this.chdSize.Text = "Size"; this.chdSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.chdSize.Width = 80; // // imlFiles // this.imlFiles.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit; this.imlFiles.ImageSize = new System.Drawing.Size(16, 16); this.imlFiles.TransparentColor = System.Drawing.Color.Transparent; // // panel1 // this.panel1.Controls.Add(this.label1); this.panel1.Dock = System.Windows.Forms.DockStyle.Top; this.panel1.Location = new System.Drawing.Point(0, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(534, 41); this.panel1.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(329, 39); this.label1.TabIndex = 0; this.label1.Text = "Drag/Drop to modify which mod\'s file version is used.\r\nMods towards the bottom ov" + "erride those above them.\r\nThe green highlighted mod is the one whose file is cur" + "rently installed.\r\n"; // // panel2 // this.panel2.Controls.Add(this.radByMod); this.panel2.Controls.Add(this.radByFile); this.panel2.Dock = System.Windows.Forms.DockStyle.Top; this.panel2.Location = new System.Drawing.Point(0, 0); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(268, 28); this.panel2.TabIndex = 1; // // radByFile // this.radByFile.Appearance = System.Windows.Forms.Appearance.Button; this.radByFile.AutoSize = true; this.radByFile.Checked = true; this.radByFile.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.radByFile.Location = new System.Drawing.Point(3, 3); this.radByFile.Name = "radByFile"; this.radByFile.Size = new System.Drawing.Size(79, 25); this.radByFile.TabIndex = 1; this.radByFile.TabStop = true; this.radByFile.Text = "Order By File"; this.radByFile.UseVisualStyleBackColor = true; this.radByFile.CheckedChanged += new System.EventHandler(this.radByFile_CheckedChanged); // // radByMod // this.radByMod.Appearance = System.Windows.Forms.Appearance.Button; this.radByMod.AutoSize = true; this.radByMod.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.radByMod.Location = new System.Drawing.Point(80, 3); this.radByMod.Name = "radByMod"; this.radByMod.Size = new System.Drawing.Size(84, 25); this.radByMod.TabIndex = 2; this.radByMod.Text = "Order By Mod"; this.radByMod.UseVisualStyleBackColor = true; // // rlvOverwrites // this.rlvOverwrites.AllowDrop = true; this.rlvOverwrites.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.chdModName}); this.rlvOverwrites.Dock = System.Windows.Forms.DockStyle.Fill; this.rlvOverwrites.FullRowSelect = true; this.rlvOverwrites.Location = new System.Drawing.Point(0, 41); this.rlvOverwrites.Name = "rlvOverwrites"; this.rlvOverwrites.ShowGroups = false; this.rlvOverwrites.Size = new System.Drawing.Size(534, 253); this.rlvOverwrites.TabIndex = 0; this.rlvOverwrites.UseCompatibleStateImageBehavior = false; this.rlvOverwrites.View = System.Windows.Forms.View.Details; this.rlvOverwrites.SizeChanged += new System.EventHandler(this.rlvOverwrites_SizeChanged); this.rlvOverwrites.DragDrop += new System.Windows.Forms.DragEventHandler(this.rlvOverwrites_DragDrop); // // chdModName // this.chdModName.Text = "Mod Name"; this.chdModName.Width = 400; // // FileManager // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(806, 466); this.Controls.Add(this.splitContainer1); this.Name = "FileManager"; this.ShowInTaskbar = false; this.Text = "File Manager"; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); this.splitContainer2.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.TreeView tvwFolders; private System.Windows.Forms.ImageList imlFolders; private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.ListView lvwFiles; private ReordableItemListView rlvOverwrites; private System.Windows.Forms.ColumnHeader chdName; private System.Windows.Forms.ColumnHeader chdDateCreated; private System.Windows.Forms.ColumnHeader chdDateModified; private System.Windows.Forms.ColumnHeader chdSize; private System.Windows.Forms.ImageList imlFiles; private System.Windows.Forms.ColumnHeader chdModName; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.RadioButton radByMod; private System.Windows.Forms.RadioButton radByFile; } }
lehjr/fomm
flmm/FileManager/FileManager.Designer.cs
C#
gpl-3.0
11,869
/* -*- c++ -*- */ /* * Copyright 2002 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <gr_fir_scc_generic.h> #if (2 == 4) gr_complex gr_fir_scc_generic::filter (const short input[]) { static const int N_UNROLL = 4; gr_complex acc0 = 0; gr_complex acc1 = 0; gr_complex acc2 = 0; gr_complex acc3 = 0; unsigned i = 0; unsigned n = (ntaps () / N_UNROLL) * N_UNROLL; for (i = 0; i < n; i += N_UNROLL){ acc0 += d_taps[i + 0] * (float) input[i + 0]; acc1 += d_taps[i + 1] * (float) input[i + 1]; acc2 += d_taps[i + 2] * (float) input[i + 2]; acc3 += d_taps[i + 3] * (float) input[i + 3]; } for (; i < ntaps (); i++) acc0 += d_taps[i] * (float) input[i]; return (gr_complex) (acc0 + acc1 + acc2 + acc3); } #else gr_complex gr_fir_scc_generic::filter (const short input[]) { static const int N_UNROLL = 2; gr_complex acc0 = 0; gr_complex acc1 = 0; unsigned i = 0; unsigned n = (ntaps () / N_UNROLL) * N_UNROLL; for (i = 0; i < n; i += N_UNROLL){ acc0 += d_taps[i + 0] * (float) input[i + 0]; acc1 += d_taps[i + 1] * (float) input[i + 1]; } for (; i < ntaps (); i++) acc0 += d_taps[i] * (float) input[i]; return (gr_complex) (acc0 + acc1); } #endif // N_UNROLL void gr_fir_scc_generic::filterN (gr_complex output[], const short input[], unsigned long n) { for (unsigned i = 0; i < n; i++) output[i] = filter (&input[i]); } void gr_fir_scc_generic::filterNdec (gr_complex output[], const short input[], unsigned long n, unsigned decimate) { unsigned j = 0; for (unsigned i = 0; i < n; i++){ output[i] = filter (&input[j]); j += decimate; } }
aviralchandra/Sandhi
build/gr36/gnuradio-core/src/lib/filter/gr_fir_scc_generic.cc
C++
gpl-3.0
2,462
# -*- coding: utf-8 -*- # Copyright (C) Alex Urban (2019) # # This file is part of the GW DetChar python package. # # GW DetChar 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. # # GW DetChar 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 gwdetchar. If not, see <http://www.gnu.org/licenses/>. """Tests for `gwdetchar.omega.batch` """ import os import shutil import numpy.testing as nptest from getpass import getuser from pycondor import Dagman from gwpy.testing.compat import mock from .. import batch __author__ = 'Alex Urban <[email protected]>' # global test objects FLAGS = [ '--ifo', 'X1', '--colormap', 'viridis', '--nproc', '8', '--far-threshold', '3.171e-08', '--disable-correlation', '--disable-checkpoint', '--ignore-state-flags', ] CONDORCMDS = [ 'accounting_group = ligo.dev.o1.detchar.user_req.omegascan', 'accounting_group_user = {}'.format(getuser()), 'periodic_remove = CurrentTime-EnteredCurrentStatus > 14400', 'test', ] # -- unit tests --------------------------------------------------------------- def test_get_command_line_flags(): ifo = 'X1' flags = batch.get_command_line_flags( ifo, disable_correlation=True, disable_checkpoint=True, ignore_state_flags=True) nptest.assert_array_equal(flags, FLAGS) def test_get_condor_arguments(): gps = 1126259462 condorcmds = batch.get_condor_arguments( timeout=4, extra_commands=['test'], gps=gps) nptest.assert_array_equal(condorcmds, CONDORCMDS) @mock.patch('pycondor.Dagman.submit_dag') def test_generate_dag(dag, tmpdir, capsys): outdir = str(tmpdir) times = [1187008882] dag.return_value = 1 # test without submit dagman = batch.generate_dag( times, flags=FLAGS, outdir=outdir, condor_commands=CONDORCMDS) assert isinstance(dagman, Dagman) assert os.path.exists(os.path.join(outdir, 'condor')) assert os.path.exists(os.path.join(outdir, 'logs')) captured = capsys.readouterr() assert captured.out.startswith('The directory') assert 'Submit to condor via' in captured.out # test with submit dagman = batch.generate_dag( times, flags=FLAGS, submit=True, outdir=outdir, condor_commands=CONDORCMDS) captured = capsys.readouterr() assert 'condor_q' in captured.out # clean up shutil.rmtree(outdir, ignore_errors=True)
tjmassin/gwdetchar
gwdetchar/omega/tests/test_batch.py
Python
gpl-3.0
2,838