repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
samsymons/SnapchatKit | Example/SnapchatKit-OSX/SnapchatKit-OSX/TBTimer.h | 345 | //
// TBTimeInterval.h
// BU Eats
//
// Created by Tanner on 4/24/15.
// Copyright (c) 2015 Tanner Bennett. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface TBTimer : NSObject
+ (void)startTimer;
+ (CGFloat)lap;
@property (nonatomic, readonly) NSDate *startTime;
@property (nonatomic, readonly) NSDate *endTime;
@end | mit |
devosc/mvc5 | src/Plugin/Gem/Copy.php | 142 | <?php
/**
*
*/
namespace Mvc5\Plugin\Gem;
interface Copy
extends Gem
{
/**
* @return object
*/
function config();
}
| mit |
markdev/markandkitty | concrete/blocks/date_nav/tools/preview_pane.php | 898 | <?php
defined('C5_EXECUTE') or die(_("Access Denied."));
Loader::block('page_list');
$previewMode = true;
$nh = Loader::helper('navigation');
$controller = new PageListBlockController($b);
$_REQUEST['num'] = ($_REQUEST['num'] > 0) ? $_REQUEST['num'] : 0;
$_REQUEST['cThis'] = ($_REQUEST['cParentID'] == $controller->cID) ? '1' : '0';
$_REQUEST['cParentID'] = ($_REQUEST['cParentID'] == 'OTHER') ? $_REQUEST['cParentIDValue'] : $_REQUEST['cParentID'];
$controller->num = $_REQUEST['num'];
$controller->cParentID = $_REQUEST['cParentID'];
$controller->cThis = $_REQUEST['cThis'];
$controller->orderBy = $_REQUEST['orderBy'];
$controller->ctID = $_REQUEST['ctID'];
$controller->rss = $_REQUEST['rss'];
$controller->displayFeaturedOnly = $_REQUEST['displayFeaturedOnly'];
$cArray = $controller->getPages();
//echo var_dump($cArray);
require(dirname(__FILE__) . '/../view.php');
exit; | mit |
mmkassem/gitlabhq | app/uploaders/avatar_uploader.rb | 746 | # frozen_string_literal: true
class AvatarUploader < GitlabUploader
include UploaderHelper
include RecordsUploads::Concern
include ObjectStorage::Concern
prepend ObjectStorage::Extension::RecordsUploads
MIME_WHITELIST = %w[image/png image/jpeg image/gif image/bmp image/tiff image/vnd.microsoft.icon].freeze
def exists?
model.avatar.file && model.avatar.file.present?
end
def move_to_store
false
end
def move_to_cache
false
end
def absolute_path
self.class.absolute_path(upload)
end
def mounted_as
super || 'avatar'
end
def content_type_whitelist
MIME_WHITELIST
end
private
def dynamic_segment
File.join(model.class.underscore, mounted_as.to_s, model.id.to_s)
end
end
| mit |
GawainLynch/bolt | tests/phpunit/unit/Controller/Backend/UsersTest.php | 13704 | <?php
namespace Bolt\Tests\Controller\Backend;
use Bolt\Storage\Entity;
use Bolt\Tests\Controller\ControllerUnitTest;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* Class to test correct operation of src/Controller/Backend/Users.
*
* @author Ross Riley <[email protected]>
* @author Gawain Lynch <[email protected]>
**/
class UsersTest extends ControllerUnitTest
{
public function testAdmin()
{
$this->setRequest(Request::create('/bolt/users'));
$response = $this->controller()->admin();
$context = $response->getContext();
$this->assertNotNull($context['context']['users']);
$this->assertNotNull($context['context']['sessions']);
}
public function testEdit()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/users/edit/1'));
// This one should redirect because of permission failure
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we allow the permsission check to return true
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
$response = $this->controller()->edit($this->getRequest(), 1);
$context = $response->getContext();
$this->assertEquals('edit', $context['context']['kind']);
$this->assertInstanceOf(FormView::class, $context['context']['form']);
$this->assertEquals('Admin', $context['context']['displayname']);
// Test that an empty user gives a create form
$this->setRequest(Request::create('/bolt/users/edit'));
$response = $this->controller()->edit($this->getRequest(), null);
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
}
public function testUserEditPost()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/useredit/1',
'POST',
[
'user_edit' => [
'username' => $user['username'],
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testFirst()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
// Because we have users in the database this should exit at first attempt
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$this->assertEquals('/bolt', $response->getTargetUrl());
// Now we delete the users
$this->getService('db')->executeQuery('DELETE FROM bolt_users;');
$this->getService('users')->users = [];
$this->setRequest(Request::create('/bolt/userfirst'));
$response = $this->controller()->first($this->getRequest());
$context = $response->getContext();
$this->assertEquals('create', $context['context']['kind']);
// This block attempts to create the user
$request = Request::create(
'/bolt/userfirst',
'POST',
[
'user_new' => [
'username' => 'admin',
'email' => '[email protected]',
'displayname' => 'Admin',
'password' => [
'first' => 'password',
'second' => 'password',
],
'_token' => 'xyz',
],
]
);
$this->setRequest($request);
$this->getService('request_stack')->push($request);
$response = $this->controller()->first($this->getRequest());
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt', $response->getTargetUrl());
}
public function testModifyBadCsrf()
{
// First test should exit/redirect with no anti CSRF token
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 1);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/Something went wrong/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testModifyValidCsrf()
{
// Now we mock the CSRF token to validate
$this->removeCSRF();
$currentuser = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($currentuser));
// This request should fail because the user doesnt exist.
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 42);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such user/', $err[0]);
// This check will fail because we are operating on the current user
$this->setRequest(Request::create('/bolt/user/disable/1'));
$response = $this->controller()->modify('disable', 1);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/yourself/', $err[0]);
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
// And retry the operation that will work now
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now try to enable the user
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Try a non-existent action, make sure we get an error
$this->setRequest(Request::create('/bolt/user/enhance/2'));
$response = $this->controller()->modify('enhance', $editor['id']);
$info = $this->getFlashBag()->get('error');
$this->assertRegExp('/No such action/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Now we run a delete action
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', $editor['id']);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/is deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
// Finally we mock the permsission check to return false and check
// we get a priileges error.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
$editor = $this->getService('users')->getUser('editor');
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(false));
$this->setService('permissions', $perms);
$this->setRequest(Request::create('/bolt/user/disable/' . $editor['id']));
$response = $this->controller()->modify('disable', $editor['id']);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$err = $this->getFlashBag()->get('error');
$this->assertRegExp('/right privileges/', $err[0]);
}
public function testModifyFailures()
{
// We add a new user that isn't the current user and now perform operations.
$this->addNewUser($this->getApp(), 'editor', 'Editor', 'editor');
// Now we mock the CSRF token to validate
$this->removeCSRF();
$users = $this->getMockUsers(['setEnabled', 'deleteUser']);
$users->expects($this->any())
->method('setEnabled')
->will($this->returnValue(false));
$users->expects($this->any())
->method('deleteUser')
->will($this->returnValue(false));
$this->setService('users', $users);
// Setup the current user
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// This mocks a failure and ensures the error is reported
$this->setRequest(Request::create('/bolt/user/disable/2'));
$response = $this->controller()->modify('disable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be disabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/enable/2'));
$response = $this->controller()->modify('enable', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be enabled/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
$this->setRequest(Request::create('/bolt/user/delete/2'));
$response = $this->controller()->modify('delete', 2);
$info = $this->getFlashBag()->get('info');
$this->assertRegExp('/could not be deleted/', $info[0]);
$this->assertEquals('/bolt/users', $response->getTargetUrl());
}
public function testProfile()
{
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
$this->setRequest(Request::create('/bolt/profile'));
$response = $this->controller()->profile($this->getRequest());
$context = $response->getContext();
$this->assertEquals('@bolt/edituser/edituser.twig', $response->getTemplate());
$this->assertEquals('profile', $context['context']['kind']);
// Now try a POST to update the profile
$this->setRequest(Request::create(
'/bolt/profile',
'POST',
[
'user_profile' => [
'email' => $user['email'],
'displayname' => 'Admin Test',
'_token' => 'xyz',
],
]
));
$this->controller()->profile($this->getRequest());
$this->assertNotEmpty($this->getFlashBag()->get('success'));
}
public function testUsernameEditKillsSession()
{
$user = $this->getService('users')->getUser(1);
$this->setSessionUser(new Entity\Users($user));
// Symfony forms need a CSRF token so we have to mock this too
$this->removeCSRF();
$perms = $this->getMockPermissions();
$perms->expects($this->any())
->method('isAllowedToManipulate')
->will($this->returnValue(true));
$this->setService('permissions', $perms);
// Update the display name via a POST request
$this->setRequest(Request::create(
'/bolt/users/edit/1',
'POST',
[
'user_edit' => [
'username' => 'admin2',
'email' => $user['email'],
'displayname' => $user['displayname'],
'_token' => 'xyz',
],
]
));
$response = $this->controller()->edit($this->getRequest(), 1);
$this->assertInstanceOf(RedirectResponse::class, $response);
$this->assertEquals('/bolt/login', $response->getTargetUrl());
}
public function testViewRoles()
{
$this->setRequest(Request::create('/bolt/roles'));
$response = $this->controller()->viewRoles();
$context = $response->getContext();
$this->assertEquals('@bolt/roles/roles.twig', $response->getTemplate());
$this->assertNotEmpty($context['context']['global_permissions']);
$this->assertNotEmpty($context['context']['effective_permissions']);
}
/**
* @return \Bolt\Controller\Backend\Users
*/
protected function controller()
{
return $this->getService('controller.backend.users');
}
}
| mit |
stewartSG/the_commentable_gem | spec/dummy_app/db/schema.rb | 2876 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20131027185334) do
create_table "comments", force: true do |t|
t.integer "user_id"
t.integer "holder_id"
t.integer "commentable_id"
t.string "commentable_type"
t.string "commentable_url"
t.string "commentable_title"
t.string "commentable_state"
t.string "anchor"
t.string "title"
t.string "contacts"
t.text "raw_content"
t.text "content"
t.string "view_token"
t.string "state", default: "draft"
t.string "ip", default: "undefined"
t.string "referer", default: "undefined"
t.string "user_agent", default: "undefined"
t.integer "tolerance_time"
t.boolean "spam", default: false
t.integer "parent_id"
t.integer "lft"
t.integer "rgt"
t.integer "depth", default: 0
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "posts", force: true do |t|
t.integer "user_id"
t.string "title"
t.text "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "draft_comments_count", default: 0
t.integer "published_comments_count", default: 0
t.integer "deleted_comments_count", default: 0
end
create_table "users", force: true do |t|
t.string "username", null: false
t.string "email"
t.string "crypted_password"
t.string "salt"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "my_draft_comments_count", default: 0
t.integer "my_published_comments_count", default: 0
t.integer "my_comments_count", default: 0
t.integer "draft_comcoms_count", default: 0
t.integer "published_comcoms_count", default: 0
t.integer "deleted_comcoms_count", default: 0
t.integer "spam_comcoms_count", default: 0
t.integer "draft_comments_count", default: 0
t.integer "published_comments_count", default: 0
t.integer "deleted_comments_count", default: 0
end
end
| mit |
blesh/angular | packages/language-service/src/definitions.ts | 5793 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript'; // used as value and is provided at runtime
import {locateSymbols} from './locate_symbol';
import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';
import {AstResult, Span} from './types';
import {extractAbsoluteFilePath} from './utils';
/**
* Convert Angular Span to TypeScript TextSpan. Angular Span has 'start' and
* 'end' whereas TS TextSpan has 'start' and 'length'.
* @param span Angular Span
*/
function ngSpanToTsTextSpan(span: Span): ts.TextSpan {
return {
start: span.start,
length: span.end - span.start,
};
}
/**
* Attempts to get the definition of a file whose URL is specified in a property assignment in a
* directive decorator.
* Currently applies to `templateUrl` and `styleUrls` properties.
*/
function getUrlFromProperty(
urlNode: ts.StringLiteralLike,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
// an array of strings:
// {
// templateUrl: './template.ng.html',
// styleUrls: ['./style.css', './other-style.css']
// }
// `templateUrl`'s property assignment can be found from the string literal node;
// `styleUrls`'s property assignment can be found from the array (parent) node.
//
// First search for `templateUrl`.
let asgn = getPropertyAssignmentFromValue(urlNode, 'templateUrl');
if (!asgn) {
// `templateUrl` assignment not found; search for `styleUrls` array assignment.
asgn = getPropertyAssignmentFromValue(urlNode.parent, 'styleUrls');
if (!asgn) {
// Nothing found, bail.
return;
}
}
// If the property assignment is not a property of a class decorator, don't generate definitions
// for it.
if (!getClassDeclFromDecoratorProp(asgn)) {
return;
}
// Extract url path specified by the url node, which is relative to the TypeScript source file
// the url node is defined in.
const url = extractAbsoluteFilePath(urlNode);
// If the file does not exist, bail. It is possible that the TypeScript language service host
// does not have a `fileExists` method, in which case optimistically assume the file exists.
if (tsLsHost.fileExists && !tsLsHost.fileExists(url)) return;
const templateDefinitions: ts.DefinitionInfo[] = [{
kind: ts.ScriptElementKind.externalModuleName,
name: url,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
// Reading the template is expensive, so don't provide a preview.
textSpan: {start: 0, length: 0},
fileName: url,
}];
return {
definitions: templateDefinitions,
textSpan: {
// Exclude opening and closing quotes in the url span.
start: urlNode.getStart() + 1,
length: urlNode.getWidth() - 2,
},
};
}
/**
* Traverse the template AST and look for the symbol located at `position`, then
* return its definition and span of bound text.
* @param info
* @param position
*/
export function getDefinitionAndBoundSpan(
info: AstResult, position: number): ts.DefinitionInfoAndBoundSpan|undefined {
const symbols = locateSymbols(info, position);
if (!symbols.length) {
return;
}
const seen = new Set<string>();
const definitions: ts.DefinitionInfo[] = [];
for (const symbolInfo of symbols) {
const {symbol} = symbolInfo;
// symbol.definition is really the locations of the symbol. There could be
// more than one. No meaningful info could be provided without any location.
const {kind, name, container, definition: locations} = symbol;
if (!locations || !locations.length) {
continue;
}
const containerKind =
container ? container.kind as ts.ScriptElementKind : ts.ScriptElementKind.unknown;
const containerName = container ? container.name : '';
for (const {fileName, span} of locations) {
const textSpan = ngSpanToTsTextSpan(span);
// In cases like two-way bindings, a request for the definitions of an expression may return
// two of the same definition:
// [(ngModel)]="prop"
// ^^^^ -- one definition for the property binding, one for the event binding
// To prune duplicate definitions, tag definitions with unique location signatures and ignore
// definitions whose locations have already been seen.
const signature = `${textSpan.start}:${textSpan.length}@${fileName}`;
if (seen.has(signature)) continue;
definitions.push({
kind: kind as ts.ScriptElementKind,
name,
containerKind,
containerName,
textSpan: ngSpanToTsTextSpan(span),
fileName: fileName,
});
seen.add(signature);
}
}
return {
definitions,
textSpan: symbols[0].span,
};
}
/**
* Gets an Angular-specific definition in a TypeScript source file.
*/
export function getTsDefinitionAndBoundSpan(
sf: ts.SourceFile, position: number,
tsLsHost: Readonly<ts.LanguageServiceHost>): ts.DefinitionInfoAndBoundSpan|undefined {
const node = findTightestNode(sf, position);
if (!node) return;
switch (node.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
// Attempt to extract definition of a URL in a property assignment.
return getUrlFromProperty(node as ts.StringLiteralLike, tsLsHost);
default:
return undefined;
}
}
| mit |
camperjz/trident | modules/boonex/accounts/updates/8.0.1_8.0.2/source/classes/BxAccntConfig.php | 2465 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*
* @defgroup Accounts Accounts
* @ingroup DolphinModules
*
* @{
*/
class BxAccntConfig extends BxBaseModGeneralConfig
{
protected $_oDb;
protected $_aHtmlIds;
/**
* Constructor
*/
public function __construct($aModule)
{
parent::__construct($aModule);
$this->CNF = array (
// page URIs
'URL_MANAGE_ADMINISTRATION' => 'page.php?i=accounts-administration',
// objects
'OBJECT_MENU_MANAGE_TOOLS' => 'bx_accounts_menu_manage_tools', //manage menu in content administration tools
'OBJECT_GRID_ADMINISTRATION' => 'bx_accounts_administration',
'OBJECT_GRID_MODERATION' => 'bx_accounts_moderation',
// some language keys
'T' => array (
'grid_action_err_delete' => '_bx_accnt_grid_action_err_delete',
'grid_action_err_perform' => '_bx_accnt_grid_action_err_perform',
'filter_item_active' => '_bx_accnt_grid_filter_item_title_adm_active',
'filter_item_pending' => '_bx_accnt_grid_filter_item_title_adm_pending',
'filter_item_suspended' => '_bx_accnt_grid_filter_item_title_adm_suspended',
'filter_item_select_one_filter1' => '_bx_accnt_grid_filter_item_title_adm_select_one_filter1',
)
);
$this->_aObjects = array(
'alert' => $this->_sName,
);
$this->_aJsClass = array(
'manage_tools' => 'BxAccntManageTools'
);
$this->_aJsObjects = array(
'manage_tools' => 'oBxAccntManageTools'
);
$this->_aGridObjects = array(
'moderation' => $this->CNF['OBJECT_GRID_MODERATION'],
'administration' => $this->CNF['OBJECT_GRID_ADMINISTRATION'],
);
$sHtmlPrefix = str_replace('_', '-', $this->_sName);
$this->_aHtmlIds = array(
'profile' => $sHtmlPrefix . '-profile-',
'profile_more_popup' => $sHtmlPrefix . '-profile-more-popup-',
);
}
public function init(&$oDb)
{
$this->_oDb = &$oDb;
}
public function getHtmlIds($sKey = '')
{
if(empty($sKey))
return $this->_aHtmlIds;
return isset($this->_aHtmlIds[$sKey]) ? $this->_aHtmlIds[$sKey] : '';
}
}
/** @} */
| mit |
pjhooker/monferratopaesaggi | trunk/wp-content/plugins/jetpack/sal/class.json-api-site-jetpack.php | 7587 | <?php
use Automattic\Jetpack\Sync\Functions;
require_once dirname( __FILE__ ) . '/class.json-api-site-jetpack-base.php';
require_once dirname( __FILE__ ) . '/class.json-api-post-jetpack.php';
// this code runs on Jetpack (.org) sites
class Jetpack_Site extends Abstract_Jetpack_Site {
protected function get_mock_option( $name ) {
return get_option( 'jetpack_'.$name );
}
protected function get_constant( $name ) {
if ( defined( $name) ) {
return constant( $name );
}
return null;
}
protected function main_network_site() {
return network_site_url();
}
protected function wp_version() {
global $wp_version;
return $wp_version;
}
protected function max_upload_size() {
return wp_max_upload_size();
}
protected function wp_memory_limit() {
return wp_convert_hr_to_bytes( WP_MEMORY_LIMIT );
}
protected function wp_max_memory_limit() {
return wp_convert_hr_to_bytes( WP_MAX_MEMORY_LIMIT );
}
protected function is_main_network() {
return Jetpack::is_multi_network();
}
public function is_multisite() {
return (bool) is_multisite();
}
public function is_single_user_site() {
return (bool) Jetpack::is_single_user_site();
}
protected function is_version_controlled() {
return Functions::is_version_controlled();
}
protected function file_system_write_access() {
return Functions::file_system_write_access();
}
protected function current_theme_supports( $feature_name ) {
return current_theme_supports( $feature_name );
}
protected function get_theme_support( $feature_name ) {
return get_theme_support( $feature_name );
}
public function get_updates() {
return (array) Jetpack::get_updates();
}
function get_id() {
return $this->platform->token->blog_id;
}
function has_videopress() {
// TODO - this only works on wporg site - need to detect videopress option for remote Jetpack site on WPCOM
$videopress = Jetpack_Options::get_option( 'videopress', array() );
if ( isset( $videopress['blog_id'] ) && $videopress['blog_id'] > 0 ) {
return true;
}
return false;
}
function upgraded_filetypes_enabled() {
return true;
}
function is_mapped_domain() {
return true;
}
function get_unmapped_url() {
// Fallback to the home URL since all Jetpack sites don't have an unmapped *.wordpress.com domain.
return $this->get_url();
}
function is_redirect() {
return false;
}
function is_following() {
return false;
}
function has_wordads() {
return Jetpack::is_module_active( 'wordads' );
}
function get_frame_nonce() {
return false;
}
function get_jetpack_frame_nonce() {
return false;
}
function is_headstart_fresh() {
return false;
}
function allowed_file_types() {
$allowed_file_types = array();
// https://codex.wordpress.org/Uploading_Files
$mime_types = get_allowed_mime_types();
foreach ( $mime_types as $type => $mime_type ) {
$extras = explode( '|', $type );
foreach ( $extras as $extra ) {
$allowed_file_types[] = $extra;
}
}
return $allowed_file_types;
}
/**
* Return site's privacy status.
*
* @return boolean Is site private?
*/
function is_private() {
return (int) $this->get_atomic_cloud_site_option( 'blog_public' ) === -1;
}
/**
* Return site's coming soon status.
*
* @return boolean Is site "Coming soon"?
*/
function is_coming_soon() {
return $this->is_private() && (int) $this->get_atomic_cloud_site_option( 'wpcom_coming_soon' ) === 1;
}
/**
* Return site's launch status.
*
* @return string|boolean Launch status ('launched', 'unlaunched', or false).
*/
function get_launch_status() {
return $this->get_atomic_cloud_site_option( 'launch-status' );
}
function get_atomic_cloud_site_option( $option ) {
if ( ! jetpack_is_atomic_site() ) {
return false;
}
$jetpack = Jetpack::init();
if ( ! method_exists( $jetpack, 'get_cloud_site_options' ) ) {
return false;
}
$result = $jetpack->get_cloud_site_options( [ $option ] );
if ( ! array_key_exists( $option, $result ) ) {
return false;
}
return $result[ $option ];
}
function get_plan() {
return false;
}
function get_subscribers_count() {
return 0; // special magic fills this in on the WPCOM side
}
function get_capabilities() {
return false;
}
function get_locale() {
return get_bloginfo( 'language' );
}
/**
* The flag indicates that the site has Jetpack installed
*
* @return bool
*/
public function is_jetpack() {
return true;
}
/**
* The flag indicates that the site is connected to WP.com via Jetpack Connection
*
* @return bool
*/
public function is_jetpack_connection() {
return true;
}
public function get_jetpack_version() {
return JETPACK__VERSION;
}
function get_ak_vp_bundle_enabled() {}
function get_jetpack_seo_front_page_description() {
return Jetpack_SEO_Utils::get_front_page_meta_description();
}
function get_jetpack_seo_title_formats() {
return Jetpack_SEO_Titles::get_custom_title_formats();
}
function get_verification_services_codes() {
return get_option( 'verification_services_codes', null );
}
function get_podcasting_archive() {
return null;
}
function is_connected_site() {
return true;
}
function is_wpforteams_site() {
return false;
}
function current_user_can( $role ) {
return current_user_can( $role );
}
/**
* Check if full site editing should be considered as currently active. Full site editing
* requires the FSE plugin to be installed and activated, as well the current
* theme to be FSE compatible. The plugin can also be explicitly disabled via the
* a8c_disable_full_site_editing filter.
*
* @since 7.7.0
*
* @return bool true if full site editing is currently active.
*/
function is_fse_active() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_full_site_editing_active' ) && \A8C\FSE\is_full_site_editing_active();
}
/**
* Check if site should be considered as eligible for full site editing. Full site editing
* requires the FSE plugin to be installed and activated. For this method to return true
* the current theme does not need to be FSE compatible. The plugin can also be explicitly
* disabled via the a8c_disable_full_site_editing filter.
*
* @since 8.1.0
*
* @return bool true if site is eligible for full site editing
*/
public function is_fse_eligible() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_eligible_for_full_site_editing' ) && \A8C\FSE\is_site_eligible_for_full_site_editing();
}
/**
* Check if site should be considered as eligible for use of the core Site Editor.
* The Site Editor requires the FSE plugin to be installed and activated.
* The plugin can be explicitly enabled via the a8c_enable_core_site_editor filter.
*
* @return bool true if site is eligible for the Site Editor
*/
public function is_core_site_editor_enabled() {
if ( ! Jetpack::is_plugin_active( 'full-site-editing/full-site-editing-plugin.php' ) ) {
return false;
}
return function_exists( '\A8C\FSE\is_site_editor_active' ) && \A8C\FSE\is_site_editor_active();
}
/**
* Return the last engine used for an import on the site.
*
* This option is not used in Jetpack.
*/
function get_import_engine() {
return null;
}
/**
* Post functions
*/
function wrap_post( $post, $context ) {
return new Jetpack_Post( $this, $post, $context );
}
}
| mit |
claudiobm/ClockingIT-In-CapellaDesign | vendor/gems/mongrel-1.1.5/test/test_uriclassifier.rb | 7361 | # Copyright (c) 2005 Zed A. Shaw
# You can redistribute it and/or modify it under the same terms as Ruby.
#
# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html
# for more information.
require 'test/testhelp'
include Mongrel
class URIClassifierTest < Test::Unit::TestCase
def test_uri_finding
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/test", script_name
end
def test_root_handler_only
uri_classifier = URIClassifier.new
uri_classifier.register("/", 1)
script_name, path_info, value = uri_classifier.resolve("/test")
assert_equal 1, value
assert_equal "/", script_name
assert_equal "/test", path_info
end
def test_uri_prefix_ops
test = "/pre/fix/test"
prefix = "/pre"
uri_classifier = URIClassifier.new
uri_classifier.register(prefix,1)
script_name, path_info, value = uri_classifier.resolve(prefix)
script_name, path_info, value = uri_classifier.resolve(test)
assert_equal 1, value
assert_equal prefix, script_name
assert_equal test[script_name.length .. -1], path_info
assert uri_classifier.inspect
assert_equal prefix, uri_classifier.uris[0]
end
def test_not_finding
test = "/cant/find/me"
uri_classifier = URIClassifier.new
uri_classifier.register(test, 1)
script_name, path_info, value = uri_classifier.resolve("/nope/not/here")
assert_nil script_name
assert_nil path_info
assert_nil value
end
def test_exceptions
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
failed = false
begin
uri_classifier.register("/test", 1)
rescue => e
failed = true
end
assert failed
failed = false
begin
uri_classifier.register("", 1)
rescue => e
failed = true
end
assert failed
end
def test_register_unregister
uri_classifier = URIClassifier.new
100.times do
uri_classifier.register("/stuff", 1)
value = uri_classifier.unregister("/stuff")
assert_equal 1, value
end
uri_classifier.register("/things",1)
script_name, path_info, value = uri_classifier.resolve("/things")
assert_equal 1, value
uri_classifier.unregister("/things")
script_name, path_info, value = uri_classifier.resolve("/things")
assert_nil value
end
def test_uri_branching
uri_classifier = URIClassifier.new
uri_classifier.register("/test", 1)
uri_classifier.register("/test/this",2)
script_name, path_info, handler = uri_classifier.resolve("/test")
script_name, path_info, handler = uri_classifier.resolve("/test/that")
assert_equal "/test", script_name, "failed to properly find script off branch portion of uri"
assert_equal "/that", path_info
assert_equal 1, handler, "wrong result for branching uri"
end
def test_all_prefixing
tests = ["/test","/test/that","/test/this"]
uri = "/test/this/that"
uri_classifier = URIClassifier.new
current = ""
uri.each_byte do |c|
current << c.chr
uri_classifier.register(current, c)
end
# Try to resolve everything with no asserts as a fuzzing
tests.each do |prefix|
current = ""
prefix.each_byte do |c|
current << c.chr
script_name, path_info, handler = uri_classifier.resolve(current)
assert script_name
assert path_info
assert handler
end
end
# Assert that we find stuff
tests.each do |t|
script_name, path_info, handler = uri_classifier.resolve(t)
assert handler
end
# Assert we don't find stuff
script_name, path_info, handler = uri_classifier.resolve("chicken")
assert_nil handler
assert_nil script_name
assert_nil path_info
end
# Verifies that a root mounted ("/") handler resolves
# such that path info matches the original URI.
# This is needed to accommodate real usage of handlers.
def test_root_mounted
uri_classifier = URIClassifier.new
root = "/"
path = "/this/is/a/test"
uri_classifier.register(root, 1)
script_name, path_info, handler = uri_classifier.resolve(root)
assert_equal 1, handler
assert_equal root, path_info
assert_equal root, script_name
script_name, path_info, handler = uri_classifier.resolve(path)
assert_equal path, path_info
assert_equal root, script_name
assert_equal 1, handler
end
# Verifies that a root mounted ("/") handler
# is the default point, doesn't matter the order we use
# to register the URIs
def test_classifier_order
tests = ["/before", "/way_past"]
root = "/"
path = "/path"
uri_classifier = URIClassifier.new
uri_classifier.register(path, 1)
uri_classifier.register(root, 2)
tests.each do |uri|
script_name, path_info, handler = uri_classifier.resolve(uri)
assert_equal root, script_name, "#{uri} did not resolve to #{root}"
assert_equal uri, path_info
assert_equal 2, handler
end
end
if ENV['BENCHMARK']
# Eventually we will have a suite of benchmarks instead of lamely installing a test
def test_benchmark
# This URI set should favor a TST. Both versions increase linearly until you hit 14
# URIs, then the TST flattens out.
@uris = %w(
/
/dag /dig /digbark /dog /dogbark /dog/bark /dug /dugbarking /puppy
/c /cat /cat/tree /cat/tree/mulberry /cats /cot /cot/tree/mulberry /kitty /kittycat
# /eag /eig /eigbark /eog /eogbark /eog/bark /eug /eugbarking /iuppy
# /f /fat /fat/tree /fat/tree/mulberry /fats /fot /fot/tree/mulberry /jitty /jittyfat
# /gag /gig /gigbark /gog /gogbark /gog/bark /gug /gugbarking /kuppy
# /h /hat /hat/tree /hat/tree/mulberry /hats /hot /hot/tree/mulberry /litty /littyhat
# /ceag /ceig /ceigbark /ceog /ceogbark /ceog/cbark /ceug /ceugbarking /ciuppy
# /cf /cfat /cfat/ctree /cfat/ctree/cmulberry /cfats /cfot /cfot/ctree/cmulberry /cjitty /cjittyfat
# /cgag /cgig /cgigbark /cgog /cgogbark /cgog/cbark /cgug /cgugbarking /ckuppy
# /ch /chat /chat/ctree /chat/ctree/cmulberry /chats /chot /chot/ctree/cmulberry /citty /cittyhat
)
@requests = %w(
/
/dig
/digging
/dogging
/dogbarking/
/puppy/barking
/c
/cat
/cat/shrub
/cat/tree
/cat/tree/maple
/cat/tree/mulberry/tree
/cat/tree/oak
/cats/
/cats/tree
/cod
/zebra
)
@classifier = URIClassifier.new
@uris.each do |uri|
@classifier.register(uri, 1)
end
puts "#{@uris.size} URIs / #{@requests.size * 10000} requests"
Benchmark.bm do |x|
x.report do
# require 'ruby-prof'
# profile = RubyProf.profile do
10000.times do
@requests.each do |request|
@classifier.resolve(request)
end
end
# end
# File.open("profile.html", 'w') { |file| RubyProf::GraphHtmlPrinter.new(profile).print(file, 0) }
end
end
end
end
end
| mit |
SuzukiMasashi/idobata-hooks | lib/hooks/pivotal_tracker/helper.rb | 1098 | require 'uri'
module Idobata::Hook
class PivotalTracker
module Helper
filters = [
::HTML::Pipeline::MarkdownFilter
]
filters << ::HTML::Pipeline::SyntaxHighlightFilter if defined?(Linguist) # This filter doesn't work on heroku
Pipeline = ::HTML::Pipeline.new(filters, gfm: true, base_url: 'https://www.pivotaltracker.com/')
def md(source)
result = Pipeline.call(source)
result[:output].to_s.html_safe
end
def new_value(kind)
new_values(kind).first
end
def new_values(kind)
payload.changes.select {|change| change.kind == kind.to_s }.map(&:new_values).compact
end
def download_url(attachment)
download_url = URI.parse(attachment.download_url)
# XXX Current API returns only path info.
unless download_url.host
download_url.scheme = 'https'
download_url.host = 'www.pivotaltracker.com'
end
download_url.query = {inline: true}.to_param unless download_url.query
download_url.to_s
end
end
end
end
| mit |
creative2020/strivela | wp-content/themes/Builder/lib/classes/css/classes.css | 211 | optgroup option {
margin-left: 1em;
}
.valign-top tr {
vertical-align: top;
}
html.thickbox-html,
.thickbox-html body {
min-width: 0;
}
html.thickbox-html,
.thickbox-html body {
margin: 0;
padding: 0;
}
| mit |
cdnjs/cdnjs | ajax/libs/angulartics2/8.3.0/routerlessmodule/fesm2015/angulartics2-routerlessmodule.js | 907 | import { __decorate } from 'tslib';
import { NgModule } from '@angular/core';
import { ANGULARTICS2_TOKEN, RouterlessTracking, Angulartics2, Angulartics2OnModule } from 'angulartics2';
var Angulartics2RouterlessModule_1;
let Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = class Angulartics2RouterlessModule {
static forRoot(settings = {}) {
return {
ngModule: Angulartics2RouterlessModule_1,
providers: [
{ provide: ANGULARTICS2_TOKEN, useValue: { settings } },
RouterlessTracking,
Angulartics2,
],
};
}
};
Angulartics2RouterlessModule = Angulartics2RouterlessModule_1 = __decorate([
NgModule({
imports: [Angulartics2OnModule],
})
], Angulartics2RouterlessModule);
export { Angulartics2RouterlessModule };
//# sourceMappingURL=angulartics2-routerlessmodule.js.map
| mit |
alastrina123/debrief | org.mwc.asset.comms/docs/docs/api/org/restlet/data/class-use/Preference.html | 15761 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_14) on Wed Nov 03 17:42:23 GMT+01:00 2010 -->
<TITLE>
Uses of Class org.restlet.data.Preference (Restlet API 2.0.2 - JSE)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Class org.restlet.data.Preference (Restlet API 2.0.2 - JSE)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/restlet/data/class-use/Preference.html" target="_top"><B>FRAMES</B></A>
<A HREF="Preference.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.restlet.data.Preference</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.restlet.data"><B>org.restlet.data</B></A></TD>
<TD>Information exchanged by components. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#org.restlet.service"><B>org.restlet.service</B></A></TD>
<TD>Services used by applications and components. </TD>
</TR>
</TABLE>
<P>
<A NAME="org.restlet.data"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A> in <A HREF="../../../../org/restlet/data/package-summary.html">org.restlet.data</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../org/restlet/data/package-summary.html">org.restlet.data</A> that return types with arguments of type <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/CharacterSet.html" title="class in org.restlet.data">CharacterSet</A>>></CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#getAcceptedCharacterSets()">getAcceptedCharacterSets</A></B>()</CODE>
<BR>
Returns the modifiable list of character set preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/Encoding.html" title="class in org.restlet.data">Encoding</A>>></CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#getAcceptedEncodings()">getAcceptedEncodings</A></B>()</CODE>
<BR>
Returns the modifiable list of encoding preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/Language.html" title="class in org.restlet.data">Language</A>>></CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#getAcceptedLanguages()">getAcceptedLanguages</A></B>()</CODE>
<BR>
Returns the modifiable list of language preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/MediaType.html" title="class in org.restlet.data">MediaType</A>>></CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#getAcceptedMediaTypes()">getAcceptedMediaTypes</A></B>()</CODE>
<BR>
Returns the modifiable list of media type preferences.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Method parameters in <A HREF="../../../../org/restlet/data/package-summary.html">org.restlet.data</A> with type arguments of type <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#setAcceptedCharacterSets(java.util.List)">setAcceptedCharacterSets</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/CharacterSet.html" title="class in org.restlet.data">CharacterSet</A>>> acceptedCharacterSets)</CODE>
<BR>
Sets the character set preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#setAcceptedEncodings(java.util.List)">setAcceptedEncodings</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/Encoding.html" title="class in org.restlet.data">Encoding</A>>> acceptedEncodings)</CODE>
<BR>
Sets the encoding preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#setAcceptedLanguages(java.util.List)">setAcceptedLanguages</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/Language.html" title="class in org.restlet.data">Language</A>>> acceptedLanguages)</CODE>
<BR>
Sets the language preferences.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ClientInfo.</B><B><A HREF="../../../../org/restlet/data/ClientInfo.html#setAcceptedMediaTypes(java.util.List)">setAcceptedMediaTypes</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/MediaType.html" title="class in org.restlet.data">MediaType</A>>> acceptedMediaTypes)</CODE>
<BR>
Sets the media type preferences.</TD>
</TR>
</TABLE>
<P>
<A NAME="org.restlet.service"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A> in <A HREF="../../../../org/restlet/service/package-summary.html">org.restlet.service</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Method parameters in <A HREF="../../../../org/restlet/service/package-summary.html">org.restlet.service</A> with type arguments of type <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>ConverterService.</B><B><A HREF="../../../../org/restlet/service/ConverterService.html#updatePreferences(java.util.List, java.lang.Class)">updatePreferences</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html" title="class or interface in java.util">List</A><<A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data">Preference</A><<A HREF="../../../../org/restlet/data/MediaType.html" title="class in org.restlet.data">MediaType</A>>> preferences,
<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html" title="class or interface in java.lang">Class</A><?> entity)</CODE>
<BR>
Updates the media type preferences with available conversion capabilities
for the given entity class.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../org/restlet/data/Preference.html" title="class in org.restlet.data"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/restlet/data/class-use/Preference.html" target="_top"><B>FRAMES</B></A>
<A HREF="Preference.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2005-2010 <a target="_top" href="http://www.noelios.com">Noelios Technologies</a>.</i>
</BODY>
</HTML>
| epl-1.0 |
drbgfc/mdht | cda/examples/org.openhealthtools.mdht.cda.builder/src/org/openhealthtools/mdht/uml/cda/builder/test/TestCDABuilderFactory.java | 1871 | /*******************************************************************************
* Copyright (c) 2010, 2011 Sean Muir
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Sean Muir (JKM Software) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.uml.cda.builder.test;
import org.junit.Assert;
import org.junit.Test;
import org.openhealthtools.mdht.uml.cda.ClinicalDocument;
import org.openhealthtools.mdht.uml.cda.Section;
import org.openhealthtools.mdht.uml.cda.builder.CDABuilderFactory;
import org.openhealthtools.mdht.uml.cda.builder.DocumentBuilder;
import org.openhealthtools.mdht.uml.cda.builder.SectionBuilder;
import org.openhealthtools.mdht.uml.cda.util.CDAUtil;
public class TestCDABuilderFactory {
@Test
public void testCreateClinicalDocumentBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
ClinicalDocument clinicalDocument = clinicalDocumentBuilder.buildDocument();
Assert.assertNotNull(clinicalDocument);
CDAUtil.save(clinicalDocument, System.out);
}
@Test
public void testCreateSectionBuilder() throws Exception {
DocumentBuilder<ClinicalDocument> clinicalDocumentBuilder = CDABuilderFactory.createClinicalDocumentBuilder();
SectionBuilder<Section> sectionBuilder = CDABuilderFactory.createSectionBuilder();
Section section = sectionBuilder.buildSection();
Assert.assertNotNull(section);
CDAUtil.save(clinicalDocumentBuilder.with(section).buildDocument(), System.out);
}
}
| epl-1.0 |
drbgfc/mdht | cts2/plugins/org.openhealthtools.mdht.cts2.core/src/org/openhealthtools/mdht/cts2/codesystem/impl/CodeSystemFactoryImpl.java | 5866 | /*******************************************************************************
* Copyright (c) 2012 David A Carlson.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.cts2.codesystem.impl;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryDirectory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryList;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryListEntry;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntryMsg;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemCatalogEntrySummary;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemFactory;
import org.openhealthtools.mdht.cts2.codesystem.CodeSystemPackage;
import org.openhealthtools.mdht.cts2.codesystem.DocumentRoot;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
*
* @generated
*/
public class CodeSystemFactoryImpl extends EFactoryImpl implements CodeSystemFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public static CodeSystemFactory init() {
try {
CodeSystemFactory theCodeSystemFactory = (CodeSystemFactory) EPackage.Registry.INSTANCE.getEFactory("http://schema.omg.org/spec/CTS2/1.0/CodeSystem");
if (theCodeSystemFactory != null) {
return theCodeSystemFactory;
}
} catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new CodeSystemFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY:
return createCodeSystemCatalogEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_DIRECTORY:
return createCodeSystemCatalogEntryDirectory();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST:
return createCodeSystemCatalogEntryList();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_LIST_ENTRY:
return createCodeSystemCatalogEntryListEntry();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_MSG:
return createCodeSystemCatalogEntryMsg();
case CodeSystemPackage.CODE_SYSTEM_CATALOG_ENTRY_SUMMARY:
return createCodeSystemCatalogEntrySummary();
case CodeSystemPackage.DOCUMENT_ROOT:
return createDocumentRoot();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntry createCodeSystemCatalogEntry() {
CodeSystemCatalogEntryImpl codeSystemCatalogEntry = new CodeSystemCatalogEntryImpl();
return codeSystemCatalogEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryDirectory createCodeSystemCatalogEntryDirectory() {
CodeSystemCatalogEntryDirectoryImpl codeSystemCatalogEntryDirectory = new CodeSystemCatalogEntryDirectoryImpl();
return codeSystemCatalogEntryDirectory;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryList createCodeSystemCatalogEntryList() {
CodeSystemCatalogEntryListImpl codeSystemCatalogEntryList = new CodeSystemCatalogEntryListImpl();
return codeSystemCatalogEntryList;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryListEntry createCodeSystemCatalogEntryListEntry() {
CodeSystemCatalogEntryListEntryImpl codeSystemCatalogEntryListEntry = new CodeSystemCatalogEntryListEntryImpl();
return codeSystemCatalogEntryListEntry;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntryMsg createCodeSystemCatalogEntryMsg() {
CodeSystemCatalogEntryMsgImpl codeSystemCatalogEntryMsg = new CodeSystemCatalogEntryMsgImpl();
return codeSystemCatalogEntryMsg;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemCatalogEntrySummary createCodeSystemCatalogEntrySummary() {
CodeSystemCatalogEntrySummaryImpl codeSystemCatalogEntrySummary = new CodeSystemCatalogEntrySummaryImpl();
return codeSystemCatalogEntrySummary;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
public CodeSystemPackage getCodeSystemPackage() {
return (CodeSystemPackage) getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @deprecated
* @generated
*/
@Deprecated
public static CodeSystemPackage getPackage() {
return CodeSystemPackage.eINSTANCE;
}
} // CodeSystemFactoryImpl
| epl-1.0 |
xiaohanz/softcontroller | opendaylight/sal/yang-prototype/concepts-lang/src/main/java/org/opendaylight/controller/concepts/lang/Acceptor.java | 516 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.concepts.lang;
public interface Acceptor<I> {
/**
*
* @param input
* @return true if input is accepted.
*/
boolean isAcceptable(I input);
}
| epl-1.0 |
kaloyan-raev/che | wsagent/che-core-api-git/src/main/java/org/eclipse/che/api/git/exception/GitInvalidRefNameException.java | 1446 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.api.git.exception;
/**
* @author Yossi Balan ([email protected])
*/
public class GitInvalidRefNameException extends GitException {
/**
* Construct a new GitInvalidRefNameException based on message
*
* @param message
* error message
*/
public GitInvalidRefNameException(String message) {
super(message);
}
/**
* Construct a new GitInvalidRefNameException based on cause
*
* @param cause
* cause exception
*/
public GitInvalidRefNameException(Throwable cause) {
super(cause);
}
/**
* Construct a new GitInvalidRefNameException based on message and cause
*
* @param message
* error message
* @param cause
* cause exception
*/
public GitInvalidRefNameException(String message, Throwable cause) {
super(message, cause);
}
}
| epl-1.0 |
agoncal/core | javaee/api/src/main/java/org/jboss/forge/addon/javaee/jaxws/JAXWSFacet.java | 550 | /*
* Copyright 2012 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.jaxws;
import org.jboss.forge.addon.javaee.JavaEEFacet;
import org.jboss.forge.addon.projects.Project;
/**
* If installed, this {@link Project} supports features from the JAX-WS specification.
*
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
*/
public interface JAXWSFacet extends JavaEEFacet
{
}
| epl-1.0 |
liveoak-io/liveoak | modules/scripts/src/main/java/io/liveoak/scripts/resourcetriggered/interceptor/ScriptInterceptor.java | 5830 | package io.liveoak.scripts.resourcetriggered.interceptor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import io.liveoak.common.DefaultResourceErrorResponse;
import io.liveoak.scripts.objects.Util;
import io.liveoak.scripts.objects.impl.exception.LiveOakException;
import io.liveoak.scripts.resourcetriggered.manager.ResourceScriptManager;
import io.liveoak.spi.Application;
import io.liveoak.spi.ResourceErrorResponse;
import io.liveoak.spi.ResourcePath;
import io.liveoak.spi.ResourceRequest;
import io.liveoak.spi.ResourceResponse;
import io.liveoak.spi.container.interceptor.DefaultInterceptor;
import io.liveoak.spi.container.interceptor.InboundInterceptorContext;
import io.liveoak.spi.container.interceptor.OutboundInterceptorContext;
import org.dynjs.exception.ThrowException;
/**
* @author <a href="mailto:[email protected]">Matt Wringe</a>
*/
public class ScriptInterceptor extends DefaultInterceptor {
Map<String, ResourceScriptManager> managers;
private static final String DYNJS_ERROR_PREFIX = "Error: ";
public ScriptInterceptor() {
managers = new HashMap<>();
}
@Override
public void onInbound(InboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.request());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.request());
if (reply instanceof ResourceRequest) {
context.forward((ResourceRequest) reply);
} else if (reply instanceof ResourceResponse) {
context.replyWith((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing request";
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, message));
return;
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.replyWith(Util.getErrorResponse(context.request(), (LiveOakException)value));
return;
}
}
context.replyWith(new DefaultResourceErrorResponse(context.request(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onOutbound(OutboundInterceptorContext context) throws Exception {
try {
String applicationName = getApplicationName(context.response().inReplyTo());
ResourceScriptManager manager = managers.get(applicationName);
if (manager != null) {
Object reply = manager.executeScripts(context.response());
if (reply instanceof ResourceResponse) {
context.forward((ResourceResponse) reply);
} else {
context.forward();
}
} else {
context.forward();
}
} catch (Exception e) {
e.printStackTrace();
String message = "Error processing response";
//TODO: remove the "Error: " check here, its because DynJS for some reason uses a crappy empty error message.
if (e.getMessage() != null && !e.getMessage().equals(DYNJS_ERROR_PREFIX)) {
message = e.getMessage();
if (message.startsWith(DYNJS_ERROR_PREFIX)) {
message = message.substring(DYNJS_ERROR_PREFIX.length());
}
} else if (e instanceof ThrowException) {
Object value = ((ThrowException)e).getValue();
if (value instanceof LiveOakException) {
context.forward(Util.getErrorResponse(context.response().inReplyTo(), (LiveOakException)value));
return;
}
}
context.forward(new DefaultResourceErrorResponse(context.response().inReplyTo(), ResourceErrorResponse.ErrorType.INTERNAL_ERROR, "Error processing script"));
}
}
@Override
public void onComplete(UUID requestId) {
//currently do nothing.
}
private String getApplicationName(ResourceRequest request) {
//TODO: once we have the application actually being added to the requestContext remove getting the name from the ResourcePath
List<ResourcePath.Segment> resourcePaths = request.resourcePath().segments();
String applicationName = "/";
if (resourcePaths.size() > 0) {
applicationName = resourcePaths.get(0).name();
}
// TODO: This is proper way to check, but application is currently not set
Application application = request.requestContext().application();
if (application != null) {
applicationName = application.id();
}
return applicationName;
}
public void addManager(String applicationName, ResourceScriptManager manager) {
managers.put(applicationName, manager);
}
public void removeManager(String applicationName) {
managers.remove(applicationName);
}
}
| epl-1.0 |
7illusions/Emby | MediaBrowser.WebDashboard/dashboard-ui/scripts/songs.js | 7309 | define(['events', 'libraryBrowser', 'imageLoader', 'listView', 'emby-itemscontainer'], function (events, libraryBrowser, imageLoader, listView) {
return function (view, params, tabContent) {
var self = this;
var data = {};
function getPageData(context) {
var key = getSavedQueryKey(context);
var pageData = data[key];
if (!pageData) {
pageData = data[key] = {
query: {
SortBy: "Album,SortName",
SortOrder: "Ascending",
IncludeItemTypes: "Audio",
Recursive: true,
Fields: "AudioInfo,ParentId",
Limit: 100,
StartIndex: 0,
ImageTypeLimit: 1,
EnableImageTypes: "Primary"
}
};
pageData.query.ParentId = params.topParentId;
libraryBrowser.loadSavedQueryValues(key, pageData.query);
}
return pageData;
}
function getQuery(context) {
return getPageData(context).query;
}
function getSavedQueryKey(context) {
if (!context.savedQueryKey) {
context.savedQueryKey = libraryBrowser.getSavedQueryKey('songs');
}
return context.savedQueryKey;
}
function reloadItems(page) {
Dashboard.showLoadingMsg();
var query = getQuery(page);
ApiClient.getItems(Dashboard.getCurrentUserId(), query).then(function (result) {
// Scroll back up so they can see the results from the beginning
window.scrollTo(0, 0);
updateFilterControls(page);
var pagingHtml = LibraryBrowser.getQueryPagingHtml({
startIndex: query.StartIndex,
limit: query.Limit,
totalRecordCount: result.TotalRecordCount,
showLimit: false,
updatePageSizeSetting: false,
addLayoutButton: false,
sortButton: false,
filterButton: false
});
var html = listView.getListViewHtml({
items: result.Items,
action: 'playallfromhere',
smallIcon: true
});
var i, length;
var elems = tabContent.querySelectorAll('.paging');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].innerHTML = pagingHtml;
}
function onNextPageClick() {
query.StartIndex += query.Limit;
reloadItems(tabContent);
}
function onPreviousPageClick() {
query.StartIndex -= query.Limit;
reloadItems(tabContent);
}
elems = tabContent.querySelectorAll('.btnNextPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onNextPageClick);
}
elems = tabContent.querySelectorAll('.btnPreviousPage');
for (i = 0, length = elems.length; i < length; i++) {
elems[i].addEventListener('click', onPreviousPageClick);
}
var itemsContainer = tabContent.querySelector('.itemsContainer');
itemsContainer.innerHTML = html;
imageLoader.lazyChildren(itemsContainer);
libraryBrowser.saveQueryValues(getSavedQueryKey(page), query);
Dashboard.hideLoadingMsg();
});
}
self.showFilterMenu = function () {
require(['components/filterdialog/filterdialog'], function (filterDialogFactory) {
var filterDialog = new filterDialogFactory({
query: getQuery(tabContent),
mode: 'songs'
});
Events.on(filterDialog, 'filterchange', function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
});
filterDialog.show();
});
}
function updateFilterControls(tabContent) {
}
function initPage(tabContent) {
tabContent.querySelector('.btnFilter').addEventListener('click', function () {
self.showFilterMenu();
});
tabContent.querySelector('.btnSort').addEventListener('click', function (e) {
libraryBrowser.showSortMenu({
items: [{
name: Globalize.translate('OptionTrackName'),
id: 'Name'
},
{
name: Globalize.translate('OptionAlbum'),
id: 'Album,SortName'
},
{
name: Globalize.translate('OptionAlbumArtist'),
id: 'AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionArtist'),
id: 'Artist,Album,SortName'
},
{
name: Globalize.translate('OptionDateAdded'),
id: 'DateCreated,SortName'
},
{
name: Globalize.translate('OptionDatePlayed'),
id: 'DatePlayed,SortName'
},
{
name: Globalize.translate('OptionPlayCount'),
id: 'PlayCount,SortName'
},
{
name: Globalize.translate('OptionReleaseDate'),
id: 'PremiereDate,AlbumArtist,Album,SortName'
},
{
name: Globalize.translate('OptionRuntime'),
id: 'Runtime,AlbumArtist,Album,SortName'
}],
callback: function () {
getQuery(tabContent).StartIndex = 0;
reloadItems(tabContent);
},
query: getQuery(tabContent),
button: e.target
});
});
}
self.getCurrentViewStyle = function () {
return getPageData(tabContent).view;
};
initPage(tabContent);
self.renderTab = function () {
reloadItems(tabContent);
updateFilterControls(tabContent);
};
self.destroy = function () {
};
};
}); | gpl-2.0 |
somaen/scummvm | engines/tucker/detection.cpp | 4298 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "common/config-manager.h"
#include "engines/advancedDetector.h"
#include "base/plugins.h"
#include "tucker/detection.h"
static const PlainGameDescriptor tuckerGames[] = {
{ "tucker", "Bud Tucker in Double Trouble" },
{ nullptr, nullptr }
};
static const ADGameDescription tuckerGameDescriptions[] = {
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "f1e42a95972643462b9c3c2ea79d6683", 543),
Common::FR_FRA,
Common::kPlatformDOS,
Tucker::kGameFlagNoSubtitles,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "9c1ddeafc5283b90d1a284bd0924831c", 462),
Common::EN_ANY,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "1b3ea79d8528ea3c7df83dd0ed345e37", 525),
Common::ES_ESP,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4df9eb65722418d1a1723508115b146c", 552),
Common::DE_DEU,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "5f85285bbc23ce57cbc164021ee1f23c", 525),
Common::PL_POL,
Common::kPlatformDOS,
0,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"",
AD_ENTRY1s("infobar.txt", "e548994877ff31ca304f6352ce022a8e", 497),
Common::CZ_CZE,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{ // Russian fan translation
"tucker",
"",
AD_ENTRY1s("infobrgr.txt", "4b5a315e449a7f9eaf2025ec87466cd8", 552),
Common::RU_RUS,
Common::kPlatformDOS,
Tucker::kGameFlagEncodedData,
GUIO1(GUIO_NOMIDI)
},
{
"tucker",
"Demo",
AD_ENTRY1s("infobar.txt", "010b055de42097b140d5bcb6e95a5c7c", 203),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo,
GUIO1(GUIO_NOMIDI)
},
AD_TABLE_END_MARKER
};
static const ADGameDescription tuckerDemoGameDescription = {
"tucker",
"Non-Interactive Demo",
AD_ENTRY1(0, 0),
Common::EN_ANY,
Common::kPlatformDOS,
ADGF_DEMO | Tucker::kGameFlagDemo | Tucker::kGameFlagIntroOnly,
GUIO1(GUIO_NOMIDI)
};
class TuckerMetaEngineDetection : public AdvancedMetaEngineDetection {
public:
TuckerMetaEngineDetection() : AdvancedMetaEngineDetection(tuckerGameDescriptions, sizeof(ADGameDescription), tuckerGames) {
_md5Bytes = 512;
}
const char *getEngineId() const override {
return "tucker";
}
const char *getName() const override {
return "Bud Tucker in Double Trouble";
}
const char *getOriginalCopyright() const override {
return "Bud Tucker in Double Trouble (C) Merit Studios";
}
ADDetectedGame fallbackDetect(const FileMap &allFiles, const Common::FSList &fslist) const override {
for (Common::FSList::const_iterator d = fslist.begin(); d != fslist.end(); ++d) {
Common::FSList audiofslist;
if (d->isDirectory() && d->getName().equalsIgnoreCase("audio") && d->getChildren(audiofslist, Common::FSNode::kListFilesOnly)) {
for (Common::FSList::const_iterator f = audiofslist.begin(); f != audiofslist.end(); ++f) {
if (!f->isDirectory() && f->getName().equalsIgnoreCase("demorolc.raw")) {
return ADDetectedGame(&tuckerDemoGameDescription);
}
}
}
}
return ADDetectedGame();
}
};
REGISTER_PLUGIN_STATIC(TUCKER_DETECTION, PLUGIN_TYPE_ENGINE_DETECTION, TuckerMetaEngineDetection);
| gpl-2.0 |
MyvarHD/OpenIDE | OpenIDE/OpenIDE.Library/Base/JSON/JsonToken.cs | 2797 | #region License
// Copyright (c) 2007 James Newton-King
//
// 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.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Lib.JSON
{
/// <summary>
/// Specifies the type of Json token.
/// </summary>
public enum JsonToken
{
/// <summary>
/// This is returned by the <see cref="JsonReader"/> if a <see cref="JsonReader.Read"/> method has not been called.
/// </summary>
None,
/// <summary>
/// An object start token.
/// </summary>
StartObject,
/// <summary>
/// An array start token.
/// </summary>
StartArray,
/// <summary>
/// A constructor start token.
/// </summary>
StartConstructor,
/// <summary>
/// An object property name.
/// </summary>
PropertyName,
/// <summary>
/// A comment.
/// </summary>
Comment,
/// <summary>
/// Raw JSON.
/// </summary>
Raw,
/// <summary>
/// An integer.
/// </summary>
Integer,
/// <summary>
/// A float.
/// </summary>
Float,
/// <summary>
/// A string.
/// </summary>
String,
/// <summary>
/// A boolean.
/// </summary>
Boolean,
/// <summary>
/// A null token.
/// </summary>
Null,
/// <summary>
/// An undefined token.
/// </summary>
Undefined,
/// <summary>
/// An object end token.
/// </summary>
EndObject,
/// <summary>
/// An array end token.
/// </summary>
EndArray,
/// <summary>
/// A constructor end token.
/// </summary>
EndConstructor,
/// <summary>
/// A Date.
/// </summary>
Date,
/// <summary>
/// Byte data.
/// </summary>
Bytes
}
} | gpl-2.0 |
mambomark/linux-systemsim | tools/perf/tests/hists_output.c | 17900 | #include "perf.h"
#include "util/debug.h"
#include "util/symbol.h"
#include "util/sort.h"
#include "util/evsel.h"
#include "util/evlist.h"
#include "util/machine.h"
#include "util/thread.h"
#include "util/parse-events.h"
#include "tests/tests.h"
#include "tests/hists_common.h"
struct sample {
u32 cpu;
u32 pid;
u64 ip;
struct thread *thread;
struct map *map;
struct symbol *sym;
};
/* For the numbers, see hists_common.c */
static struct sample fake_samples[] = {
/* perf [kernel] schedule() */
{ .cpu = 0, .pid = 100, .ip = 0xf0000 + 700, },
/* perf [perf] main() */
{ .cpu = 1, .pid = 100, .ip = 0x40000 + 700, },
/* perf [perf] cmd_record() */
{ .cpu = 1, .pid = 100, .ip = 0x40000 + 900, },
/* perf [libc] malloc() */
{ .cpu = 1, .pid = 100, .ip = 0x50000 + 700, },
/* perf [libc] free() */
{ .cpu = 2, .pid = 100, .ip = 0x50000 + 800, },
/* perf [perf] main() */
{ .cpu = 2, .pid = 200, .ip = 0x40000 + 700, },
/* perf [kernel] page_fault() */
{ .cpu = 2, .pid = 200, .ip = 0xf0000 + 800, },
/* bash [bash] main() */
{ .cpu = 3, .pid = 300, .ip = 0x40000 + 700, },
/* bash [bash] xmalloc() */
{ .cpu = 0, .pid = 300, .ip = 0x40000 + 800, },
/* bash [kernel] page_fault() */
{ .cpu = 1, .pid = 300, .ip = 0xf0000 + 800, },
};
static int add_hist_entries(struct hists *hists, struct machine *machine)
{
struct addr_location al;
struct hist_entry *he;
struct perf_sample sample = { .period = 100, };
size_t i;
for (i = 0; i < ARRAY_SIZE(fake_samples); i++) {
const union perf_event event = {
.header = {
.misc = PERF_RECORD_MISC_USER,
},
};
sample.cpu = fake_samples[i].cpu;
sample.pid = fake_samples[i].pid;
sample.tid = fake_samples[i].pid;
sample.ip = fake_samples[i].ip;
if (perf_event__preprocess_sample(&event, machine, &al,
&sample) < 0)
goto out;
he = __hists__add_entry(hists, &al, NULL, NULL, NULL,
sample.period, 1, 0);
if (he == NULL)
goto out;
fake_samples[i].thread = al.thread;
fake_samples[i].map = al.map;
fake_samples[i].sym = al.sym;
}
return TEST_OK;
out:
pr_debug("Not enough memory for adding a hist entry\n");
return TEST_FAIL;
}
static void del_hist_entries(struct hists *hists)
{
struct hist_entry *he;
struct rb_root *root_in;
struct rb_root *root_out;
struct rb_node *node;
if (sort__need_collapse)
root_in = &hists->entries_collapsed;
else
root_in = hists->entries_in;
root_out = &hists->entries;
while (!RB_EMPTY_ROOT(root_out)) {
node = rb_first(root_out);
he = rb_entry(node, struct hist_entry, rb_node);
rb_erase(node, root_out);
rb_erase(&he->rb_node_in, root_in);
hist_entry__free(he);
}
}
typedef int (*test_fn_t)(struct perf_evsel *, struct machine *);
#define COMM(he) (thread__comm_str(he->thread))
#define DSO(he) (he->ms.map->dso->short_name)
#define SYM(he) (he->ms.sym->name)
#define CPU(he) (he->cpu)
#define PID(he) (he->thread->tid)
/* default sort keys (no field) */
static int test1(struct perf_evsel *evsel, struct machine *machine)
{
int err;
struct hists *hists = &evsel->hists;
struct hist_entry *he;
struct rb_root *root;
struct rb_node *node;
field_order = NULL;
sort_order = NULL; /* equivalent to sort_order = "comm,dso,sym" */
setup_sorting();
/*
* expected output:
*
* Overhead Command Shared Object Symbol
* ======== ======= ============= ==============
* 20.00% perf perf [.] main
* 10.00% bash [kernel] [k] page_fault
* 10.00% bash bash [.] main
* 10.00% bash bash [.] xmalloc
* 10.00% perf [kernel] [k] page_fault
* 10.00% perf [kernel] [k] schedule
* 10.00% perf libc [.] free
* 10.00% perf libc [.] malloc
* 10.00% perf perf [.] cmd_record
*/
err = add_hist_entries(hists, machine);
if (err < 0)
goto out;
hists__collapse_resort(hists, NULL);
hists__output_resort(hists);
if (verbose > 2) {
pr_info("[fields = %s, sort = %s]\n", field_order, sort_order);
print_hists_out(hists);
}
root = &evsel->hists.entries;
node = rb_first(root);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
!strcmp(SYM(he), "main") && he->stat.period == 200);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "page_fault") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "bash") &&
!strcmp(SYM(he), "main") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "bash") &&
!strcmp(SYM(he), "xmalloc") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "page_fault") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "schedule") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "libc") &&
!strcmp(SYM(he), "free") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "libc") &&
!strcmp(SYM(he), "malloc") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
!strcmp(SYM(he), "cmd_record") && he->stat.period == 100);
out:
del_hist_entries(hists);
reset_output_field();
return err;
}
/* mixed fields and sort keys */
static int test2(struct perf_evsel *evsel, struct machine *machine)
{
int err;
struct hists *hists = &evsel->hists;
struct hist_entry *he;
struct rb_root *root;
struct rb_node *node;
field_order = "overhead,cpu";
sort_order = "pid";
setup_sorting();
/*
* expected output:
*
* Overhead CPU Command: Pid
* ======== === =============
* 30.00% 1 perf : 100
* 10.00% 0 perf : 100
* 10.00% 2 perf : 100
* 20.00% 2 perf : 200
* 10.00% 0 bash : 300
* 10.00% 1 bash : 300
* 10.00% 3 bash : 300
*/
err = add_hist_entries(hists, machine);
if (err < 0)
goto out;
hists__collapse_resort(hists, NULL);
hists__output_resort(hists);
if (verbose > 2) {
pr_info("[fields = %s, sort = %s]\n", field_order, sort_order);
print_hists_out(hists);
}
root = &evsel->hists.entries;
node = rb_first(root);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 1 && PID(he) == 100 && he->stat.period == 300);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 0 && PID(he) == 100 && he->stat.period == 100);
out:
del_hist_entries(hists);
reset_output_field();
return err;
}
/* fields only (no sort key) */
static int test3(struct perf_evsel *evsel, struct machine *machine)
{
int err;
struct hists *hists = &evsel->hists;
struct hist_entry *he;
struct rb_root *root;
struct rb_node *node;
field_order = "comm,overhead,dso";
sort_order = NULL;
setup_sorting();
/*
* expected output:
*
* Command Overhead Shared Object
* ======= ======== =============
* bash 20.00% bash
* bash 10.00% [kernel]
* perf 30.00% perf
* perf 20.00% [kernel]
* perf 20.00% libc
*/
err = add_hist_entries(hists, machine);
if (err < 0)
goto out;
hists__collapse_resort(hists, NULL);
hists__output_resort(hists);
if (verbose > 2) {
pr_info("[fields = %s, sort = %s]\n", field_order, sort_order);
print_hists_out(hists);
}
root = &evsel->hists.entries;
node = rb_first(root);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "bash") &&
he->stat.period == 200);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "[kernel]") &&
he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
he->stat.period == 300);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "[kernel]") &&
he->stat.period == 200);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "libc") &&
he->stat.period == 200);
out:
del_hist_entries(hists);
reset_output_field();
return err;
}
/* handle duplicate 'dso' field */
static int test4(struct perf_evsel *evsel, struct machine *machine)
{
int err;
struct hists *hists = &evsel->hists;
struct hist_entry *he;
struct rb_root *root;
struct rb_node *node;
field_order = "dso,sym,comm,overhead,dso";
sort_order = "sym";
setup_sorting();
/*
* expected output:
*
* Shared Object Symbol Command Overhead
* ============= ============== ======= ========
* perf [.] cmd_record perf 10.00%
* libc [.] free perf 10.00%
* bash [.] main bash 10.00%
* perf [.] main perf 20.00%
* libc [.] malloc perf 10.00%
* [kernel] [k] page_fault bash 10.00%
* [kernel] [k] page_fault perf 10.00%
* [kernel] [k] schedule perf 10.00%
* bash [.] xmalloc bash 10.00%
*/
err = add_hist_entries(hists, machine);
if (err < 0)
goto out;
hists__collapse_resort(hists, NULL);
hists__output_resort(hists);
if (verbose > 2) {
pr_info("[fields = %s, sort = %s]\n", field_order, sort_order);
print_hists_out(hists);
}
root = &evsel->hists.entries;
node = rb_first(root);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "perf") && !strcmp(SYM(he), "cmd_record") &&
!strcmp(COMM(he), "perf") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "libc") && !strcmp(SYM(he), "free") &&
!strcmp(COMM(he), "perf") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "bash") && !strcmp(SYM(he), "main") &&
!strcmp(COMM(he), "bash") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "perf") && !strcmp(SYM(he), "main") &&
!strcmp(COMM(he), "perf") && he->stat.period == 200);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "libc") && !strcmp(SYM(he), "malloc") &&
!strcmp(COMM(he), "perf") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "[kernel]") && !strcmp(SYM(he), "page_fault") &&
!strcmp(COMM(he), "bash") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "[kernel]") && !strcmp(SYM(he), "page_fault") &&
!strcmp(COMM(he), "perf") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "[kernel]") && !strcmp(SYM(he), "schedule") &&
!strcmp(COMM(he), "perf") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
!strcmp(DSO(he), "bash") && !strcmp(SYM(he), "xmalloc") &&
!strcmp(COMM(he), "bash") && he->stat.period == 100);
out:
del_hist_entries(hists);
reset_output_field();
return err;
}
/* full sort keys w/o overhead field */
static int test5(struct perf_evsel *evsel, struct machine *machine)
{
int err;
struct hists *hists = &evsel->hists;
struct hist_entry *he;
struct rb_root *root;
struct rb_node *node;
field_order = "cpu,pid,comm,dso,sym";
sort_order = "dso,pid";
setup_sorting();
/*
* expected output:
*
* CPU Command: Pid Command Shared Object Symbol
* === ============= ======= ============= ==============
* 0 perf: 100 perf [kernel] [k] schedule
* 2 perf: 200 perf [kernel] [k] page_fault
* 1 bash: 300 bash [kernel] [k] page_fault
* 0 bash: 300 bash bash [.] xmalloc
* 3 bash: 300 bash bash [.] main
* 1 perf: 100 perf libc [.] malloc
* 2 perf: 100 perf libc [.] free
* 1 perf: 100 perf perf [.] cmd_record
* 1 perf: 100 perf perf [.] main
* 2 perf: 200 perf perf [.] main
*/
err = add_hist_entries(hists, machine);
if (err < 0)
goto out;
hists__collapse_resort(hists, NULL);
hists__output_resort(hists);
if (verbose > 2) {
pr_info("[fields = %s, sort = %s]\n", field_order, sort_order);
print_hists_out(hists);
}
root = &evsel->hists.entries;
node = rb_first(root);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 0 && PID(he) == 100 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "schedule") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 2 && PID(he) == 200 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "page_fault") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 1 && PID(he) == 300 &&
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "[kernel]") &&
!strcmp(SYM(he), "page_fault") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 0 && PID(he) == 300 &&
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "bash") &&
!strcmp(SYM(he), "xmalloc") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 3 && PID(he) == 300 &&
!strcmp(COMM(he), "bash") && !strcmp(DSO(he), "bash") &&
!strcmp(SYM(he), "main") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 1 && PID(he) == 100 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "libc") &&
!strcmp(SYM(he), "malloc") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 2 && PID(he) == 100 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "libc") &&
!strcmp(SYM(he), "free") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 1 && PID(he) == 100 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
!strcmp(SYM(he), "cmd_record") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 1 && PID(he) == 100 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
!strcmp(SYM(he), "main") && he->stat.period == 100);
node = rb_next(node);
he = rb_entry(node, struct hist_entry, rb_node);
TEST_ASSERT_VAL("Invalid hist entry",
CPU(he) == 2 && PID(he) == 200 &&
!strcmp(COMM(he), "perf") && !strcmp(DSO(he), "perf") &&
!strcmp(SYM(he), "main") && he->stat.period == 100);
out:
del_hist_entries(hists);
reset_output_field();
return err;
}
int test__hists_output(void)
{
int err = TEST_FAIL;
struct machines machines;
struct machine *machine;
struct perf_evsel *evsel;
struct perf_evlist *evlist = perf_evlist__new();
size_t i;
test_fn_t testcases[] = {
test1,
test2,
test3,
test4,
test5,
};
TEST_ASSERT_VAL("No memory", evlist);
err = parse_events(evlist, "cpu-clock");
if (err)
goto out;
machines__init(&machines);
/* setup threads/dso/map/symbols also */
machine = setup_fake_machine(&machines);
if (!machine)
goto out;
if (verbose > 1)
machine__fprintf(machine, stderr);
evsel = perf_evlist__first(evlist);
for (i = 0; i < ARRAY_SIZE(testcases); i++) {
err = testcases[i](evsel, machine);
if (err < 0)
break;
}
out:
/* tear down everything */
perf_evlist__delete(evlist);
machines__exit(&machines);
return err;
}
| gpl-2.0 |
maxhutch/quantum-espresso | VdW/Makefile | 189 | # Makefile for VdW
sinclude ../make.sys
default: all
all:
@echo "VdW no longer maintained"
# ( cd src ; $(MAKE) all || exit 1 )
clean :
( cd src ; $(MAKE) clean ; )
distclean: clean
| gpl-2.0 |
borgotech/Infinity_MaNGOS | sql/Tools & Optional/Websites/I_CSwowd/pvpmini/shared/wow-com/includes-client/armorsets/en/pvpsuperior.js | 49796 | var armorSetPvPSuperior = new armorSetObject("pvpsuperior");
armorSetPvPSuperior.slotsArray = new Array();
t = 0;
armorSetPvPSuperior.slotsArray[t] = "head"; t++;
armorSetPvPSuperior.slotsArray[t] = "shoulder"; t++;
armorSetPvPSuperior.slotsArray[t] = "chest"; t++;
armorSetPvPSuperior.slotsArray[t] = "hands"; t++;
armorSetPvPSuperior.slotsArray[t] = "legs"; t++;
armorSetPvPSuperior.slotsArray[t] = "feet"; t++;
armorSetPvPSuperior.slotsNumber = armorSetPvPSuperior.slotsArray.length;
armorSetPvPSuperior.statsArray = new Array();
armorSetPvPSuperior.itemNameArray = new Array();
armorSetPvPSuperior.setNameArray = new Array();
t = 0;
armorSetPvPSuperior.setNamesArray = new Array();
x = 0;
armorSetPvPSuperior.setNamesArray[x] = "Refuge"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Pursuance"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Arcanum"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Redoubt"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Investiture"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Guard"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Stormcaller"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Dreadgear"; x++;
armorSetPvPSuperior.setNamesArray[x] = "Battlearmor"; x++;
classCounter = 0;
//DONT LOCALIZE ABOVE THIS COMMENT LINE
//LOCALIZE EVERYTHING BELOW THIS COMMENT LINE
//druid begin
var sanctuaryBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power<br>\
(4) Set: Increases your movement speed by 15% while in Bear, Cat, or Travel Form. Only active outdoors.<br>\
(6) Set: +20 Stamina\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dragonhide Shoulders<br>\
Lieutenant Commander\'s Dragonhide Headguard<br>\
Knight-Captain\'s Dragonhide Leggings<br>\
Knight-Captain\'s Dragonhide Chestpiece<br>\
Knight-Lieutenant\'s Dragonhide Treads<br>\
Knight-Lieutenant\'s Dragonhide Grips<br>\
</span>'+ sanctuaryBlue, '<span class = "myYellow">\
Champion\'s Refuge (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dragonhide Treads<br>\
Blood Guard\'s Dragonhide Grips<br>\
Legionnaire\'s Dragonhide Chestpiece<br>\
Legionnaire\'s Dragonhide Leggings<br>\
Champion\'s Dragonhide Headguard<br>\
Champion\'s Dragonhide Shoulders<br>\
</span>'+ sanctuaryBlue];
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Headguard', '<span class = "myBlue">\
Champion\'s Dragonhide Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
198 Armor<br>\
+16 Strength<br>\
+12 Agility<br>\
+16 Stamina<br>\
+16 Intellect<br>\
+8 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dragonhide Shoulders', '<span class = "myBlue">\
Champion\'s Dragonhide Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
206 Armor<br>\
+12 Strength<br>\
+6 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
218 Armor<br>\
+13 Strength<br>\
+12 Agility<br>\
+13 Stamina<br>\
+12 Intellect<br>\
Classes: Druid<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 15.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Grips', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
115 Armor<br>\
+13 Strength<br>\
+10 Agility<br>\
+12 Stamina<br>\
+9 Intellect<br>\
Classes: Druid<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Slightly increases your stealth detection.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dragonhide Leggings', '<span class = "myBlue">\
Legionnaire\'s Dragonhide Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
215 Armor<br>\
+12 Strength<br>\
+12 Agility<br>\
+12 Stamina<br>\
+12 Intellect<br>\
+5 Spirit<br>\
Classes: Druid<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 14.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dragonhide Treads', '<span class = "myBlue">\
Blood Guard\'s Dragonhide Treads'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
126 Armor<br>\
+13 Strength<br>\
+6 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
+6 Spirit<br>\
Classes: Druid<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//druid end
classCounter++;
//hunter begin
var pursuitBlue = '<span class = "myGreen">\
(2) Set: +20 Agility.<br>\
(4) Set: Reduces the cooldown of your Concussive Shot by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Chain Shoulders<br>\
Lieutenant Commander\'s Chain Helm<br>\
Knight-Captain\'s Chain Legguards<br>\
Knight-Captain\'s Chain Hauberk<br>\
Knight-Lieutenant\'s Chain Greaves<br>\
Knight-Lieutenant\'s Chain Vices<br>\
</span>'+ pursuitBlue, '<span class = "myYellow">\
Champion\'s Pursuance (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Chain Greaves<br>\
Blood Guard\'s Chain Vices<br>\
Legionnaire\'s Chain Hauberk<br>\
Legionnaire\'s Chain Legguards<br>\
Champion\'s Chain Helm<br>\
Champion\'s Chain Shoulders<br>\
</span>'+ pursuitBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Helm', '<span class = "myBlue">\
Champion\'s Chain Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+18 Agility<br>\
+14 Stamina<br>\
+9 Intellect<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Chain Shoulders', '<span class = "myBlue">\
Champion\'s Chain Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+18 Agility<br>\
+13 Stamina<br>\
Classes: Hunter<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Hauberk', '<span class = "myBlue">\
Legionnaire\'s Chain Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Vices', '<span class = "myBlue">\
Blood Guard\'s Chain Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+18 Agility<br>\
+16 Stamina<br>\
Classes: Hunter<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage done by your Multi-Shot by 4%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Chain Legguards', '<span class = "myBlue">\
Legionnaire\'s Chain Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+16 Agility<br>\
+13 Stamina<br>\
+6 Intellect<br>\
Classes: Hunter<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Chain Greaves', '<span class = "myBlue">\
Blood Guard\'s Chain Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+20 Agility<br>\
+19 Stamina<br>\
Classes: Hunter<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//hunter end
classCounter++;
//mage begin
var regaliaBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Blink spell by 1.5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Silk Mantle<br>\
Lieutenant Commander\'s Silk Cowl<br>\
Knight-Captain\'s Silk Legguards<br>\
Knight-Captain\'s Silk Tunic<br>\
Knight-Lieutenant\'s Silk Walkers<br>\
Knight-Lieutenant\'s Silk Handwraps<br>\
</span>'+ regaliaBlue, '<span class = "myYellow">\
Champion\'s Arcanum (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Silk Walkers<br>\
Blood Guard\'s Silk Handwraps<br>\
Legionnaire\'s Silk Tunic<br>\
Legionnaire\'s Silk Legguards<br>\
Champion\'s Silk Cowl<br>\
Champion\'s Silk Mantle<br>\
</span>'+ regaliaBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Cowl', '<span class = "myBlue">\
Champion\'s Silk Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
141 Armor<br>\
+19 Stamina<br>\
+18 Intellect<br>\
+6 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Silk Mantle', '<span class = "myBlue">\
Champion\'s Silk Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
135 Armor<br>\
+14 Stamina<br>\
+11 Intellect<br>\
+4 Spirit<br>\
Classes: Mage<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equp: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Tunic', '<span class = "myBlue">\
Legionnaires\'s Silk Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike with spells by 1%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Handwraps', '<span class = "myBlue">\
Blood Guard\'s Silk Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage absorbed by your Mana Shield by 285.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Silk Legguards', '<span class = "myBlue">\
Legionnaire\'s Silk Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
+5 Spirit<br>\
Classes: Mage<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Silk Walkers', '<span class = "myBlue">\
Blood Guard\'s Silk Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
104 Armor<br>\
+15 Stamina<br>\
+10 Intellect<br>\
Classes: Mage<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to hit with spells by 1%.</span>\
<p>';
//mage end
classCounter++;
//paladin begin
var aegisBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the cooldown of your Hammer of Justice by 10 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Redoubt (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Lamellar Shoulders<br>\
Lieutenant Commander\'s Lamellar Headguard<br>\
Knight-Captain\'s Lamellar Leggings<br>\
Knight-Captain\'s Lamellar Breastplate<br>\
Knight-Lieutenant\'s Lamellar Sabatons<br>\
Knight-Lieutenant\'s Lamellar Gauntlets<br>\
</span>'+ aegisBlue, ''];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Headguard', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+18 Strength<br>\
+19 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Increases damage and healing done by magical spells and effects by up to 26.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Lamellar Shoulders', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+14 Strength<br>\
+14 Stamina<br>\
+8 Intellect<br>\
Classes: Paladin<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 20.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Breastplate', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Gauntlets', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+12 Strength<br>\
+13 Stamina<br>\
Classes: Paladin<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the Holy damage bonus of your Judgement of the Crusader by 10.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Lamellar Leggings', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+18 Strength<br>\
+17 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Lamellar Sabatons', ''];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+12 Strength<br>\
+12 Stamina<br>\
+12 Intellect<br>\
Classes: Paladin<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.\
</span>\
<p>';
//Paladin end
classCounter++;
//priest begin
var raimentBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Increases the duration of your Psychic Scream spell by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Satin Mantle<br>\
Lieutenant Commander\'s Satin Hood<br>\
Knight-Captain\'s Satin Legguards<br>\
Knight-Captain\'s Satin Tunic<br>\
Knight-Lieutenant\'s Satin Walkers<br>\
Knight-Lieutenant\'s Satin Handwraps<br>\
</span>'+ raimentBlue, '<span class = "myYellow">\
Champion\'s Investiture (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Satin Walkers<br>\
Blood Guard\'s Satin Handwraps<br>\
Legionnaire\'s Satin Tunic<br>\
Legionnaire\'s Satin Legguards<br>\
Champion\'s Satin Hood<br>\
Champion\'s Satin Mantle<br>\
</span>'+ raimentBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Hood', '<span class = "myBlue">\
Champion\'s Satin Hood'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
131 Armor<br>\
+20 Stamina<br>\
+18 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Satin Mantle', '<span class = "myBlue">\
Champion\'s Satin Mantle'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
115 Armor<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Priest<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 16.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Tunic', '<span class = "myBlue">\
Legionnaire\'s Satin Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
156 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Handwraps', '<span class = "myBlue">\
Blood Guard\'s Satin Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
98 Armor<br>\
+12 Stamina<br>\
+5 Intellect<br>\
Classes: Priest<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Gives you a 50% chance to avoid interruption caused by damage while casting Mind Blast.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Satin Legguards', '<span class = "myBlue">\
Legionnaire\'s Satin Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
144 Armor<br>\
+19 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Restores 6 mana per 5 sec.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Satin Walkers', '<span class = "myBlue">\
Blood Guard\'s Satin Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+15 Intellect<br>\
Classes: Priest<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 14.</span>\
<p>';
//priest end
classCounter++;
//rogue begin
var vestmentsBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Gouge ability by 1 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Leather Helm<br>\
Lieutenant Commander\'s Leather Shoulders<br>\
Knight-Captain\'s Leather Legguards<br>\
Knight-Captain\'s Leather Chestpiece<br>\
Knight-Lieutenant\'s Leather Walkers<br>\
Knight-Lieutenant\'s Leather Grips<br>\
</span>'+ vestmentsBlue, '<span class = "myYellow">\
Champion\'s Guard (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Leather Walkers<br>\
Blood Guard\'s Leather Grips<br>\
Legionnaire\'s Leather Chestpiece<br>\
Legionnaire\'s Leather Legguards<br>\
Champion\'s Leather Helm<br>\
Champion\'s Leather Shoulders<br>\
</span>'+ vestmentsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Helm', '<span class = "myBlue">\
Champion\'s Leather Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
238 Armor<br>\
+23 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: +36 Attack Power.<br>\
Equip: Improves your chance to hit by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Leather Shoulders', '<span class = "myBlue">\
Champion\'s Leather Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
196 Armor<br>\
+17 Stamina<br>\
Classes: Rogue<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: +22 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Chestpiece', '<span class = "myBlue">\
Legionnaire\'s Leather Chestpiece'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
248 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Grips', '<span class = "myBlue">\
Blood Guard\'s Leather Grips'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
155 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 35/35<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: +20 Attack Power.<br>\
Equip: Improves your chance to get a critical strike by 1%.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Leather Legguards', '<span class = "myBlue">\
Legionnaire\'s Leather Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
225 Armor<br>\
+22 Stamina<br>\
Classes: Rogue<br>\
Durability 75/75<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.<br>\
Equip: +34 Attack Power.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Leather Walkers', '<span class = "myBlue">\
Blood Guard\'s Leather Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Leather\
</span></td></tr></table>\
166 Armor<br>\
+18 Stamina<br>\
Classes: Rogue<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the duration of your Sprint ability by 3 sec.<br>\
Equip: +28 Attack Power.\
</span>\
<p>';
//Rogue end
classCounter++;
//shaman begin
var earthshakerBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Improves your chance to get a critical strike with all Shock spells by 2%.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['', '<span class = "myYellow">\
Champion\'s Stormcaller (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Mail Greaves<br>\
Blood Guard\'s Mail Vices<br>\
Legionnaire\'s Mail Hauberk<br>\
Legionnaire\'s Mail Legguards<br>\
Champion\'s Mail Headguard<br>\
Champion\'s Mail Pauldrons<br>\
</span>'+ earthshakerBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Headguard'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
337 Armor<br>\
+6 Strength<br>\
+24 Stamina<br>\
+16 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Champion\'s Mail Pauldrons'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
311 Armor<br>\
+5 Strength<br>\
+16 Stamina<br>\
+10 Intellect<br>\
Classes: Shaman<br>\
Durability 70/70<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 15.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
398 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
+18 Intellect<br>\
Classes: Shaman<br>\
Durability 120/120<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Vices'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
242 Armor<br>\
+15 Stamina<br>\
+9 Intellect<br>\
Classes: Shaman<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 13.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Legionnaire\'s Mail Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
348 Armor<br>\
+18 Stamina<br>\
+17 Intellect<br>\
Classes: Shaman<br>\
Durability 90/90<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['', '<span class = "myBlue">\
Blood Guard\'s Mail Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Mail\
</span></td></tr></table>\
266 Armor<br>\
+13 Strength<br>\
+14 Stamina<br>\
+12 Intellect<br>\
Classes: Shaman<br>\
Durability 60/60<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the speed of your Ghost Wolf ability by 15%.</span>\
<p>';
//Shaman end
classCounter++;
//warlock begin
var threadsBlue = '<span class = "myGreen">\
(2) Set: Increases damage and healing done by magical spells and effects by up to 23.<br>\
(4) Set: Reduces the casting time of your Immolate spell by 0.2 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Dreadweave Spaulders<br>\
Lieutenant Commander\'s Dreadweave Cowl<br>\
Knight-Captain\'s Dreadweave Legguards<br>\
Knight-Captain\'s Dreadweave Tunic<br>\
Knight-Lieutenant\'s Dreadweave Walkers<br>\
Knight-Lieutenant\'s Dreadweave Handwraps<br>\
</span>'+ threadsBlue, '<span class = "myYellow">\
Champion\'s Dreadgear (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Dreadweave Walkers<br>\
Blood Guard\'s Dreadweave Handwraps<br>\
Legionnaire\'s Dreadweave Tunic<br>\
Legionnaire\'s Dreadweave Legguards<br>\
Champion\'s Dreadweave Cowl<br>\
Champion\'s Dreadweave Spaulders<br>\
</span>'+ threadsBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Cowl', '<span class = "myBlue">\
Champion\'s Dreadweave Cowl'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
81 Armor<br>\
+21 Stamina<br>\
+18 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 21.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Dreadweave Spaulders', '<span class = "myBlue">\
Champion\'s Dreadweave Spaulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
75 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 50/50<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 12.<br>\
Equip: Improves your chance to get a critical strike with spells by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Tunic', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Tunic'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
96 Armor<br>\
+20 Stamina<br>\
+20 Intellect<br>\
Classes: Warlock<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 25.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Handwraps', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Handwraps'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
58 Armor<br>\
+14 Stamina<br>\
+4 Intellect<br>\
Classes: Warlock<br>\
Durability 30/30<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases the damage dealt and health regained by your Death Coil spell by 8%.<br>\
Equip: Increases damage and healing done by magical spells and effects by up to 21.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Dreadweave Legguards', '<span class = "myBlue">\
Legionnaire\'s Dreadweave Legguards'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
84 Armor<br>\
+21 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 28.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Dreadweave Walkers', '<span class = "myBlue">\
Blood Guard\'s Dreadweave Walkers'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Cloth\
</span></td></tr></table>\
64 Armor<br>\
+17 Stamina<br>\
+13 Intellect<br>\
Classes: Warlock<br>\
Durability 40/40<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Increases damage and healing done by magical spells and effects by up to 18.</span>\
<p>';
//Warlock end
classCounter++;
//warrior begin
var battlegearBlue = '<span class = "myGreen">\
(2) Set: +40 Attack Power.<br>\
(4) Set: Reduces the cooldown of your Intercept ability by 5 sec.<br>\
(6) Set: +20 Stamina.\
</span>';
armorSetPvPSuperior.setNameArray[classCounter] = ['<span class = "myYellow">\
Lieutenant Commander\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Lieutenant Commander\'s Plate Shoulders<br>\
Lieutenant Commander\'s Plate Helm<br>\
Knight-Captain\'s Plate Leggings<br>\
Knight-Captain\'s Plate Hauberk<br>\
Knight-Lieutenant\'s Plate Greaves<br>\
Knight-Lieutenant\'s Plate Gauntlets<br>\
</span>'+ battlegearBlue, '<span class = "myYellow">\
Champion\'s Battlearmor (0/6)<br>\
</span><span class = "myGray">\
Blood Guard\'s Plate Greaves<br>\
Blood Guard\'s Plate Gauntlets<br>\
Legionnaire\'s Plate Hauberk<br>\
Legionnaire\'s Plate Leggings<br>\
Champion\'s Plate Helm<br>\
Champion\'s Plate Shoulders<br>\
</span>'+ battlegearBlue];
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Helm', '<span class = "myBlue">\
Champion\'s Plate Helm'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Head\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
598 Armor<br>\
+21 Strength<br>\
+24 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.<br>\
Equip: Improves your chance to hit by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Lieutenant Commander\'s Plate Shoulders', '<span class = "myBlue">\
Champion\'s Plate Shoulders'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Shoulders\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
552 Armor<br>\
+17 Strength<br>\
+18 Stamina<br>\
Classes: Warrior<br>\
Durability 80/80<br>\
Requires Level 60<br>\
Requires Rank 10<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Hauberk', '<span class = "myBlue">\
Legionnaire\'s Plate Hauberk'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Chest\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
706 Armor<br>\
+21 Strength<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 135/135<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 1%.\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant\'s Plate Gauntlets', '<span class = "myBlue">\
Blood Guard\'s Plate Gauntlets'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Hands\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
429 Armor<br>\
+17 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 45/45<br>\
Requires Level 60<br>\
Requires Rank 7<br>\
<span class = "myGreen">\
Equip: Hamstring Rage cost reduced by 3.</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Captain\'s Plate Leggings', '<span class = "myBlue">\
Legionnaire\'s Plate Leggings'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Legs\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
618 Armor<br>\
+12 Strength<br>\
+17 Stamina<br>\
Classes: Warrior<br>\
Durability 100/100<br>\
Requires Level 60<br>\
Requires Rank 8<br>\
<span class = "myGreen">\
Equip: Improves your chance to get a critical strike by 2%.\
</span>\
<p>';
t++;
armorSetPvPSuperior.itemNameArray[t] = ['<span class = "myBlue">\
Knight-Lieutenant Plate Greaves', '<span class = "myBlue">\
Blood Guard\'s Plate Greaves'];
armorSetPvPSuperior.statsArray[t] = '</span><br>\
Binds when picked up<br>\
<table cellspacing = "0" cellpadding = "0" border = "0" width = "265"><tr><td><span class = "myTable">\
Feet\
</span></td><td align = "right"><span class = "myTable">\
Plate\
</span></td></tr></table>\
472 Armor<br>\
+10 Strength<br>\
+9 Agility<br>\
+23 Stamina<br>\
Classes: Warrior<br>\
Durability 65/65<br>\
Requires Level 60<br>\
Requires Rank 7\
<span class = "myGreen">\
</span>\
<p>';
//Warrior end
armorSetsArray[theArmorSetCounter] = armorSetPvPSuperior;
armorSetsValues[theArmorSetCounter] = "pvpsuperior";
theArmorSetCounter++;
| gpl-2.0 |
mearleycf/boltgun2 | wp-content/themes/pilcrow/sidebar-footer.php | 1009 | <?php
/**
* The Footer widget areas.
*
* @package Pilcrow
* @since Pilcrow 1.0
*/
?>
<?php
/* The footer widget area is triggered if any of the areas
* have widgets. So let's check that first.
*
* If none of the sidebars have widgets, then let's bail early.
*/
if ( ! is_active_sidebar( 'sidebar-4' )
&& ! is_active_sidebar( 'sidebar-5' )
)
return;
// If we get this far, we have widgets. Let's do this.
?>
<div id="footer-widget-area" role="complementary">
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<div id="first" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-4' ); ?>
</ul>
</div><!-- #first .widget-area -->
<?php endif; ?>
<?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?>
<div id="second" class="widget-area">
<ul class="xoxo sidebar-list">
<?php dynamic_sidebar( 'sidebar-5' ); ?>
</ul>
</div><!-- #second .widget-area -->
<?php endif; ?>
</div><!-- #footer-widget-area -->
| gpl-2.0 |
taozhijiang/linux | drivers/infiniband/sw/rdmavt/qp.c | 44834 | /*
* Copyright(c) 2016 Intel Corporation.
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* 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 Intel Corporation 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.
*
*/
#include <linux/hash.h>
#include <linux/bitops.h>
#include <linux/lockdep.h>
#include <linux/vmalloc.h>
#include <linux/slab.h>
#include <rdma/ib_verbs.h>
#include "qp.h"
#include "vt.h"
#include "trace.h"
/*
* Note that it is OK to post send work requests in the SQE and ERR
* states; rvt_do_send() will process them and generate error
* completions as per IB 1.2 C10-96.
*/
const int ib_rvt_state_ops[IB_QPS_ERR + 1] = {
[IB_QPS_RESET] = 0,
[IB_QPS_INIT] = RVT_POST_RECV_OK,
[IB_QPS_RTR] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK,
[IB_QPS_RTS] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
RVT_POST_SEND_OK | RVT_PROCESS_SEND_OK |
RVT_PROCESS_NEXT_SEND_OK,
[IB_QPS_SQD] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
RVT_POST_SEND_OK | RVT_PROCESS_SEND_OK,
[IB_QPS_SQE] = RVT_POST_RECV_OK | RVT_PROCESS_RECV_OK |
RVT_POST_SEND_OK | RVT_FLUSH_SEND,
[IB_QPS_ERR] = RVT_POST_RECV_OK | RVT_FLUSH_RECV |
RVT_POST_SEND_OK | RVT_FLUSH_SEND,
};
EXPORT_SYMBOL(ib_rvt_state_ops);
static void get_map_page(struct rvt_qpn_table *qpt,
struct rvt_qpn_map *map,
gfp_t gfp)
{
unsigned long page = get_zeroed_page(gfp);
/*
* Free the page if someone raced with us installing it.
*/
spin_lock(&qpt->lock);
if (map->page)
free_page(page);
else
map->page = (void *)page;
spin_unlock(&qpt->lock);
}
/**
* init_qpn_table - initialize the QP number table for a device
* @qpt: the QPN table
*/
static int init_qpn_table(struct rvt_dev_info *rdi, struct rvt_qpn_table *qpt)
{
u32 offset, i;
struct rvt_qpn_map *map;
int ret = 0;
if (!(rdi->dparms.qpn_res_end >= rdi->dparms.qpn_res_start))
return -EINVAL;
spin_lock_init(&qpt->lock);
qpt->last = rdi->dparms.qpn_start;
qpt->incr = rdi->dparms.qpn_inc << rdi->dparms.qos_shift;
/*
* Drivers may want some QPs beyond what we need for verbs let them use
* our qpn table. No need for two. Lets go ahead and mark the bitmaps
* for those. The reserved range must be *after* the range which verbs
* will pick from.
*/
/* Figure out number of bit maps needed before reserved range */
qpt->nmaps = rdi->dparms.qpn_res_start / RVT_BITS_PER_PAGE;
/* This should always be zero */
offset = rdi->dparms.qpn_res_start & RVT_BITS_PER_PAGE_MASK;
/* Starting with the first reserved bit map */
map = &qpt->map[qpt->nmaps];
rvt_pr_info(rdi, "Reserving QPNs from 0x%x to 0x%x for non-verbs use\n",
rdi->dparms.qpn_res_start, rdi->dparms.qpn_res_end);
for (i = rdi->dparms.qpn_res_start; i <= rdi->dparms.qpn_res_end; i++) {
if (!map->page) {
get_map_page(qpt, map, GFP_KERNEL);
if (!map->page) {
ret = -ENOMEM;
break;
}
}
set_bit(offset, map->page);
offset++;
if (offset == RVT_BITS_PER_PAGE) {
/* next page */
qpt->nmaps++;
map++;
offset = 0;
}
}
return ret;
}
/**
* free_qpn_table - free the QP number table for a device
* @qpt: the QPN table
*/
static void free_qpn_table(struct rvt_qpn_table *qpt)
{
int i;
for (i = 0; i < ARRAY_SIZE(qpt->map); i++)
free_page((unsigned long)qpt->map[i].page);
}
/**
* rvt_driver_qp_init - Init driver qp resources
* @rdi: rvt dev strucutre
*
* Return: 0 on success
*/
int rvt_driver_qp_init(struct rvt_dev_info *rdi)
{
int i;
int ret = -ENOMEM;
if (!rdi->dparms.qp_table_size)
return -EINVAL;
/*
* If driver is not doing any QP allocation then make sure it is
* providing the necessary QP functions.
*/
if (!rdi->driver_f.free_all_qps ||
!rdi->driver_f.qp_priv_alloc ||
!rdi->driver_f.qp_priv_free ||
!rdi->driver_f.notify_qp_reset)
return -EINVAL;
/* allocate parent object */
rdi->qp_dev = kzalloc_node(sizeof(*rdi->qp_dev), GFP_KERNEL,
rdi->dparms.node);
if (!rdi->qp_dev)
return -ENOMEM;
/* allocate hash table */
rdi->qp_dev->qp_table_size = rdi->dparms.qp_table_size;
rdi->qp_dev->qp_table_bits = ilog2(rdi->dparms.qp_table_size);
rdi->qp_dev->qp_table =
kmalloc_node(rdi->qp_dev->qp_table_size *
sizeof(*rdi->qp_dev->qp_table),
GFP_KERNEL, rdi->dparms.node);
if (!rdi->qp_dev->qp_table)
goto no_qp_table;
for (i = 0; i < rdi->qp_dev->qp_table_size; i++)
RCU_INIT_POINTER(rdi->qp_dev->qp_table[i], NULL);
spin_lock_init(&rdi->qp_dev->qpt_lock);
/* initialize qpn map */
if (init_qpn_table(rdi, &rdi->qp_dev->qpn_table))
goto fail_table;
spin_lock_init(&rdi->n_qps_lock);
return 0;
fail_table:
kfree(rdi->qp_dev->qp_table);
free_qpn_table(&rdi->qp_dev->qpn_table);
no_qp_table:
kfree(rdi->qp_dev);
return ret;
}
/**
* free_all_qps - check for QPs still in use
* @qpt: the QP table to empty
*
* There should not be any QPs still in use.
* Free memory for table.
*/
static unsigned rvt_free_all_qps(struct rvt_dev_info *rdi)
{
unsigned long flags;
struct rvt_qp *qp;
unsigned n, qp_inuse = 0;
spinlock_t *ql; /* work around too long line below */
if (rdi->driver_f.free_all_qps)
qp_inuse = rdi->driver_f.free_all_qps(rdi);
qp_inuse += rvt_mcast_tree_empty(rdi);
if (!rdi->qp_dev)
return qp_inuse;
ql = &rdi->qp_dev->qpt_lock;
spin_lock_irqsave(ql, flags);
for (n = 0; n < rdi->qp_dev->qp_table_size; n++) {
qp = rcu_dereference_protected(rdi->qp_dev->qp_table[n],
lockdep_is_held(ql));
RCU_INIT_POINTER(rdi->qp_dev->qp_table[n], NULL);
for (; qp; qp = rcu_dereference_protected(qp->next,
lockdep_is_held(ql)))
qp_inuse++;
}
spin_unlock_irqrestore(ql, flags);
synchronize_rcu();
return qp_inuse;
}
/**
* rvt_qp_exit - clean up qps on device exit
* @rdi: rvt dev structure
*
* Check for qp leaks and free resources.
*/
void rvt_qp_exit(struct rvt_dev_info *rdi)
{
u32 qps_inuse = rvt_free_all_qps(rdi);
if (qps_inuse)
rvt_pr_err(rdi, "QP memory leak! %u still in use\n",
qps_inuse);
if (!rdi->qp_dev)
return;
kfree(rdi->qp_dev->qp_table);
free_qpn_table(&rdi->qp_dev->qpn_table);
kfree(rdi->qp_dev);
}
static inline unsigned mk_qpn(struct rvt_qpn_table *qpt,
struct rvt_qpn_map *map, unsigned off)
{
return (map - qpt->map) * RVT_BITS_PER_PAGE + off;
}
/**
* alloc_qpn - Allocate the next available qpn or zero/one for QP type
* IB_QPT_SMI/IB_QPT_GSI
*@rdi: rvt device info structure
*@qpt: queue pair number table pointer
*@port_num: IB port number, 1 based, comes from core
*
* Return: The queue pair number
*/
static int alloc_qpn(struct rvt_dev_info *rdi, struct rvt_qpn_table *qpt,
enum ib_qp_type type, u8 port_num, gfp_t gfp)
{
u32 i, offset, max_scan, qpn;
struct rvt_qpn_map *map;
u32 ret;
if (rdi->driver_f.alloc_qpn)
return rdi->driver_f.alloc_qpn(rdi, qpt, type, port_num, gfp);
if (type == IB_QPT_SMI || type == IB_QPT_GSI) {
unsigned n;
ret = type == IB_QPT_GSI;
n = 1 << (ret + 2 * (port_num - 1));
spin_lock(&qpt->lock);
if (qpt->flags & n)
ret = -EINVAL;
else
qpt->flags |= n;
spin_unlock(&qpt->lock);
goto bail;
}
qpn = qpt->last + qpt->incr;
if (qpn >= RVT_QPN_MAX)
qpn = qpt->incr | ((qpt->last & 1) ^ 1);
/* offset carries bit 0 */
offset = qpn & RVT_BITS_PER_PAGE_MASK;
map = &qpt->map[qpn / RVT_BITS_PER_PAGE];
max_scan = qpt->nmaps - !offset;
for (i = 0;;) {
if (unlikely(!map->page)) {
get_map_page(qpt, map, gfp);
if (unlikely(!map->page))
break;
}
do {
if (!test_and_set_bit(offset, map->page)) {
qpt->last = qpn;
ret = qpn;
goto bail;
}
offset += qpt->incr;
/*
* This qpn might be bogus if offset >= BITS_PER_PAGE.
* That is OK. It gets re-assigned below
*/
qpn = mk_qpn(qpt, map, offset);
} while (offset < RVT_BITS_PER_PAGE && qpn < RVT_QPN_MAX);
/*
* In order to keep the number of pages allocated to a
* minimum, we scan the all existing pages before increasing
* the size of the bitmap table.
*/
if (++i > max_scan) {
if (qpt->nmaps == RVT_QPNMAP_ENTRIES)
break;
map = &qpt->map[qpt->nmaps++];
/* start at incr with current bit 0 */
offset = qpt->incr | (offset & 1);
} else if (map < &qpt->map[qpt->nmaps]) {
++map;
/* start at incr with current bit 0 */
offset = qpt->incr | (offset & 1);
} else {
map = &qpt->map[0];
/* wrap to first map page, invert bit 0 */
offset = qpt->incr | ((offset & 1) ^ 1);
}
/* there can be no bits at shift and below */
WARN_ON(offset & (rdi->dparms.qos_shift - 1));
qpn = mk_qpn(qpt, map, offset);
}
ret = -ENOMEM;
bail:
return ret;
}
static void free_qpn(struct rvt_qpn_table *qpt, u32 qpn)
{
struct rvt_qpn_map *map;
map = qpt->map + qpn / RVT_BITS_PER_PAGE;
if (map->page)
clear_bit(qpn & RVT_BITS_PER_PAGE_MASK, map->page);
}
/**
* rvt_clear_mr_refs - Drop help mr refs
* @qp: rvt qp data structure
* @clr_sends: If shoudl clear send side or not
*/
static void rvt_clear_mr_refs(struct rvt_qp *qp, int clr_sends)
{
unsigned n;
struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
if (test_and_clear_bit(RVT_R_REWIND_SGE, &qp->r_aflags))
rvt_put_ss(&qp->s_rdma_read_sge);
rvt_put_ss(&qp->r_sge);
if (clr_sends) {
while (qp->s_last != qp->s_head) {
struct rvt_swqe *wqe = rvt_get_swqe_ptr(qp, qp->s_last);
unsigned i;
for (i = 0; i < wqe->wr.num_sge; i++) {
struct rvt_sge *sge = &wqe->sg_list[i];
rvt_put_mr(sge->mr);
}
if (qp->ibqp.qp_type == IB_QPT_UD ||
qp->ibqp.qp_type == IB_QPT_SMI ||
qp->ibqp.qp_type == IB_QPT_GSI)
atomic_dec(&ibah_to_rvtah(
wqe->ud_wr.ah)->refcount);
if (++qp->s_last >= qp->s_size)
qp->s_last = 0;
smp_wmb(); /* see qp_set_savail */
}
if (qp->s_rdma_mr) {
rvt_put_mr(qp->s_rdma_mr);
qp->s_rdma_mr = NULL;
}
}
if (qp->ibqp.qp_type != IB_QPT_RC)
return;
for (n = 0; n < rvt_max_atomic(rdi); n++) {
struct rvt_ack_entry *e = &qp->s_ack_queue[n];
if (e->opcode == IB_OPCODE_RC_RDMA_READ_REQUEST &&
e->rdma_sge.mr) {
rvt_put_mr(e->rdma_sge.mr);
e->rdma_sge.mr = NULL;
}
}
}
/**
* rvt_remove_qp - remove qp form table
* @rdi: rvt dev struct
* @qp: qp to remove
*
* Remove the QP from the table so it can't be found asynchronously by
* the receive routine.
*/
static void rvt_remove_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp)
{
struct rvt_ibport *rvp = rdi->ports[qp->port_num - 1];
u32 n = hash_32(qp->ibqp.qp_num, rdi->qp_dev->qp_table_bits);
unsigned long flags;
int removed = 1;
spin_lock_irqsave(&rdi->qp_dev->qpt_lock, flags);
if (rcu_dereference_protected(rvp->qp[0],
lockdep_is_held(&rdi->qp_dev->qpt_lock)) == qp) {
RCU_INIT_POINTER(rvp->qp[0], NULL);
} else if (rcu_dereference_protected(rvp->qp[1],
lockdep_is_held(&rdi->qp_dev->qpt_lock)) == qp) {
RCU_INIT_POINTER(rvp->qp[1], NULL);
} else {
struct rvt_qp *q;
struct rvt_qp __rcu **qpp;
removed = 0;
qpp = &rdi->qp_dev->qp_table[n];
for (; (q = rcu_dereference_protected(*qpp,
lockdep_is_held(&rdi->qp_dev->qpt_lock))) != NULL;
qpp = &q->next) {
if (q == qp) {
RCU_INIT_POINTER(*qpp,
rcu_dereference_protected(qp->next,
lockdep_is_held(&rdi->qp_dev->qpt_lock)));
removed = 1;
trace_rvt_qpremove(qp, n);
break;
}
}
}
spin_unlock_irqrestore(&rdi->qp_dev->qpt_lock, flags);
if (removed) {
synchronize_rcu();
if (atomic_dec_and_test(&qp->refcount))
wake_up(&qp->wait);
}
}
/**
* reset_qp - initialize the QP state to the reset state
* @qp: the QP to reset
* @type: the QP type
* r and s lock are required to be held by the caller
*/
static void rvt_reset_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp,
enum ib_qp_type type)
__releases(&qp->s_lock)
__releases(&qp->s_hlock)
__releases(&qp->r_lock)
__acquires(&qp->r_lock)
__acquires(&qp->s_hlock)
__acquires(&qp->s_lock)
{
if (qp->state != IB_QPS_RESET) {
qp->state = IB_QPS_RESET;
/* Let drivers flush their waitlist */
rdi->driver_f.flush_qp_waiters(qp);
qp->s_flags &= ~(RVT_S_TIMER | RVT_S_ANY_WAIT);
spin_unlock(&qp->s_lock);
spin_unlock(&qp->s_hlock);
spin_unlock_irq(&qp->r_lock);
/* Stop the send queue and the retry timer */
rdi->driver_f.stop_send_queue(qp);
/* Wait for things to stop */
rdi->driver_f.quiesce_qp(qp);
/* take qp out the hash and wait for it to be unused */
rvt_remove_qp(rdi, qp);
wait_event(qp->wait, !atomic_read(&qp->refcount));
/* grab the lock b/c it was locked at call time */
spin_lock_irq(&qp->r_lock);
spin_lock(&qp->s_hlock);
spin_lock(&qp->s_lock);
rvt_clear_mr_refs(qp, 1);
}
/*
* Let the driver do any tear down it needs to for a qp
* that has been reset
*/
rdi->driver_f.notify_qp_reset(qp);
qp->remote_qpn = 0;
qp->qkey = 0;
qp->qp_access_flags = 0;
qp->s_flags &= RVT_S_SIGNAL_REQ_WR;
qp->s_hdrwords = 0;
qp->s_wqe = NULL;
qp->s_draining = 0;
qp->s_next_psn = 0;
qp->s_last_psn = 0;
qp->s_sending_psn = 0;
qp->s_sending_hpsn = 0;
qp->s_psn = 0;
qp->r_psn = 0;
qp->r_msn = 0;
if (type == IB_QPT_RC) {
qp->s_state = IB_OPCODE_RC_SEND_LAST;
qp->r_state = IB_OPCODE_RC_SEND_LAST;
} else {
qp->s_state = IB_OPCODE_UC_SEND_LAST;
qp->r_state = IB_OPCODE_UC_SEND_LAST;
}
qp->s_ack_state = IB_OPCODE_RC_ACKNOWLEDGE;
qp->r_nak_state = 0;
qp->r_aflags = 0;
qp->r_flags = 0;
qp->s_head = 0;
qp->s_tail = 0;
qp->s_cur = 0;
qp->s_acked = 0;
qp->s_last = 0;
qp->s_ssn = 1;
qp->s_lsn = 0;
qp->s_mig_state = IB_MIG_MIGRATED;
if (qp->s_ack_queue)
memset(
qp->s_ack_queue,
0,
rvt_max_atomic(rdi) *
sizeof(*qp->s_ack_queue));
qp->r_head_ack_queue = 0;
qp->s_tail_ack_queue = 0;
qp->s_num_rd_atomic = 0;
if (qp->r_rq.wq) {
qp->r_rq.wq->head = 0;
qp->r_rq.wq->tail = 0;
}
qp->r_sge.num_sge = 0;
}
/**
* rvt_create_qp - create a queue pair for a device
* @ibpd: the protection domain who's device we create the queue pair for
* @init_attr: the attributes of the queue pair
* @udata: user data for libibverbs.so
*
* Queue pair creation is mostly an rvt issue. However, drivers have their own
* unique idea of what queue pair numbers mean. For instance there is a reserved
* range for PSM.
*
* Return: the queue pair on success, otherwise returns an errno.
*
* Called by the ib_create_qp() core verbs function.
*/
struct ib_qp *rvt_create_qp(struct ib_pd *ibpd,
struct ib_qp_init_attr *init_attr,
struct ib_udata *udata)
{
struct rvt_qp *qp;
int err;
struct rvt_swqe *swq = NULL;
size_t sz;
size_t sg_list_sz;
struct ib_qp *ret = ERR_PTR(-ENOMEM);
struct rvt_dev_info *rdi = ib_to_rvt(ibpd->device);
void *priv = NULL;
gfp_t gfp;
if (!rdi)
return ERR_PTR(-EINVAL);
if (init_attr->cap.max_send_sge > rdi->dparms.props.max_sge ||
init_attr->cap.max_send_wr > rdi->dparms.props.max_qp_wr ||
init_attr->create_flags & ~(IB_QP_CREATE_USE_GFP_NOIO))
return ERR_PTR(-EINVAL);
/* GFP_NOIO is applicable to RC QP's only */
if (init_attr->create_flags & IB_QP_CREATE_USE_GFP_NOIO &&
init_attr->qp_type != IB_QPT_RC)
return ERR_PTR(-EINVAL);
gfp = init_attr->create_flags & IB_QP_CREATE_USE_GFP_NOIO ?
GFP_NOIO : GFP_KERNEL;
/* Check receive queue parameters if no SRQ is specified. */
if (!init_attr->srq) {
if (init_attr->cap.max_recv_sge > rdi->dparms.props.max_sge ||
init_attr->cap.max_recv_wr > rdi->dparms.props.max_qp_wr)
return ERR_PTR(-EINVAL);
if (init_attr->cap.max_send_sge +
init_attr->cap.max_send_wr +
init_attr->cap.max_recv_sge +
init_attr->cap.max_recv_wr == 0)
return ERR_PTR(-EINVAL);
}
switch (init_attr->qp_type) {
case IB_QPT_SMI:
case IB_QPT_GSI:
if (init_attr->port_num == 0 ||
init_attr->port_num > ibpd->device->phys_port_cnt)
return ERR_PTR(-EINVAL);
case IB_QPT_UC:
case IB_QPT_RC:
case IB_QPT_UD:
sz = sizeof(struct rvt_sge) *
init_attr->cap.max_send_sge +
sizeof(struct rvt_swqe);
if (gfp == GFP_NOIO)
swq = __vmalloc(
(init_attr->cap.max_send_wr + 1) * sz,
gfp | __GFP_ZERO, PAGE_KERNEL);
else
swq = vzalloc_node(
(init_attr->cap.max_send_wr + 1) * sz,
rdi->dparms.node);
if (!swq)
return ERR_PTR(-ENOMEM);
sz = sizeof(*qp);
sg_list_sz = 0;
if (init_attr->srq) {
struct rvt_srq *srq = ibsrq_to_rvtsrq(init_attr->srq);
if (srq->rq.max_sge > 1)
sg_list_sz = sizeof(*qp->r_sg_list) *
(srq->rq.max_sge - 1);
} else if (init_attr->cap.max_recv_sge > 1)
sg_list_sz = sizeof(*qp->r_sg_list) *
(init_attr->cap.max_recv_sge - 1);
qp = kzalloc_node(sz + sg_list_sz, gfp, rdi->dparms.node);
if (!qp)
goto bail_swq;
RCU_INIT_POINTER(qp->next, NULL);
if (init_attr->qp_type == IB_QPT_RC) {
qp->s_ack_queue =
kzalloc_node(
sizeof(*qp->s_ack_queue) *
rvt_max_atomic(rdi),
gfp,
rdi->dparms.node);
if (!qp->s_ack_queue)
goto bail_qp;
}
/*
* Driver needs to set up it's private QP structure and do any
* initialization that is needed.
*/
priv = rdi->driver_f.qp_priv_alloc(rdi, qp, gfp);
if (!priv)
goto bail_qp;
qp->priv = priv;
qp->timeout_jiffies =
usecs_to_jiffies((4096UL * (1UL << qp->timeout)) /
1000UL);
if (init_attr->srq) {
sz = 0;
} else {
qp->r_rq.size = init_attr->cap.max_recv_wr + 1;
qp->r_rq.max_sge = init_attr->cap.max_recv_sge;
sz = (sizeof(struct ib_sge) * qp->r_rq.max_sge) +
sizeof(struct rvt_rwqe);
if (udata)
qp->r_rq.wq = vmalloc_user(
sizeof(struct rvt_rwq) +
qp->r_rq.size * sz);
else if (gfp == GFP_NOIO)
qp->r_rq.wq = __vmalloc(
sizeof(struct rvt_rwq) +
qp->r_rq.size * sz,
gfp | __GFP_ZERO, PAGE_KERNEL);
else
qp->r_rq.wq = vzalloc_node(
sizeof(struct rvt_rwq) +
qp->r_rq.size * sz,
rdi->dparms.node);
if (!qp->r_rq.wq)
goto bail_driver_priv;
}
/*
* ib_create_qp() will initialize qp->ibqp
* except for qp->ibqp.qp_num.
*/
spin_lock_init(&qp->r_lock);
spin_lock_init(&qp->s_hlock);
spin_lock_init(&qp->s_lock);
spin_lock_init(&qp->r_rq.lock);
atomic_set(&qp->refcount, 0);
init_waitqueue_head(&qp->wait);
init_timer(&qp->s_timer);
qp->s_timer.data = (unsigned long)qp;
INIT_LIST_HEAD(&qp->rspwait);
qp->state = IB_QPS_RESET;
qp->s_wq = swq;
qp->s_size = init_attr->cap.max_send_wr + 1;
qp->s_avail = init_attr->cap.max_send_wr;
qp->s_max_sge = init_attr->cap.max_send_sge;
if (init_attr->sq_sig_type == IB_SIGNAL_REQ_WR)
qp->s_flags = RVT_S_SIGNAL_REQ_WR;
err = alloc_qpn(rdi, &rdi->qp_dev->qpn_table,
init_attr->qp_type,
init_attr->port_num, gfp);
if (err < 0) {
ret = ERR_PTR(err);
goto bail_rq_wq;
}
qp->ibqp.qp_num = err;
qp->port_num = init_attr->port_num;
rvt_reset_qp(rdi, qp, init_attr->qp_type);
break;
default:
/* Don't support raw QPs */
return ERR_PTR(-EINVAL);
}
init_attr->cap.max_inline_data = 0;
/*
* Return the address of the RWQ as the offset to mmap.
* See rvt_mmap() for details.
*/
if (udata && udata->outlen >= sizeof(__u64)) {
if (!qp->r_rq.wq) {
__u64 offset = 0;
err = ib_copy_to_udata(udata, &offset,
sizeof(offset));
if (err) {
ret = ERR_PTR(err);
goto bail_qpn;
}
} else {
u32 s = sizeof(struct rvt_rwq) + qp->r_rq.size * sz;
qp->ip = rvt_create_mmap_info(rdi, s,
ibpd->uobject->context,
qp->r_rq.wq);
if (!qp->ip) {
ret = ERR_PTR(-ENOMEM);
goto bail_qpn;
}
err = ib_copy_to_udata(udata, &qp->ip->offset,
sizeof(qp->ip->offset));
if (err) {
ret = ERR_PTR(err);
goto bail_ip;
}
}
qp->pid = current->pid;
}
spin_lock(&rdi->n_qps_lock);
if (rdi->n_qps_allocated == rdi->dparms.props.max_qp) {
spin_unlock(&rdi->n_qps_lock);
ret = ERR_PTR(-ENOMEM);
goto bail_ip;
}
rdi->n_qps_allocated++;
/*
* Maintain a busy_jiffies variable that will be added to the timeout
* period in mod_retry_timer and add_retry_timer. This busy jiffies
* is scaled by the number of rc qps created for the device to reduce
* the number of timeouts occurring when there is a large number of
* qps. busy_jiffies is incremented every rc qp scaling interval.
* The scaling interval is selected based on extensive performance
* evaluation of targeted workloads.
*/
if (init_attr->qp_type == IB_QPT_RC) {
rdi->n_rc_qps++;
rdi->busy_jiffies = rdi->n_rc_qps / RC_QP_SCALING_INTERVAL;
}
spin_unlock(&rdi->n_qps_lock);
if (qp->ip) {
spin_lock_irq(&rdi->pending_lock);
list_add(&qp->ip->pending_mmaps, &rdi->pending_mmaps);
spin_unlock_irq(&rdi->pending_lock);
}
ret = &qp->ibqp;
/*
* We have our QP and its good, now keep track of what types of opcodes
* can be processed on this QP. We do this by keeping track of what the
* 3 high order bits of the opcode are.
*/
switch (init_attr->qp_type) {
case IB_QPT_SMI:
case IB_QPT_GSI:
case IB_QPT_UD:
qp->allowed_ops = IB_OPCODE_UD;
break;
case IB_QPT_RC:
qp->allowed_ops = IB_OPCODE_RC;
break;
case IB_QPT_UC:
qp->allowed_ops = IB_OPCODE_UC;
break;
default:
ret = ERR_PTR(-EINVAL);
goto bail_ip;
}
return ret;
bail_ip:
kref_put(&qp->ip->ref, rvt_release_mmap_info);
bail_qpn:
free_qpn(&rdi->qp_dev->qpn_table, qp->ibqp.qp_num);
bail_rq_wq:
vfree(qp->r_rq.wq);
bail_driver_priv:
rdi->driver_f.qp_priv_free(rdi, qp);
bail_qp:
kfree(qp->s_ack_queue);
kfree(qp);
bail_swq:
vfree(swq);
return ret;
}
/**
* rvt_error_qp - put a QP into the error state
* @qp: the QP to put into the error state
* @err: the receive completion error to signal if a RWQE is active
*
* Flushes both send and receive work queues.
*
* Return: true if last WQE event should be generated.
* The QP r_lock and s_lock should be held and interrupts disabled.
* If we are already in error state, just return.
*/
int rvt_error_qp(struct rvt_qp *qp, enum ib_wc_status err)
{
struct ib_wc wc;
int ret = 0;
struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
if (qp->state == IB_QPS_ERR || qp->state == IB_QPS_RESET)
goto bail;
qp->state = IB_QPS_ERR;
if (qp->s_flags & (RVT_S_TIMER | RVT_S_WAIT_RNR)) {
qp->s_flags &= ~(RVT_S_TIMER | RVT_S_WAIT_RNR);
del_timer(&qp->s_timer);
}
if (qp->s_flags & RVT_S_ANY_WAIT_SEND)
qp->s_flags &= ~RVT_S_ANY_WAIT_SEND;
rdi->driver_f.notify_error_qp(qp);
/* Schedule the sending tasklet to drain the send work queue. */
if (ACCESS_ONCE(qp->s_last) != qp->s_head)
rdi->driver_f.schedule_send(qp);
rvt_clear_mr_refs(qp, 0);
memset(&wc, 0, sizeof(wc));
wc.qp = &qp->ibqp;
wc.opcode = IB_WC_RECV;
if (test_and_clear_bit(RVT_R_WRID_VALID, &qp->r_aflags)) {
wc.wr_id = qp->r_wr_id;
wc.status = err;
rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
}
wc.status = IB_WC_WR_FLUSH_ERR;
if (qp->r_rq.wq) {
struct rvt_rwq *wq;
u32 head;
u32 tail;
spin_lock(&qp->r_rq.lock);
/* sanity check pointers before trusting them */
wq = qp->r_rq.wq;
head = wq->head;
if (head >= qp->r_rq.size)
head = 0;
tail = wq->tail;
if (tail >= qp->r_rq.size)
tail = 0;
while (tail != head) {
wc.wr_id = rvt_get_rwqe_ptr(&qp->r_rq, tail)->wr_id;
if (++tail >= qp->r_rq.size)
tail = 0;
rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
}
wq->tail = tail;
spin_unlock(&qp->r_rq.lock);
} else if (qp->ibqp.event_handler) {
ret = 1;
}
bail:
return ret;
}
EXPORT_SYMBOL(rvt_error_qp);
/*
* Put the QP into the hash table.
* The hash table holds a reference to the QP.
*/
static void rvt_insert_qp(struct rvt_dev_info *rdi, struct rvt_qp *qp)
{
struct rvt_ibport *rvp = rdi->ports[qp->port_num - 1];
unsigned long flags;
atomic_inc(&qp->refcount);
spin_lock_irqsave(&rdi->qp_dev->qpt_lock, flags);
if (qp->ibqp.qp_num <= 1) {
rcu_assign_pointer(rvp->qp[qp->ibqp.qp_num], qp);
} else {
u32 n = hash_32(qp->ibqp.qp_num, rdi->qp_dev->qp_table_bits);
qp->next = rdi->qp_dev->qp_table[n];
rcu_assign_pointer(rdi->qp_dev->qp_table[n], qp);
trace_rvt_qpinsert(qp, n);
}
spin_unlock_irqrestore(&rdi->qp_dev->qpt_lock, flags);
}
/**
* qib_modify_qp - modify the attributes of a queue pair
* @ibqp: the queue pair who's attributes we're modifying
* @attr: the new attributes
* @attr_mask: the mask of attributes to modify
* @udata: user data for libibverbs.so
*
* Return: 0 on success, otherwise returns an errno.
*/
int rvt_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_udata *udata)
{
struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
enum ib_qp_state cur_state, new_state;
struct ib_event ev;
int lastwqe = 0;
int mig = 0;
int pmtu = 0; /* for gcc warning only */
enum rdma_link_layer link;
link = rdma_port_get_link_layer(ibqp->device, qp->port_num);
spin_lock_irq(&qp->r_lock);
spin_lock(&qp->s_hlock);
spin_lock(&qp->s_lock);
cur_state = attr_mask & IB_QP_CUR_STATE ?
attr->cur_qp_state : qp->state;
new_state = attr_mask & IB_QP_STATE ? attr->qp_state : cur_state;
if (!ib_modify_qp_is_ok(cur_state, new_state, ibqp->qp_type,
attr_mask, link))
goto inval;
if (rdi->driver_f.check_modify_qp &&
rdi->driver_f.check_modify_qp(qp, attr, attr_mask, udata))
goto inval;
if (attr_mask & IB_QP_AV) {
if (attr->ah_attr.dlid >= be16_to_cpu(IB_MULTICAST_LID_BASE))
goto inval;
if (rvt_check_ah(qp->ibqp.device, &attr->ah_attr))
goto inval;
}
if (attr_mask & IB_QP_ALT_PATH) {
if (attr->alt_ah_attr.dlid >=
be16_to_cpu(IB_MULTICAST_LID_BASE))
goto inval;
if (rvt_check_ah(qp->ibqp.device, &attr->alt_ah_attr))
goto inval;
if (attr->alt_pkey_index >= rvt_get_npkeys(rdi))
goto inval;
}
if (attr_mask & IB_QP_PKEY_INDEX)
if (attr->pkey_index >= rvt_get_npkeys(rdi))
goto inval;
if (attr_mask & IB_QP_MIN_RNR_TIMER)
if (attr->min_rnr_timer > 31)
goto inval;
if (attr_mask & IB_QP_PORT)
if (qp->ibqp.qp_type == IB_QPT_SMI ||
qp->ibqp.qp_type == IB_QPT_GSI ||
attr->port_num == 0 ||
attr->port_num > ibqp->device->phys_port_cnt)
goto inval;
if (attr_mask & IB_QP_DEST_QPN)
if (attr->dest_qp_num > RVT_QPN_MASK)
goto inval;
if (attr_mask & IB_QP_RETRY_CNT)
if (attr->retry_cnt > 7)
goto inval;
if (attr_mask & IB_QP_RNR_RETRY)
if (attr->rnr_retry > 7)
goto inval;
/*
* Don't allow invalid path_mtu values. OK to set greater
* than the active mtu (or even the max_cap, if we have tuned
* that to a small mtu. We'll set qp->path_mtu
* to the lesser of requested attribute mtu and active,
* for packetizing messages.
* Note that the QP port has to be set in INIT and MTU in RTR.
*/
if (attr_mask & IB_QP_PATH_MTU) {
pmtu = rdi->driver_f.get_pmtu_from_attr(rdi, qp, attr);
if (pmtu < 0)
goto inval;
}
if (attr_mask & IB_QP_PATH_MIG_STATE) {
if (attr->path_mig_state == IB_MIG_REARM) {
if (qp->s_mig_state == IB_MIG_ARMED)
goto inval;
if (new_state != IB_QPS_RTS)
goto inval;
} else if (attr->path_mig_state == IB_MIG_MIGRATED) {
if (qp->s_mig_state == IB_MIG_REARM)
goto inval;
if (new_state != IB_QPS_RTS && new_state != IB_QPS_SQD)
goto inval;
if (qp->s_mig_state == IB_MIG_ARMED)
mig = 1;
} else {
goto inval;
}
}
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
if (attr->max_dest_rd_atomic > rdi->dparms.max_rdma_atomic)
goto inval;
switch (new_state) {
case IB_QPS_RESET:
if (qp->state != IB_QPS_RESET)
rvt_reset_qp(rdi, qp, ibqp->qp_type);
break;
case IB_QPS_RTR:
/* Allow event to re-trigger if QP set to RTR more than once */
qp->r_flags &= ~RVT_R_COMM_EST;
qp->state = new_state;
break;
case IB_QPS_SQD:
qp->s_draining = qp->s_last != qp->s_cur;
qp->state = new_state;
break;
case IB_QPS_SQE:
if (qp->ibqp.qp_type == IB_QPT_RC)
goto inval;
qp->state = new_state;
break;
case IB_QPS_ERR:
lastwqe = rvt_error_qp(qp, IB_WC_WR_FLUSH_ERR);
break;
default:
qp->state = new_state;
break;
}
if (attr_mask & IB_QP_PKEY_INDEX)
qp->s_pkey_index = attr->pkey_index;
if (attr_mask & IB_QP_PORT)
qp->port_num = attr->port_num;
if (attr_mask & IB_QP_DEST_QPN)
qp->remote_qpn = attr->dest_qp_num;
if (attr_mask & IB_QP_SQ_PSN) {
qp->s_next_psn = attr->sq_psn & rdi->dparms.psn_modify_mask;
qp->s_psn = qp->s_next_psn;
qp->s_sending_psn = qp->s_next_psn;
qp->s_last_psn = qp->s_next_psn - 1;
qp->s_sending_hpsn = qp->s_last_psn;
}
if (attr_mask & IB_QP_RQ_PSN)
qp->r_psn = attr->rq_psn & rdi->dparms.psn_modify_mask;
if (attr_mask & IB_QP_ACCESS_FLAGS)
qp->qp_access_flags = attr->qp_access_flags;
if (attr_mask & IB_QP_AV) {
qp->remote_ah_attr = attr->ah_attr;
qp->s_srate = attr->ah_attr.static_rate;
qp->srate_mbps = ib_rate_to_mbps(qp->s_srate);
}
if (attr_mask & IB_QP_ALT_PATH) {
qp->alt_ah_attr = attr->alt_ah_attr;
qp->s_alt_pkey_index = attr->alt_pkey_index;
}
if (attr_mask & IB_QP_PATH_MIG_STATE) {
qp->s_mig_state = attr->path_mig_state;
if (mig) {
qp->remote_ah_attr = qp->alt_ah_attr;
qp->port_num = qp->alt_ah_attr.port_num;
qp->s_pkey_index = qp->s_alt_pkey_index;
}
}
if (attr_mask & IB_QP_PATH_MTU) {
qp->pmtu = rdi->driver_f.mtu_from_qp(rdi, qp, pmtu);
qp->path_mtu = rdi->driver_f.mtu_to_path_mtu(qp->pmtu);
qp->log_pmtu = ilog2(qp->pmtu);
}
if (attr_mask & IB_QP_RETRY_CNT) {
qp->s_retry_cnt = attr->retry_cnt;
qp->s_retry = attr->retry_cnt;
}
if (attr_mask & IB_QP_RNR_RETRY) {
qp->s_rnr_retry_cnt = attr->rnr_retry;
qp->s_rnr_retry = attr->rnr_retry;
}
if (attr_mask & IB_QP_MIN_RNR_TIMER)
qp->r_min_rnr_timer = attr->min_rnr_timer;
if (attr_mask & IB_QP_TIMEOUT) {
qp->timeout = attr->timeout;
qp->timeout_jiffies =
usecs_to_jiffies((4096UL * (1UL << qp->timeout)) /
1000UL);
}
if (attr_mask & IB_QP_QKEY)
qp->qkey = attr->qkey;
if (attr_mask & IB_QP_MAX_DEST_RD_ATOMIC)
qp->r_max_rd_atomic = attr->max_dest_rd_atomic;
if (attr_mask & IB_QP_MAX_QP_RD_ATOMIC)
qp->s_max_rd_atomic = attr->max_rd_atomic;
if (rdi->driver_f.modify_qp)
rdi->driver_f.modify_qp(qp, attr, attr_mask, udata);
spin_unlock(&qp->s_lock);
spin_unlock(&qp->s_hlock);
spin_unlock_irq(&qp->r_lock);
if (cur_state == IB_QPS_RESET && new_state == IB_QPS_INIT)
rvt_insert_qp(rdi, qp);
if (lastwqe) {
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_QP_LAST_WQE_REACHED;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
if (mig) {
ev.device = qp->ibqp.device;
ev.element.qp = &qp->ibqp;
ev.event = IB_EVENT_PATH_MIG;
qp->ibqp.event_handler(&ev, qp->ibqp.qp_context);
}
return 0;
inval:
spin_unlock(&qp->s_lock);
spin_unlock(&qp->s_hlock);
spin_unlock_irq(&qp->r_lock);
return -EINVAL;
}
/** rvt_free_qpn - Free a qpn from the bit map
* @qpt: QP table
* @qpn: queue pair number to free
*/
static void rvt_free_qpn(struct rvt_qpn_table *qpt, u32 qpn)
{
struct rvt_qpn_map *map;
map = qpt->map + qpn / RVT_BITS_PER_PAGE;
if (map->page)
clear_bit(qpn & RVT_BITS_PER_PAGE_MASK, map->page);
}
/**
* rvt_destroy_qp - destroy a queue pair
* @ibqp: the queue pair to destroy
*
* Note that this can be called while the QP is actively sending or
* receiving!
*
* Return: 0 on success.
*/
int rvt_destroy_qp(struct ib_qp *ibqp)
{
struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
spin_lock_irq(&qp->r_lock);
spin_lock(&qp->s_hlock);
spin_lock(&qp->s_lock);
rvt_reset_qp(rdi, qp, ibqp->qp_type);
spin_unlock(&qp->s_lock);
spin_unlock(&qp->s_hlock);
spin_unlock_irq(&qp->r_lock);
/* qpn is now available for use again */
rvt_free_qpn(&rdi->qp_dev->qpn_table, qp->ibqp.qp_num);
spin_lock(&rdi->n_qps_lock);
rdi->n_qps_allocated--;
if (qp->ibqp.qp_type == IB_QPT_RC) {
rdi->n_rc_qps--;
rdi->busy_jiffies = rdi->n_rc_qps / RC_QP_SCALING_INTERVAL;
}
spin_unlock(&rdi->n_qps_lock);
if (qp->ip)
kref_put(&qp->ip->ref, rvt_release_mmap_info);
else
vfree(qp->r_rq.wq);
vfree(qp->s_wq);
rdi->driver_f.qp_priv_free(rdi, qp);
kfree(qp->s_ack_queue);
kfree(qp);
return 0;
}
/**
* rvt_query_qp - query an ipbq
* @ibqp: IB qp to query
* @attr: attr struct to fill in
* @attr_mask: attr mask ignored
* @init_attr: struct to fill in
*
* Return: always 0
*/
int rvt_query_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr,
int attr_mask, struct ib_qp_init_attr *init_attr)
{
struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
attr->qp_state = qp->state;
attr->cur_qp_state = attr->qp_state;
attr->path_mtu = qp->path_mtu;
attr->path_mig_state = qp->s_mig_state;
attr->qkey = qp->qkey;
attr->rq_psn = qp->r_psn & rdi->dparms.psn_mask;
attr->sq_psn = qp->s_next_psn & rdi->dparms.psn_mask;
attr->dest_qp_num = qp->remote_qpn;
attr->qp_access_flags = qp->qp_access_flags;
attr->cap.max_send_wr = qp->s_size - 1;
attr->cap.max_recv_wr = qp->ibqp.srq ? 0 : qp->r_rq.size - 1;
attr->cap.max_send_sge = qp->s_max_sge;
attr->cap.max_recv_sge = qp->r_rq.max_sge;
attr->cap.max_inline_data = 0;
attr->ah_attr = qp->remote_ah_attr;
attr->alt_ah_attr = qp->alt_ah_attr;
attr->pkey_index = qp->s_pkey_index;
attr->alt_pkey_index = qp->s_alt_pkey_index;
attr->en_sqd_async_notify = 0;
attr->sq_draining = qp->s_draining;
attr->max_rd_atomic = qp->s_max_rd_atomic;
attr->max_dest_rd_atomic = qp->r_max_rd_atomic;
attr->min_rnr_timer = qp->r_min_rnr_timer;
attr->port_num = qp->port_num;
attr->timeout = qp->timeout;
attr->retry_cnt = qp->s_retry_cnt;
attr->rnr_retry = qp->s_rnr_retry_cnt;
attr->alt_port_num = qp->alt_ah_attr.port_num;
attr->alt_timeout = qp->alt_timeout;
init_attr->event_handler = qp->ibqp.event_handler;
init_attr->qp_context = qp->ibqp.qp_context;
init_attr->send_cq = qp->ibqp.send_cq;
init_attr->recv_cq = qp->ibqp.recv_cq;
init_attr->srq = qp->ibqp.srq;
init_attr->cap = attr->cap;
if (qp->s_flags & RVT_S_SIGNAL_REQ_WR)
init_attr->sq_sig_type = IB_SIGNAL_REQ_WR;
else
init_attr->sq_sig_type = IB_SIGNAL_ALL_WR;
init_attr->qp_type = qp->ibqp.qp_type;
init_attr->port_num = qp->port_num;
return 0;
}
/**
* rvt_post_receive - post a receive on a QP
* @ibqp: the QP to post the receive on
* @wr: the WR to post
* @bad_wr: the first bad WR is put here
*
* This may be called from interrupt context.
*
* Return: 0 on success otherwise errno
*/
int rvt_post_recv(struct ib_qp *ibqp, struct ib_recv_wr *wr,
struct ib_recv_wr **bad_wr)
{
struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
struct rvt_rwq *wq = qp->r_rq.wq;
unsigned long flags;
int qp_err_flush = (ib_rvt_state_ops[qp->state] & RVT_FLUSH_RECV) &&
!qp->ibqp.srq;
/* Check that state is OK to post receive. */
if (!(ib_rvt_state_ops[qp->state] & RVT_POST_RECV_OK) || !wq) {
*bad_wr = wr;
return -EINVAL;
}
for (; wr; wr = wr->next) {
struct rvt_rwqe *wqe;
u32 next;
int i;
if ((unsigned)wr->num_sge > qp->r_rq.max_sge) {
*bad_wr = wr;
return -EINVAL;
}
spin_lock_irqsave(&qp->r_rq.lock, flags);
next = wq->head + 1;
if (next >= qp->r_rq.size)
next = 0;
if (next == wq->tail) {
spin_unlock_irqrestore(&qp->r_rq.lock, flags);
*bad_wr = wr;
return -ENOMEM;
}
if (unlikely(qp_err_flush)) {
struct ib_wc wc;
memset(&wc, 0, sizeof(wc));
wc.qp = &qp->ibqp;
wc.opcode = IB_WC_RECV;
wc.wr_id = wr->wr_id;
wc.status = IB_WC_WR_FLUSH_ERR;
rvt_cq_enter(ibcq_to_rvtcq(qp->ibqp.recv_cq), &wc, 1);
} else {
wqe = rvt_get_rwqe_ptr(&qp->r_rq, wq->head);
wqe->wr_id = wr->wr_id;
wqe->num_sge = wr->num_sge;
for (i = 0; i < wr->num_sge; i++)
wqe->sg_list[i] = wr->sg_list[i];
/*
* Make sure queue entry is written
* before the head index.
*/
smp_wmb();
wq->head = next;
}
spin_unlock_irqrestore(&qp->r_rq.lock, flags);
}
return 0;
}
/**
* qp_get_savail - return number of avail send entries
*
* @qp - the qp
*
* This assumes the s_hlock is held but the s_last
* qp variable is uncontrolled.
*/
static inline u32 qp_get_savail(struct rvt_qp *qp)
{
u32 slast;
u32 ret;
smp_read_barrier_depends(); /* see rc.c */
slast = ACCESS_ONCE(qp->s_last);
if (qp->s_head >= slast)
ret = qp->s_size - (qp->s_head - slast);
else
ret = slast - qp->s_head;
return ret - 1;
}
/**
* rvt_post_one_wr - post one RC, UC, or UD send work request
* @qp: the QP to post on
* @wr: the work request to send
*/
static int rvt_post_one_wr(struct rvt_qp *qp,
struct ib_send_wr *wr,
int *call_send)
{
struct rvt_swqe *wqe;
u32 next;
int i;
int j;
int acc;
struct rvt_lkey_table *rkt;
struct rvt_pd *pd;
struct rvt_dev_info *rdi = ib_to_rvt(qp->ibqp.device);
u8 log_pmtu;
int ret;
/* IB spec says that num_sge == 0 is OK. */
if (unlikely(wr->num_sge > qp->s_max_sge))
return -EINVAL;
/*
* Don't allow RDMA reads or atomic operations on UC or
* undefined operations.
* Make sure buffer is large enough to hold the result for atomics.
*/
if (qp->ibqp.qp_type == IB_QPT_UC) {
if ((unsigned)wr->opcode >= IB_WR_RDMA_READ)
return -EINVAL;
} else if (qp->ibqp.qp_type != IB_QPT_RC) {
/* Check IB_QPT_SMI, IB_QPT_GSI, IB_QPT_UD opcode */
if (wr->opcode != IB_WR_SEND &&
wr->opcode != IB_WR_SEND_WITH_IMM)
return -EINVAL;
/* Check UD destination address PD */
if (qp->ibqp.pd != ud_wr(wr)->ah->pd)
return -EINVAL;
} else if ((unsigned)wr->opcode > IB_WR_ATOMIC_FETCH_AND_ADD) {
return -EINVAL;
} else if (wr->opcode >= IB_WR_ATOMIC_CMP_AND_SWP &&
(wr->num_sge == 0 ||
wr->sg_list[0].length < sizeof(u64) ||
wr->sg_list[0].addr & (sizeof(u64) - 1))) {
return -EINVAL;
} else if (wr->opcode >= IB_WR_RDMA_READ && !qp->s_max_rd_atomic) {
return -EINVAL;
}
/* check for avail */
if (unlikely(!qp->s_avail)) {
qp->s_avail = qp_get_savail(qp);
if (WARN_ON(qp->s_avail > (qp->s_size - 1)))
rvt_pr_err(rdi,
"More avail entries than QP RB size.\nQP: %u, size: %u, avail: %u\nhead: %u, tail: %u, cur: %u, acked: %u, last: %u",
qp->ibqp.qp_num, qp->s_size, qp->s_avail,
qp->s_head, qp->s_tail, qp->s_cur,
qp->s_acked, qp->s_last);
if (!qp->s_avail)
return -ENOMEM;
}
next = qp->s_head + 1;
if (next >= qp->s_size)
next = 0;
rkt = &rdi->lkey_table;
pd = ibpd_to_rvtpd(qp->ibqp.pd);
wqe = rvt_get_swqe_ptr(qp, qp->s_head);
if (qp->ibqp.qp_type != IB_QPT_UC &&
qp->ibqp.qp_type != IB_QPT_RC)
memcpy(&wqe->ud_wr, ud_wr(wr), sizeof(wqe->ud_wr));
else if (wr->opcode == IB_WR_RDMA_WRITE_WITH_IMM ||
wr->opcode == IB_WR_RDMA_WRITE ||
wr->opcode == IB_WR_RDMA_READ)
memcpy(&wqe->rdma_wr, rdma_wr(wr), sizeof(wqe->rdma_wr));
else if (wr->opcode == IB_WR_ATOMIC_CMP_AND_SWP ||
wr->opcode == IB_WR_ATOMIC_FETCH_AND_ADD)
memcpy(&wqe->atomic_wr, atomic_wr(wr), sizeof(wqe->atomic_wr));
else
memcpy(&wqe->wr, wr, sizeof(wqe->wr));
wqe->length = 0;
j = 0;
if (wr->num_sge) {
acc = wr->opcode >= IB_WR_RDMA_READ ?
IB_ACCESS_LOCAL_WRITE : 0;
for (i = 0; i < wr->num_sge; i++) {
u32 length = wr->sg_list[i].length;
int ok;
if (length == 0)
continue;
ok = rvt_lkey_ok(rkt, pd, &wqe->sg_list[j],
&wr->sg_list[i], acc);
if (!ok) {
ret = -EINVAL;
goto bail_inval_free;
}
wqe->length += length;
j++;
}
wqe->wr.num_sge = j;
}
/* general part of wqe valid - allow for driver checks */
if (rdi->driver_f.check_send_wqe) {
ret = rdi->driver_f.check_send_wqe(qp, wqe);
if (ret < 0)
goto bail_inval_free;
if (ret)
*call_send = ret;
}
log_pmtu = qp->log_pmtu;
if (qp->ibqp.qp_type != IB_QPT_UC &&
qp->ibqp.qp_type != IB_QPT_RC) {
struct rvt_ah *ah = ibah_to_rvtah(wqe->ud_wr.ah);
log_pmtu = ah->log_pmtu;
atomic_inc(&ibah_to_rvtah(ud_wr(wr)->ah)->refcount);
}
wqe->ssn = qp->s_ssn++;
wqe->psn = qp->s_next_psn;
wqe->lpsn = wqe->psn +
(wqe->length ? ((wqe->length - 1) >> log_pmtu) : 0);
qp->s_next_psn = wqe->lpsn + 1;
trace_rvt_post_one_wr(qp, wqe);
smp_wmb(); /* see request builders */
qp->s_avail--;
qp->s_head = next;
return 0;
bail_inval_free:
/* release mr holds */
while (j) {
struct rvt_sge *sge = &wqe->sg_list[--j];
rvt_put_mr(sge->mr);
}
return ret;
}
/**
* rvt_post_send - post a send on a QP
* @ibqp: the QP to post the send on
* @wr: the list of work requests to post
* @bad_wr: the first bad WR is put here
*
* This may be called from interrupt context.
*
* Return: 0 on success else errno
*/
int rvt_post_send(struct ib_qp *ibqp, struct ib_send_wr *wr,
struct ib_send_wr **bad_wr)
{
struct rvt_qp *qp = ibqp_to_rvtqp(ibqp);
struct rvt_dev_info *rdi = ib_to_rvt(ibqp->device);
unsigned long flags = 0;
int call_send;
unsigned nreq = 0;
int err = 0;
spin_lock_irqsave(&qp->s_hlock, flags);
/*
* Ensure QP state is such that we can send. If not bail out early,
* there is no need to do this every time we post a send.
*/
if (unlikely(!(ib_rvt_state_ops[qp->state] & RVT_POST_SEND_OK))) {
spin_unlock_irqrestore(&qp->s_hlock, flags);
return -EINVAL;
}
/*
* If the send queue is empty, and we only have a single WR then just go
* ahead and kick the send engine into gear. Otherwise we will always
* just schedule the send to happen later.
*/
call_send = qp->s_head == ACCESS_ONCE(qp->s_last) && !wr->next;
for (; wr; wr = wr->next) {
err = rvt_post_one_wr(qp, wr, &call_send);
if (unlikely(err)) {
*bad_wr = wr;
goto bail;
}
nreq++;
}
bail:
spin_unlock_irqrestore(&qp->s_hlock, flags);
if (nreq) {
if (call_send)
rdi->driver_f.do_send(qp);
else
rdi->driver_f.schedule_send_no_lock(qp);
}
return err;
}
/**
* rvt_post_srq_receive - post a receive on a shared receive queue
* @ibsrq: the SRQ to post the receive on
* @wr: the list of work requests to post
* @bad_wr: A pointer to the first WR to cause a problem is put here
*
* This may be called from interrupt context.
*
* Return: 0 on success else errno
*/
int rvt_post_srq_recv(struct ib_srq *ibsrq, struct ib_recv_wr *wr,
struct ib_recv_wr **bad_wr)
{
struct rvt_srq *srq = ibsrq_to_rvtsrq(ibsrq);
struct rvt_rwq *wq;
unsigned long flags;
for (; wr; wr = wr->next) {
struct rvt_rwqe *wqe;
u32 next;
int i;
if ((unsigned)wr->num_sge > srq->rq.max_sge) {
*bad_wr = wr;
return -EINVAL;
}
spin_lock_irqsave(&srq->rq.lock, flags);
wq = srq->rq.wq;
next = wq->head + 1;
if (next >= srq->rq.size)
next = 0;
if (next == wq->tail) {
spin_unlock_irqrestore(&srq->rq.lock, flags);
*bad_wr = wr;
return -ENOMEM;
}
wqe = rvt_get_rwqe_ptr(&srq->rq, wq->head);
wqe->wr_id = wr->wr_id;
wqe->num_sge = wr->num_sge;
for (i = 0; i < wr->num_sge; i++)
wqe->sg_list[i] = wr->sg_list[i];
/* Make sure queue entry is written before the head index. */
smp_wmb();
wq->head = next;
spin_unlock_irqrestore(&srq->rq.lock, flags);
}
return 0;
}
| gpl-2.0 |
NicoleRobin/glibc | sysdeps/alpha/soft-fp/ots_nintxq.c | 1608 | /* Software floating-point emulation: convert to fortran nearest.
Copyright (C) 1997-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Richard Henderson ([email protected]) and
Jakub Jelinek ([email protected]).
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library. If not, see
<http://www.gnu.org/licenses/>. */
#include "local-soft-fp.h"
long
_OtsNintXQ (long al, long ah, long _round)
{
FP_DECL_EX;
FP_DECL_Q(A); FP_DECL_Q(B); FP_DECL_Q(C);
unsigned long r;
long s;
/* If bit 3 is set, then integer overflow detection is requested. */
s = _round & 8 ? 1 : -1;
_round = _round & 3;
FP_INIT_ROUNDMODE;
AXP_UNPACK_SEMIRAW_Q(A, a);
/* Build 0.5 * sign(A) */
B_e = _FP_EXPBIAS_Q;
__FP_FRAC_SET_2 (B, 0, 0);
B_s = A_s;
FP_ADD_Q(C, A, B);
_FP_FRAC_SRL_2(C, _FP_WORKBITS);
_FP_FRAC_HIGH_RAW_Q(C) &= ~(_FP_W_TYPE)_FP_IMPLBIT_Q;
FP_TO_INT_Q(r, C, 64, s);
if (s > 0 && (_fex &= FP_EX_INVALID))
FP_HANDLE_EXCEPTIONS;
return r;
}
| gpl-2.0 |
ryanpeng84/HermitLibrary | doc/index-files/index-11.html | 7522 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Sat Jun 26 10:05:24 PDT 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
K-Index
</TITLE>
<META NAME="date" CONTENT="2010-06-26">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="K-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-10.html"><B>PREV LETTER</B></A>
<A HREF="index-12.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-11.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-11.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <A HREF="index-24.html">Y</A> <A HREF="index-25.html">Z</A> <A HREF="index-26.html">Ε</A> <A HREF="index-27.html">Θ</A> <HR>
<A NAME="_K_"><!-- --></A><H2>
<B>K</B></H2>
<DL>
<DT><A HREF="../org/hermit/geometry/cluster/KMeansClusterer.html" title="class in org.hermit.geometry.cluster"><B>KMeansClusterer</B></A> - Class in <A HREF="../org/hermit/geometry/cluster/package-summary.html">org.hermit.geometry.cluster</A><DD>An implementation of Lloyd's k-clusterMeans clustering algorithm.<DT><A HREF="../org/hermit/geometry/cluster/KMeansClusterer.html#KMeansClusterer()"><B>KMeansClusterer()</B></A> -
Constructor for class org.hermit.geometry.cluster.<A HREF="../org/hermit/geometry/cluster/KMeansClusterer.html" title="class in org.hermit.geometry.cluster">KMeansClusterer</A>
<DD>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-10.html"><B>PREV LETTER</B></A>
<A HREF="index-12.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-11.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-11.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">R</A> <A HREF="index-18.html">S</A> <A HREF="index-19.html">T</A> <A HREF="index-20.html">U</A> <A HREF="index-21.html">V</A> <A HREF="index-22.html">W</A> <A HREF="index-23.html">X</A> <A HREF="index-24.html">Y</A> <A HREF="index-25.html">Z</A> <A HREF="index-26.html">Ε</A> <A HREF="index-27.html">Θ</A> <HR>
</BODY>
</HTML>
| gpl-2.0 |
jumpcakes/plunkett | wp-content/themes/genesis-sample/assets/js/bower_components/vue/src/observer/index.js | 4867 | var _ = require('../util')
var config = require('../config')
var Dep = require('./dep')
var arrayMethods = require('./array')
var arrayKeys = Object.getOwnPropertyNames(arrayMethods)
require('./object')
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*
* @param {Array|Object} value
* @constructor
*/
function Observer (value) {
this.value = value
this.active = true
this.deps = []
_.define(value, '__ob__', this)
if (_.isArray(value)) {
var augment = config.proto && _.hasProto
? protoAugment
: copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
this.walk(value)
}
}
// Static methods
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*
* @param {*} value
* @param {Vue} [vm]
* @return {Observer|undefined}
* @static
*/
Observer.create = function (value, vm) {
var ob
if (
value &&
value.hasOwnProperty('__ob__') &&
value.__ob__ instanceof Observer
) {
ob = value.__ob__
} else if (
_.isObject(value) &&
!Object.isFrozen(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (ob && vm) {
ob.addVm(vm)
}
return ob
}
/**
* Set the target watcher that is currently being evaluated.
*
* @param {Watcher} watcher
*/
Observer.setTarget = function (watcher) {
Dep.target = watcher
}
// Instance methods
var p = Observer.prototype
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object. Properties prefixed with `$` or `_`
* and accessor properties are ignored.
*
* @param {Object} obj
*/
p.walk = function (obj) {
var keys = Object.keys(obj)
var i = keys.length
var key, prefix
while (i--) {
key = keys[i]
prefix = key.charCodeAt(0)
if (prefix !== 0x24 && prefix !== 0x5F) { // skip $ or _
this.convert(key, obj[key])
}
}
}
/**
* Try to carete an observer for a child value,
* and if value is array, link dep to the array.
*
* @param {*} val
* @return {Dep|undefined}
*/
p.observe = function (val) {
return Observer.create(val)
}
/**
* Observe a list of Array items.
*
* @param {Array} items
*/
p.observeArray = function (items) {
var i = items.length
while (i--) {
this.observe(items[i])
}
}
/**
* Convert a property into getter/setter so we can emit
* the events when the property is accessed/changed.
*
* @param {String} key
* @param {*} val
*/
p.convert = function (key, val) {
var ob = this
var childOb = ob.observe(val)
var dep = new Dep()
if (childOb) {
childOb.deps.push(dep)
}
Object.defineProperty(ob.value, key, {
enumerable: true,
configurable: true,
get: function () {
if (ob.active) {
dep.depend()
}
return val
},
set: function (newVal) {
if (newVal === val) return
// remove dep from old value
var oldChildOb = val && val.__ob__
if (oldChildOb) {
oldChildOb.deps.$remove(dep)
}
val = newVal
// add dep to new value
var newChildOb = ob.observe(newVal)
if (newChildOb) {
newChildOb.deps.push(dep)
}
dep.notify()
}
})
}
/**
* Notify change on all self deps on an observer.
* This is called when a mutable value mutates. e.g.
* when an Array's mutating methods are called, or an
* Object's $add/$delete are called.
*/
p.notify = function () {
var deps = this.deps
for (var i = 0, l = deps.length; i < l; i++) {
deps[i].notify()
}
}
/**
* Add an owner vm, so that when $add/$delete mutations
* happen we can notify owner vms to proxy the keys and
* digest the watchers. This is only called when the object
* is observed as an instance's root $data.
*
* @param {Vue} vm
*/
p.addVm = function (vm) {
(this.vms || (this.vms = [])).push(vm)
}
/**
* Remove an owner vm. This is called when the object is
* swapped out as an instance's $data object.
*
* @param {Vue} vm
*/
p.removeVm = function (vm) {
this.vms.$remove(vm)
}
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*
* @param {Object|Array} target
* @param {Object} proto
*/
function protoAugment (target, src) {
target.__proto__ = src
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*
* @param {Object|Array} target
* @param {Object} proto
*/
function copyAugment (target, src, keys) {
var i = keys.length
var key
while (i--) {
key = keys[i]
_.define(target, key, src[key])
}
}
module.exports = Observer
| gpl-2.0 |
WellDone/gpsim | src/src/p12f6xx.cc | 16139 | /*
Copyright (C) 2009 Roy R. Rankin
This file is part of the libgpsim library of gpsim
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see
<http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
//
// p12f6xx
//
// This file supports:
// PIC12F629
// PIC12F675
// PIC12F683
//
//Note: unlike most other 12F processors these have 14bit instructions
#include <stdio.h>
#include <iostream>
#include <string>
#include "../config.h"
#include "symbol.h"
#include "stimuli.h"
#include "eeprom.h"
#include "p12f6xx.h"
#include "pic-ioports.h"
#include "packages.h"
//#define DEBUG
#if defined(DEBUG)
#include "../config.h"
#define Dprintf(arg) {printf("%s:%d ",__FILE__,__LINE__); printf arg; }
#else
#define Dprintf(arg) {}
#endif
//========================================================================
//
// Configuration Memory for the 12F6XX devices.
class Config12F6 : public ConfigWord
{
public:
Config12F6(P12F629 *pCpu)
: ConfigWord("CONFIG12F6", 0x3fff, "Configuration Word", pCpu, 0x2007)
{
Dprintf(("Config12F6::Config12F6 %p\n", m_pCpu));
if (m_pCpu)
{
m_pCpu->set_config_word(0x2007, 0x3fff);
}
}
};
// Does not match any of 3 versions in pir.h, pir.cc
// If required by any other porcessors should be moved there
//
class PIR1v12f : public PIR
{
public:
enum {
TMR1IF = 1 << 0,
TMR2IF = 1 << 1, //For 12F683
CMIF = 1 << 3,
ADIF = 1 << 6,
EEIF = 1 << 7
};
//------------------------------------------------------------------------
PIR1v12f(Processor *pCpu, const char *pName, const char *pDesc,INTCON *_intcon, PIE *_pie)
: PIR(pCpu,pName,pDesc,_intcon, _pie,0)
{
valid_bits = TMR1IF | CMIF | ADIF | EEIF;
writable_bits = TMR1IF | CMIF | ADIF | EEIF;
}
virtual void set_tmr1if()
{
put(get() | TMR1IF);
}
virtual void set_tmr2if()
{
put(get() | TMR2IF);
}
virtual void set_cmif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | CMIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_c1if()
{
set_cmif();
}
virtual void set_eeif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | EEIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
virtual void set_adif()
{
trace.raw(write_trace.get() | value.get());
value.put(value.get() | ADIF);
if( value.get() & pie->value.get() )
setPeripheralInterrupt();
}
};
//========================================================================
void P12F629::create_config_memory()
{
m_configMemory = new ConfigMemory(this,1);
m_configMemory->addConfigWord(0,new Config12F6(this));
};
class MCLRPinMonitor;
bool P12F629::set_config_word(unsigned int address,unsigned int cfg_word)
{
enum {
FOSC0 = 1<<0,
FOSC1 = 1<<1,
FOSC2 = 1<<2,
WDTEN = 1<<3,
PWRTEN = 1<<4,
MCLRE = 1<<5,
BOREN = 1<<6,
CP = 1<<7,
CPD = 1<<8,
BG0 = 1<<12,
BG1 = 1<<13
};
if(address == config_word_address())
{
if ((cfg_word & MCLRE) == MCLRE)
assignMCLRPin(4); // package pin 4
else
unassignMCLRPin();
wdt.initialize((cfg_word & WDTEN) == WDTEN);
if ((cfg_word & (FOSC2 | FOSC1 )) == 0x04) // internal RC OSC
osccal.set_freq(4e6);
return(_14bit_processor::set_config_word(address, cfg_word));
}
return false;
}
P12F629::P12F629(const char *_name, const char *desc)
: _14bit_processor(_name,desc),
intcon_reg(this,"intcon","Interrupt Control"),
comparator(this),
pie1(this,"PIE1", "Peripheral Interrupt Enable"),
t1con(this, "t1con", "TMR1 Control"),
tmr1l(this, "tmr1l", "TMR1 Low"),
tmr1h(this, "tmr1h", "TMR1 High"),
pcon(this, "pcon", "pcon"),
osccal(this, "osccal", "Oscillator Calibration Register", 0xfc)
{
m_ioc = new IOC(this, "ioc", "Interrupt-On-Change GPIO Register");
m_gpio = new PicPortGRegister(this,"gpio","", &intcon_reg, m_ioc,8,0x3f);
m_trisio = new PicTrisRegister(this,"trisio","", m_gpio, false);
m_wpu = new WPU(this, "wpu", "Weak Pull-up Register", m_gpio, 0x37);
pir1 = new PIR1v12f(this,"pir1","Peripheral Interrupt Register",&intcon_reg, &pie1);
tmr0.set_cpu(this, m_gpio, 4, option_reg);
tmr0.start(0);
if(config_modes)
config_modes->valid_bits = ConfigMode::CM_FOSC0 | ConfigMode::CM_FOSC1 |
ConfigMode::CM_FOSC1x | ConfigMode::CM_WDTE | ConfigMode::CM_PWRTE;
}
P12F629::~P12F629()
{
delete_file_registers(0x20, ram_top);
remove_sfr_register(&tmr0);
remove_sfr_register(&tmr1l);
remove_sfr_register(&tmr1h);
remove_sfr_register(&pcon);
remove_sfr_register(&t1con);
remove_sfr_register(&intcon_reg);
remove_sfr_register(&pie1);
remove_sfr_register(&comparator.cmcon);
remove_sfr_register(&comparator.vrcon);
remove_sfr_register(get_eeprom()->get_reg_eedata());
remove_sfr_register(get_eeprom()->get_reg_eeadr());
remove_sfr_register(get_eeprom()->get_reg_eecon1());
remove_sfr_register(get_eeprom()->get_reg_eecon2());
remove_sfr_register(&osccal);
delete_sfr_register(m_gpio);
delete_sfr_register(m_trisio);
delete_sfr_register(m_wpu);
delete_sfr_register(m_ioc);
delete_sfr_register(pir1);
delete e;
}
Processor * P12F629::construct(const char *name)
{
P12F629 *p = new P12F629(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
void P12F629::create_symbols()
{
pic_processor::create_symbols();
addSymbol(Wreg);
}
void P12F629::create_sfr_map()
{
pir_set_def.set_pir1(pir1);
add_sfr_register(indf, 0x00);
alias_file_registers(0x00,0x00,0x80);
add_sfr_register(&tmr0, 0x01, RegisterValue(0xff,0));
add_sfr_register(option_reg, 0x81, RegisterValue(0xff,0));
add_sfr_register(pcl, 0x02, RegisterValue(0,0));
add_sfr_register(status, 0x03, RegisterValue(0x18,0));
add_sfr_register(fsr, 0x04);
alias_file_registers(0x02,0x04,0x80);
add_sfr_register(&tmr1l, 0x0e, RegisterValue(0,0),"tmr1l");
add_sfr_register(&tmr1h, 0x0f, RegisterValue(0,0),"tmr1h");
add_sfr_register(&pcon, 0x8e, RegisterValue(0,0),"pcon");
add_sfr_register(&t1con, 0x10, RegisterValue(0,0));
add_sfr_register(m_gpio, 0x05);
add_sfr_register(m_trisio, 0x85, RegisterValue(0x3f,0));
add_sfr_register(pclath, 0x0a, RegisterValue(0,0));
add_sfr_register(&intcon_reg, 0x0b, RegisterValue(0,0));
alias_file_registers(0x0a,0x0b,0x80);
intcon = &intcon_reg;
intcon_reg.set_pir_set(get_pir_set());
add_sfr_register(pir1, 0x0c, RegisterValue(0,0),"pir1");
tmr1l.tmrh = &tmr1h;
tmr1l.t1con = &t1con;
tmr1l.setInterruptSource(new InterruptSource(pir1, PIR1v1::TMR1IF));
tmr1h.tmrl = &tmr1l;
t1con.tmrl = &tmr1l;
tmr1l.setIOpin(&(*m_gpio)[5]);
tmr1l.setGatepin(&(*m_gpio)[4]);
add_sfr_register(&pie1, 0x8c, RegisterValue(0,0));
if (pir1) {
pir1->set_intcon(&intcon_reg);
pir1->set_pie(&pie1);
}
pie1.setPir(pir1);
// Link the comparator and voltage ref to porta
comparator.initialize(get_pir_set(), NULL,
&(*m_gpio)[0], &(*m_gpio)[1],
NULL, NULL,
&(*m_gpio)[2], NULL);
comparator.cmcon.set_configuration(1, 0, AN0, AN1, AN0, AN1, ZERO);
comparator.cmcon.set_configuration(1, 1, AN0, AN1, AN0, AN1, OUT0);
comparator.cmcon.set_configuration(1, 2, AN0, AN1, AN0, AN1, NO_OUT);
comparator.cmcon.set_configuration(1, 3, AN1, VREF, AN1, VREF, OUT0);
comparator.cmcon.set_configuration(1, 4, AN1, VREF, AN1, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 5, AN1, VREF, AN0, VREF, OUT0);
comparator.cmcon.set_configuration(1, 6, AN1, VREF, AN0, VREF, NO_OUT);
comparator.cmcon.set_configuration(1, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 0, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 1, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 2, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 3, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 4, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 5, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 6, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
comparator.cmcon.set_configuration(2, 7, NO_IN, NO_IN, NO_IN, NO_IN, ZERO);
add_sfr_register(&comparator.cmcon, 0x19, RegisterValue(0,0),"cmcon");
add_sfr_register(&comparator.vrcon, 0x99, RegisterValue(0,0),"cvrcon");
add_sfr_register(get_eeprom()->get_reg_eedata(), 0x9a);
add_sfr_register(get_eeprom()->get_reg_eeadr(), 0x9b);
add_sfr_register(get_eeprom()->get_reg_eecon1(), 0x9c, RegisterValue(0,0));
add_sfr_register(get_eeprom()->get_reg_eecon2(), 0x9d);
add_sfr_register(m_wpu, 0x95, RegisterValue(0x37,0),"wpu");
add_sfr_register(m_ioc, 0x96, RegisterValue(0,0),"ioc");
add_sfr_register(&osccal, 0x90, RegisterValue(0x80,0));
}
//-------------------------------------------------------------------
void P12F629::set_out_of_range_pm(unsigned int address, unsigned int value)
{
if( (address>= 0x2100) && (address < 0x2100 + get_eeprom()->get_rom_size()))
get_eeprom()->change_rom(address - 0x2100, value);
}
void P12F629::create_iopin_map()
{
package = new Package(8);
if(!package)
return;
// Now Create the package and place the I/O pins
package->assign_pin( 7, m_gpio->addPin(new IO_bi_directional_pu("gpio0"),0));
package->assign_pin( 6, m_gpio->addPin(new IO_bi_directional_pu("gpio1"),1));
package->assign_pin( 5, m_gpio->addPin(new IO_bi_directional_pu("gpio2"),2));
package->assign_pin( 4, m_gpio->addPin(new IOPIN("gpio3"),3));
package->assign_pin( 3, m_gpio->addPin(new IO_bi_directional_pu("gpio4"),4));
package->assign_pin( 2, m_gpio->addPin(new IO_bi_directional_pu("gpio5"),5));
package->assign_pin( 1, 0);
package->assign_pin( 8, 0);
}
void P12F629::create(int _ram_top, int eeprom_size)
{
ram_top = _ram_top;
create_iopin_map();
_14bit_processor::create();
e = new EEPROM_PIR(this, pir1);
e->initialize(eeprom_size);
e->set_intcon(&intcon_reg);
set_eeprom(e);
add_file_registers(0x20, ram_top, 0x80);
P12F629::create_sfr_map();
}
//-------------------------------------------------------------------
void P12F629::enter_sleep()
{
tmr1l.sleep();
_14bit_processor::enter_sleep();
}
//-------------------------------------------------------------------
void P12F629::exit_sleep()
{
tmr1l.wake();
_14bit_processor::exit_sleep();
}
//-------------------------------------------------------------------
void P12F629::option_new_bits_6_7(unsigned int bits)
{
Dprintf(("P12F629::option_new_bits_6_7 bits=%x\n", bits));
m_gpio->setIntEdge ( (bits & OPTION_REG::BIT6) == OPTION_REG::BIT6);
m_wpu->set_wpu_pu ( (bits & OPTION_REG::BIT7) != OPTION_REG::BIT7);
}
//========================================================================
//
// Pic 16F675
//
Processor * P12F675::construct(const char *name)
{
P12F675 *p = new P12F675(name);
p->create(0x5f, 128);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F675::P12F675(const char *_name, const char *desc)
: P12F629(_name,desc),
ansel(this,"ansel", "Analog Select"),
adcon0(this,"adcon0", "A2D Control 0"),
adcon1(this,"adcon1", "A2D Control 1"),
adresh(this,"adresh", "A2D Result High"),
adresl(this,"adresl", "A2D Result Low")
{
}
P12F675::~P12F675()
{
remove_sfr_register(&adresl);
remove_sfr_register(&adresh);
remove_sfr_register(&adcon0);
remove_sfr_register(&ansel);
}
void P12F675::create(int ram_top, int eeprom_size)
{
P12F629::create(ram_top, eeprom_size);
create_sfr_map();
}
void P12F675::create_sfr_map()
{
//
// adcon1 is not a register on the 12f675, but it is used internally
// to perform the ADC conversions
//
add_sfr_register(&adresl, 0x9e, RegisterValue(0,0));
add_sfr_register(&adresh, 0x1e, RegisterValue(0,0));
add_sfr_register(&adcon0, 0x1f, RegisterValue(0,0));
add_sfr_register(&ansel, 0x9f, RegisterValue(0x0f,0));
ansel.setAdcon1(&adcon1);
ansel.setAdcon0(&adcon0);
adcon0.setAdresLow(&adresl);
adcon0.setAdres(&adresh);
adcon0.setAdcon1(&adcon1);
adcon0.setIntcon(&intcon_reg);
adcon0.setA2DBits(10);
adcon0.setPir(pir1);
adcon0.setChannel_Mask(3);
adcon0.setChannel_shift(2);
adcon1.setNumberOfChannels(4);
adcon1.setIOPin(0, &(*m_gpio)[0]);
adcon1.setIOPin(1, &(*m_gpio)[1]);
adcon1.setIOPin(2, &(*m_gpio)[2]);
adcon1.setIOPin(3, &(*m_gpio)[4]);
adcon1.setVrefHiConfiguration(2, 1);
/* Channel Configuration done dynamiclly based on ansel */
adcon1.setValidCfgBits(ADCON1::VCFG0 | ADCON1::VCFG1 , 4);
}
//========================================================================
//
// Pic 16F683
//
Processor * P12F683::construct(const char *name)
{
P12F683 *p = new P12F683(name);
p->create(0x7f, 256);
p->create_invalid_registers ();
p->create_symbols();
return p;
}
P12F683::P12F683(const char *_name, const char *desc)
: P12F675(_name,desc),
t2con(this, "t2con", "TMR2 Control"),
pr2(this, "pr2", "TMR2 Period Register"),
tmr2(this, "tmr2", "TMR2 Register"),
ccp1con(this, "ccp1con", "Capture Compare Control"),
ccpr1l(this, "ccpr1l", "Capture Compare 1 Low"),
ccpr1h(this, "ccpr1h", "Capture Compare 1 High"),
wdtcon(this, "wdtcon", "WDT Control", 0x1f),
osccon(this, "osccon", "OSC Control"),
osctune(this, "osctune", "OSC Tune")
{
internal_osc = false;
pir1->valid_bits |= PIR1v12f::TMR2IF;
pir1->writable_bits |= PIR1v12f::TMR2IF;
}
P12F683::~P12F683()
{
delete_file_registers(0x20, 0x7f);
delete_file_registers(0xa0, 0xbf);
remove_sfr_register(&tmr2);
remove_sfr_register(&t2con);
remove_sfr_register(&pr2);
remove_sfr_register(&ccpr1l);
remove_sfr_register(&ccpr1h);
remove_sfr_register(&ccp1con);
remove_sfr_register(&wdtcon);
remove_sfr_register(&osccon);
remove_sfr_register(&osctune);
remove_sfr_register(&comparator.cmcon1);
}
void P12F683::create(int _ram_top, int eeprom_size)
{
P12F629::create(0, eeprom_size);
add_file_registers(0x20, 0x6f, 0);
add_file_registers(0xa0, 0xbf, 0);
add_file_registers(0x70, 0x7f, 0x80);
create_sfr_map();
}
void P12F683::create_sfr_map()
{
P12F675::create_sfr_map();
add_sfr_register(&tmr2, 0x11, RegisterValue(0,0));
add_sfr_register(&t2con, 0x12, RegisterValue(0,0));
add_sfr_register(&pr2, 0x92, RegisterValue(0xff,0));
add_sfr_register(&ccpr1l, 0x13, RegisterValue(0,0));
add_sfr_register(&ccpr1h, 0x14, RegisterValue(0,0));
add_sfr_register(&ccp1con, 0x15, RegisterValue(0,0));
add_sfr_register(&wdtcon, 0x18, RegisterValue(0x08,0),"wdtcon");
add_sfr_register(&osccon, 0x8f, RegisterValue(0,0),"osccon");
remove_sfr_register(&osccal);
add_sfr_register(&osctune, 0x90, RegisterValue(0,0),"osctune");
osccon.set_osctune(&osctune);
osctune.set_osccon(&osccon);
t2con.tmr2 = &tmr2;
tmr2.pir_set = get_pir_set();
tmr2.pr2 = &pr2;
tmr2.t2con = &t2con;
tmr2.add_ccp ( &ccp1con );
pr2.tmr2 = &tmr2;
ccp1con.setCrosslinks(&ccpr1l, pir1, PIR1v1::CCP1IF, &tmr2);
ccp1con.setIOpin(&((*m_gpio)[2]));
ccpr1l.ccprh = &ccpr1h;
ccpr1l.tmrl = &tmr1l;
ccpr1h.ccprl = &ccpr1l;
comparator.cmcon.new_name("cmcon0");
comparator.cmcon.set_tmrl(&tmr1l);
comparator.cmcon1.set_tmrl(&tmr1l);
add_sfr_register(&comparator.cmcon1, 0x1a, RegisterValue(2,0),"cmcon1");
wdt.set_timeout(1./31000.);
}
| gpl-2.0 |
abirjepatil/iOS | config/module-lite.sh | 15079 | #! /usr/bin/env bash
#--------------------
# Standard options:
export COMMON_FF_CFG_FLAGS=
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --prefix=PREFIX"
# Licensing options:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-gpl"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-version3"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-nonfree"
# Configuration options:
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-static"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-shared"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-small"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-runtime-cpudetect"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-gray"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-swscale-alpha"
# Program options:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-programs"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-ffmpeg"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-ffplay"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-ffprobe"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-ffserver"
# Documentation options:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-doc"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-htmlpages"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-manpages"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-podpages"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-txtpages"
# Component options:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-avdevice"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-avcodec"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-avformat"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-avutil"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-swresample"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-swscale"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-postproc"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-avfilter"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-avresample"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-pthreads"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-w32threads"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-os2threads"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-network"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-dct"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-dwt"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-lsp"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-lzo"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mdct"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-rdft"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-fft"
# Hardware accelerators:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-dxva2"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-vaapi"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-vda"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-vdpau"
# Individual component options:
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-everything"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-encoders"
# ./configure --list-decoders
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-decoders"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=aac"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=aac_latm"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=ac3"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=flv"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=h263"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=h263i"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=h263p"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=h264"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=mp3*"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vc1"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vorbis"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vp6"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vp6a"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vp6f"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=vp8"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-decoder=webp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-hwaccels"
# ./configure --list-muxers
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-muxers"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-muxer=mpegts"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-muxer=mp4"
# ./configure --list-demuxers
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-demuxers"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=aac"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=ac3"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=concat"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=data"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=flv"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=hls"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=latm"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=live_flv"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=loas"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=m4v"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=mov"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=mp3"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=mpegps"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=mpegts"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-demuxer=mpegvideo"
# ./configure --list-parsers
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-parsers"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=aac"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=aac_latm"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=ac3"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=h263"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=h264"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=vc1"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=vorbis"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=vp8"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-parser=vp9"
# ./configure --list-bsf
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-bsfs"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-bsf=mjpeg2jpeg"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-bsf=mjpeg2jpeg"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-bsf=mjpega_dump_header"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-bsf=mov2textsub"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-bsf=text2movsub"
# ./configure --list-protocols
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-protocols"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=bluray"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=ffrtmpcrypt"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-protocol=ffrtmphttp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=gopher"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=librtmp*"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=libssh"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=mmsh"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=mmst"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=pipe"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=rtmp*"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-protocol=rtmp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-protocol=rtmpt"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=rtp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=sctp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=srtp"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-protocol=unix"
#
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-devices"
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-filters"
# External library support:
export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-iconv"
# ...
# Advanced options (experts only):
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --cross-prefix=${FF_CROSS_PREFIX}-"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-cross-compile"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --sysroot=PATH"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --sysinclude=PATH"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --target-os=TAGET_OS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --target-exec=CMD"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --target-path=DIR"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --toolchain=NAME"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --nm=NM"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --ar=AR"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --as=AS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --yasmexe=EXE"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --cc=CC"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --cxx=CXX"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --dep-cc=DEPCC"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --ld=LD"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-cc=HOSTCC"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-cflags=HCFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-cppflags=HCPPFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-ld=HOSTLD"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-ldflags=HLDFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-libs=HLIBS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --host-os=OS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --extra-cflags=ECFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --extra-cxxflags=ECFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --extra-ldflags=ELDFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --extra-libs=ELIBS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --extra-version=STRING"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --optflags=OPTFLAGS"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --build-suffix=SUFFIX"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --malloc-prefix=PREFIX"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --progs-suffix=SUFFIX"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --arch=ARCH"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --cpu=CPU"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-pic"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-sram"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-thumb"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-symver"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-hardcoded-tables"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-safe-bitstream-reader"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-memalign-hack"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-lto"
# Optimization options (experts only):
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-asm"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-altivec"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-amd3dnow"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-amd3dnowext"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mmx"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mmxext"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-sse"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-sse2"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-sse3"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-ssse3"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-sse4"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-sse42"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-avx"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-fma4"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-armv5te"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-armv6"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-armv6t2"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-vfp"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-neon"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-vis"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-inline-asm"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-yasm"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mips32r2"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mipsdspr1"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mipsdspr2"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-mipsfpu"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-fast-unaligned"
# Developer options (useful when working on FFmpeg itself):
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-coverage"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-debug"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-debug=LEVEL"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-optimizations"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-extra-warnings"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-stripping"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --assert-level=level"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-memory-poisoning"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --valgrind=VALGRIND"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-ftrapv"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --samples=PATH"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-xmm-clobber-test"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-random"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-random"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --enable-random=LIST"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --disable-random=LIST"
# export COMMON_FF_CFG_FLAGS="$COMMON_FF_CFG_FLAGS --random-seed=VALUE"
| gpl-2.0 |
ohtacky/ECCUBE3 | src/Eccube/Controller/BlockController.php | 1549 | <?php
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
namespace Eccube\Controller;
use Eccube\Application;
use Eccube\Entity\BlocPosition;
class BlockController
{
public function index(Application $app)
{
$position = $app['request']->get('position');
$blocks = array();
if ($app['eccube.layout']) {
foreach ($app['eccube.layout']->getBlocPositions() as $blocPositions) {
if ($blocPositions->getTargetId() == constant("Eccube\Entity\BlocPosition::" . $position)) {
$blocks[] = $blocPositions->getBloc();
}
}
}
return $app['twig']->render('block.twig', array(
'blocks' => $blocks,
));
}
}
| gpl-2.0 |
dakcarto/QGIS | src/core/raster/qgsrasterrendererregistry.h | 3450 | /***************************************************************************
qgsrasterrendererregistry.h
---------------------------
begin : January 2012
copyright : (C) 2012 by Marco Hugentobler
email : marco at sourcepole dot ch
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef QGSRASTERRENDERERREGISTRY_H
#define QGSRASTERRENDERERREGISTRY_H
#include "qgsrasterlayer.h" //for DrawingStyle enum
#include <QHash>
#include <QString>
class QDomElement;
class QgsRasterInterface;
class QgsRasterLayer;
class QgsRasterRenderer;
class QgsRasterRendererWidget;
typedef QgsRasterRenderer*( *QgsRasterRendererCreateFunc )( const QDomElement&, QgsRasterInterface* input );
typedef QgsRasterRendererWidget*( *QgsRasterRendererWidgetCreateFunc )( QgsRasterLayer*, const QgsRectangle &extent );
/** \ingroup core
* Registry for raster renderer entries.
*/
struct CORE_EXPORT QgsRasterRendererRegistryEntry
{
QgsRasterRendererRegistryEntry( const QString& theName, const QString& theVisibleName, QgsRasterRendererCreateFunc rendererFunction,
QgsRasterRendererWidgetCreateFunc widgetFunction );
QgsRasterRendererRegistryEntry();
QString name;
QString visibleName; //visible (and translatable) name
QgsRasterRendererCreateFunc rendererCreateFunction; //pointer to create function
QgsRasterRendererWidgetCreateFunc widgetCreateFunction; //pointer to create function for renderer widget
};
/** \ingroup core
* Registry for raster renderers.
*/
class CORE_EXPORT QgsRasterRendererRegistry
{
public:
static QgsRasterRendererRegistry* instance();
~QgsRasterRendererRegistry();
void insert( const QgsRasterRendererRegistryEntry& entry );
void insertWidgetFunction( const QString& rendererName, QgsRasterRendererWidgetCreateFunc func );
bool rendererData( const QString& rendererName, QgsRasterRendererRegistryEntry& data ) const;
QStringList renderersList() const;
QList< QgsRasterRendererRegistryEntry > entries() const;
/** Creates a default renderer for a raster drawing style (considering user options such as default contrast enhancement).
Caller takes ownership*/
QgsRasterRenderer* defaultRendererForDrawingStyle( const QgsRaster::DrawingStyle& theDrawingStyle, QgsRasterDataProvider* provider ) const;
protected:
QgsRasterRendererRegistry();
private:
static QgsRasterRendererRegistry* mInstance;
QHash< QString, QgsRasterRendererRegistryEntry > mEntries;
QStringList mSortedEntries;
//read min/max values from
bool minMaxValuesForBand( int band, QgsRasterDataProvider* provider, double& minValue, double& maxValue ) const;
};
#endif // QGSRASTERRENDERERREGISTRY_H
| gpl-2.0 |
leprechau/freeradius-server | scripts/docker/debian9/Dockerfile | 1168 | ARG from=debian:stretch
FROM ${from} as build
ARG gccver=6
#
# Install build tools
#
RUN apt-get update
RUN apt-get install -y devscripts equivs git quilt g++-${gccver}
#
# Create build directory
#
RUN mkdir -p /usr/local/src/repositories
WORKDIR /usr/local/src/repositories
#
# Shallow clone the FreeRADIUS source
#
ARG source=https://github.com/FreeRADIUS/freeradius-server.git
ARG release=v3.0.x
RUN git clone --depth 1 --single-branch --branch ${release} ${source}
WORKDIR freeradius-server
#
# Install build dependencies
#
RUN git checkout ${release}; \
if [ -e ./debian/control.in ]; then \
debian/rules debian/control; \
fi; \
echo 'y' | mk-build-deps -irt'apt-get -yV' debian/control
#
# Build the server
#
RUN make -j2 deb
#
# Clean environment and run the server
#
FROM ${from}
COPY --from=build /usr/local/src/repositories/*.deb /tmp/
RUN apt-get update \
&& apt-get install -y /tmp/*.deb \
&& apt-get clean \
&& rm -r /var/lib/apt/lists/* /tmp/*.deb \
\
&& ln -s /etc/freeradius /etc/raddb
COPY docker-entrypoint.sh /
EXPOSE 1812/udp 1813/udp
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["freeradius"]
| gpl-2.0 |
bondjimbond/bcelnapps | sites/all/modules/quiz/quiz.api.php | 4847 | <?php
/**
* @file quiz.api.php
* Hooks provided by Quiz module.
*
* These entity types provided by Quiz also have entity API hooks. There are a
* few additional Quiz specific hooks defined in this file.
*
* quiz (settings for quiz nodes)
* quiz_result (quiz attempt/result)
* quiz_result_answer (answer to a specific question in a quiz result)
* quiz_question (generic settings for question nodes)
* quiz_question_relationship (relationship from quiz to question)
*
* So for example
*
* hook_quiz_result_presave($quiz_result)
* - Runs before a result is saved to the DB.
* hook_quiz_question_relationship_insert($quiz_question_relationship)
* - Runs when a new question is added to a quiz.
*
* You can also use Rules to build conditional actions based off of these
* events.
*
* Enjoy :)
*/
/**
* Implements hook_quiz_begin().
*
* Fired when a new quiz result is created.
*
* @deprecated
*
* Use hook_quiz_result_insert().
*/
function hook_quiz_begin($quiz, $result_id) {
}
/**
* Implements hook_quiz_finished().
*
* Fired after the last question is submitted.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_finished($quiz, $score, $data) {
}
/**
* Implements hook_quiz_scored().
*
* Fired when a quiz is evaluated.
*
* @deprecated
*
* Use hook_quiz_result_update().
*/
function hook_quiz_scored($quiz, $score, $result_id) {
}
/**
* Implements hook_quiz_question_info().
*
* Define a new question type. The question provider must extend QuizQuestion,
* and the response provider must extend QuizQuestionResponse. See those classes
* for additional implementation details.
*/
function hook_quiz_question_info() {
return array(
'long_answer' => array(
'name' => t('Example question type'),
'description' => t('An example question type that does something.'),
'question provider' => 'ExampleAnswerQuestion',
'response provider' => 'ExampleAnswerResponse',
'module' => 'quiz_question',
),
);
}
/**
* Expose a feedback option to Quiz so that Quiz administrators can choose when
* to show it to Quiz takers.
*
* @return array
* An array of feedback options keyed by machine name.
*/
function hook_quiz_feedback_options() {
return array(
'percentile' => t('Percentile'),
);
}
/**
* Allow modules to alter the quiz feedback options.
*
* @param array $review_options
* An array of review options keyed by a machine name.
*/
function hook_quiz_feedback_options_alter(&$review_options) {
// Change label.
$review_options['quiz_feedback'] = t('General feedback from the Quiz.');
// Disable showing correct answer.
unset($review_options['solution']);
}
/**
* Allow modules to define feedback times.
*
* Feedback times are configurable by Rules.
*
* @return array
* An array of feedback times keyed by machine name.
*/
function hook_quiz_feedback_times() {
return array(
'2_weeks_later' => t('Two weeks after finishing'),
);
}
/**
* Allow modules to alter the feedback times.
*
* @param array $feedback_times
*/
function hook_quiz_feedback_times_alter(&$feedback_times) {
// Change label.
$feedback_times['end'] = t('At the end of a quiz');
// Do not allow question feedback.
unset($feedback_times['question']);
}
/**
* Allow modules to alter the feedback labels.
*
* These are the labels that are displayed to the user, so instead of
* "Answer feedback" you may want to display something more learner-friendly.
*
* @param $feedback_labels
* An array keyed by the feedback option. Default keys are the keys from
* quiz_get_feedback_options().
*/
function hook_quiz_feedback_labels_alter(&$feedback_labels) {
$feedback_labels['solution'] = t('The answer you should have chosen.');
}
/**
* Implements hook_quiz_access().
*
* Control access to Quizzes.
*
* @see quiz_quiz_access() for default access implementations.
*
* Modules may implement Quiz access control hooks to block access to a Quiz or
* display a non-blocking message. Blockers are keyed by a blocker name, and
* must be an array keyed by 'success' and 'message'.
*/
function hook_quiz_access($op, $quiz, $account) {
if ($op == 'take') {
$today = date('l');
if ($today == 'Monday') {
return array(
'monday' => array(
'success' => FALSE,
'message' => t('You cannot take quizzes on Monday.'),
),
);
}
else {
return array(
'not_monday' => array(
'success' => TRUE,
'message' => t('It is not Monday so you may take quizzes.'),
),
);
}
}
}
/**
* Implements hook_quiz_access_alter().
*
* Alter the access blockers for a Quiz.
*
*/
function hook_quiz_access_alter(&$hooks, $op, $quiz, $account) {
if ($op == 'take') {
unset($hooks['monday']);
}
}
| gpl-2.0 |
major91/Zeta-Chromium-N5 | arch/arm/mach-msm/peripheral-loader.c | 20309 | /* Copyright (c) 2010-2013, 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.
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/firmware.h>
#include <linux/io.h>
#include <linux/elf.h>
#include <linux/mutex.h>
#include <linux/memblock.h>
#include <linux/slab.h>
#include <linux/suspend.h>
#include <linux/rwsem.h>
#include <linux/sysfs.h>
#include <linux/workqueue.h>
#include <linux/jiffies.h>
#include <linux/wakelock.h>
#include <linux/err.h>
#include <linux/msm_ion.h>
#include <linux/list.h>
#include <linux/list_sort.h>
#include <linux/idr.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <asm/setup.h>
#include <asm-generic/io-64-nonatomic-lo-hi.h>
#include <mach/msm_iomap.h>
#include <mach/ramdump.h>
#include "peripheral-loader.h"
#define pil_err(desc, fmt, ...) \
dev_err(desc->dev, "%s: " fmt, desc->name, ##__VA_ARGS__)
#define pil_info(desc, fmt, ...) \
dev_info(desc->dev, "%s: " fmt, desc->name, ##__VA_ARGS__)
#define PIL_IMAGE_INFO_BASE (MSM_IMEM_BASE + 0x94c)
/**
* proxy_timeout - Override for proxy vote timeouts
* -1: Use driver-specified timeout
* 0: Hold proxy votes until shutdown
* >0: Specify a custom timeout in ms
*/
static int proxy_timeout_ms = -1;
module_param(proxy_timeout_ms, int, S_IRUGO | S_IWUSR);
/**
* struct pil_mdt - Representation of <name>.mdt file in memory
* @hdr: ELF32 header
* @phdr: ELF32 program headers
*/
struct pil_mdt {
struct elf32_hdr hdr;
struct elf32_phdr phdr[];
};
/**
* struct pil_seg - memory map representing one segment
* @next: points to next seg mentor NULL if last segment
* @paddr: start address of segment
* @sz: size of segment
* @filesz: size of segment on disk
* @num: segment number
* @relocated: true if segment is relocated, false otherwise
*
* Loosely based on an elf program header. Contains all necessary information
* to load and initialize a segment of the image in memory.
*/
struct pil_seg {
phys_addr_t paddr;
unsigned long sz;
unsigned long filesz;
int num;
struct list_head list;
bool relocated;
};
/**
* struct pil_image_info - information in IMEM about image and where it is loaded
* @name: name of image (may or may not be NULL terminated)
* @start: indicates physical address where image starts (little endian)
* @size: size of image (little endian)
*/
struct pil_image_info {
char name[8];
__le64 start;
__le32 size;
} __attribute__((__packed__));
/**
* struct pil_priv - Private state for a pil_desc
* @proxy: work item used to run the proxy unvoting routine
* @wlock: wakelock to prevent suspend during pil_boot
* @wname: name of @wlock
* @desc: pointer to pil_desc this is private data for
* @seg: list of segments sorted by physical address
* @entry_addr: physical address where processor starts booting at
* @base_addr: smallest start address among all segments that are relocatable
* @region_start: address where relocatable region starts or lowest address
* for non-relocatable images
* @region_end: address where relocatable region ends or highest address for
* non-relocatable images
* @region: region allocated for relocatable images
*
* This struct contains data for a pil_desc that should not be exposed outside
* of this file. This structure points to the descriptor and the descriptor
* points to this structure so that PIL drivers can't access the private
* data of a descriptor but this file can access both.
*/
struct pil_priv {
struct delayed_work proxy;
struct wake_lock wlock;
char wname[32];
struct pil_desc *desc;
struct list_head segs;
phys_addr_t entry_addr;
phys_addr_t base_addr;
phys_addr_t region_start;
phys_addr_t region_end;
struct ion_handle *region;
struct pil_image_info __iomem *info;
int id;
};
/**
* pil_do_ramdump() - Ramdump an image
* @desc: descriptor from pil_desc_init()
* @ramdump_dev: ramdump device returned from create_ramdump_device()
*
* Calls the ramdump API with a list of segments generated from the addresses
* that the descriptor corresponds to.
*/
int pil_do_ramdump(struct pil_desc *desc, void *ramdump_dev)
{
struct pil_priv *priv = desc->priv;
struct pil_seg *seg;
int count = 0, ret;
struct ramdump_segment *ramdump_segs, *s;
list_for_each_entry(seg, &priv->segs, list)
count++;
ramdump_segs = kmalloc_array(count, sizeof(*ramdump_segs), GFP_KERNEL);
if (!ramdump_segs)
return -ENOMEM;
s = ramdump_segs;
list_for_each_entry(seg, &priv->segs, list) {
s->address = seg->paddr;
s->size = seg->sz;
s++;
}
ret = do_elf_ramdump(ramdump_dev, ramdump_segs, count);
kfree(ramdump_segs);
return ret;
}
EXPORT_SYMBOL(pil_do_ramdump);
static struct ion_client *ion;
/**
* pil_get_entry_addr() - Retrieve the entry address of a peripheral image
* @desc: descriptor from pil_desc_init()
*
* Returns the physical address where the image boots at or 0 if unknown.
*/
phys_addr_t pil_get_entry_addr(struct pil_desc *desc)
{
return desc->priv ? desc->priv->entry_addr : 0;
}
EXPORT_SYMBOL(pil_get_entry_addr);
static void pil_proxy_work(struct work_struct *work)
{
struct delayed_work *delayed = to_delayed_work(work);
struct pil_priv *priv = container_of(delayed, struct pil_priv, proxy);
struct pil_desc *desc = priv->desc;
desc->ops->proxy_unvote(desc);
wake_unlock(&priv->wlock);
module_put(desc->owner);
}
static int pil_proxy_vote(struct pil_desc *desc)
{
int ret = 0;
struct pil_priv *priv = desc->priv;
if (desc->ops->proxy_vote) {
wake_lock(&priv->wlock);
ret = desc->ops->proxy_vote(desc);
if (ret)
wake_unlock(&priv->wlock);
}
return ret;
}
static void pil_proxy_unvote(struct pil_desc *desc, int immediate)
{
struct pil_priv *priv = desc->priv;
unsigned long timeout;
if (proxy_timeout_ms == 0 && !immediate)
return;
else if (proxy_timeout_ms > 0)
timeout = proxy_timeout_ms;
else
timeout = desc->proxy_timeout;
if (desc->ops->proxy_unvote) {
if (WARN_ON(!try_module_get(desc->owner)))
return;
if (immediate)
timeout = 0;
if (!desc->proxy_unvote_irq || immediate)
schedule_delayed_work(&priv->proxy,
msecs_to_jiffies(timeout));
}
}
static irqreturn_t proxy_unvote_intr_handler(int irq, void *dev_id)
{
struct pil_desc *desc = dev_id;
schedule_delayed_work(&desc->priv->proxy, 0);
return IRQ_HANDLED;
}
static bool segment_is_relocatable(const struct elf32_phdr *p)
{
return !!(p->p_flags & BIT(27));
}
static phys_addr_t pil_reloc(const struct pil_priv *priv, phys_addr_t addr)
{
return addr - priv->base_addr + priv->region_start;
}
static struct pil_seg *pil_init_seg(const struct pil_desc *desc,
const struct elf32_phdr *phdr, int num)
{
bool reloc = segment_is_relocatable(phdr);
const struct pil_priv *priv = desc->priv;
struct pil_seg *seg;
if (!reloc && memblock_overlaps_memory(phdr->p_paddr, phdr->p_memsz)) {
pil_err(desc, "kernel memory would be overwritten [%#08lx, %#08lx)\n",
(unsigned long)phdr->p_paddr,
(unsigned long)(phdr->p_paddr + phdr->p_memsz));
return ERR_PTR(-EPERM);
}
seg = kmalloc(sizeof(*seg), GFP_KERNEL);
if (!seg)
return ERR_PTR(-ENOMEM);
seg->num = num;
seg->paddr = reloc ? pil_reloc(priv, phdr->p_paddr) : phdr->p_paddr;
seg->filesz = phdr->p_filesz;
seg->sz = phdr->p_memsz;
seg->relocated = reloc;
INIT_LIST_HEAD(&seg->list);
return seg;
}
#define segment_is_hash(flag) (((flag) & (0x7 << 24)) == (0x2 << 24))
static int segment_is_loadable(const struct elf32_phdr *p)
{
return (p->p_type == PT_LOAD) && !segment_is_hash(p->p_flags) &&
p->p_memsz;
}
static void pil_dump_segs(const struct pil_priv *priv)
{
struct pil_seg *seg;
phys_addr_t seg_h_paddr;
list_for_each_entry(seg, &priv->segs, list) {
seg_h_paddr = seg->paddr + seg->sz;
pil_info(priv->desc, "%d: %pa %pa\n", seg->num,
&seg->paddr, &seg_h_paddr);
}
}
/*
* Ensure the entry address lies within the image limits and if the image is
* relocatable ensure it lies within a relocatable segment.
*/
static int pil_init_entry_addr(struct pil_priv *priv, const struct pil_mdt *mdt)
{
struct pil_seg *seg;
phys_addr_t entry = mdt->hdr.e_entry;
bool image_relocated = priv->region;
if (image_relocated)
entry = pil_reloc(priv, entry);
priv->entry_addr = entry;
if (priv->desc->flags & PIL_SKIP_ENTRY_CHECK)
return 0;
list_for_each_entry(seg, &priv->segs, list) {
if (entry >= seg->paddr && entry < seg->paddr + seg->sz) {
if (!image_relocated)
return 0;
else if (seg->relocated)
return 0;
}
}
pil_err(priv->desc, "entry address %pa not within range\n", &entry);
pil_dump_segs(priv);
return -EADDRNOTAVAIL;
}
static int pil_alloc_region(struct pil_priv *priv, phys_addr_t min_addr,
phys_addr_t max_addr, size_t align)
{
struct ion_handle *region;
int ret;
unsigned int mask;
size_t size = max_addr - min_addr;
/* Don't reallocate due to fragmentation concerns, just sanity check */
if (priv->region) {
if (WARN(priv->region_end - priv->region_start < size,
"Can't reuse PIL memory, too small\n"))
return -ENOMEM;
return 0;
}
if (!ion) {
WARN_ON_ONCE("No ION client, can't support relocation\n");
return -ENOMEM;
}
/* Force alignment due to linker scripts not getting it right */
if (align > SZ_1M) {
mask = ION_HEAP(ION_PIL2_HEAP_ID);
align = SZ_4M;
} else {
mask = ION_HEAP(ION_PIL1_HEAP_ID);
align = SZ_1M;
}
region = ion_alloc(ion, size, align, mask, 0);
if (IS_ERR(region)) {
pil_err(priv->desc, "Failed to allocate relocatable region\n");
return PTR_ERR(region);
}
ret = ion_phys(ion, region, (ion_phys_addr_t *)&priv->region_start,
&size);
if (ret) {
ion_free(ion, region);
return ret;
}
priv->region = region;
priv->region_end = priv->region_start + size;
priv->base_addr = min_addr;
return 0;
}
static int pil_setup_region(struct pil_priv *priv, const struct pil_mdt *mdt)
{
const struct elf32_phdr *phdr;
phys_addr_t min_addr_r, min_addr_n, max_addr_r, max_addr_n, start, end;
size_t align = 0;
int i, ret = 0;
bool relocatable = false;
min_addr_n = min_addr_r = (phys_addr_t)ULLONG_MAX;
max_addr_n = max_addr_r = 0;
/* Find the image limits */
for (i = 0; i < mdt->hdr.e_phnum; i++) {
phdr = &mdt->phdr[i];
if (!segment_is_loadable(phdr))
continue;
start = phdr->p_paddr;
end = start + phdr->p_memsz;
if (segment_is_relocatable(phdr)) {
min_addr_r = min(min_addr_r, start);
max_addr_r = max(max_addr_r, end);
/*
* Lowest relocatable segment dictates alignment of
* relocatable region
*/
if (min_addr_r == start)
align = phdr->p_align;
relocatable = true;
} else {
min_addr_n = min(min_addr_n, start);
max_addr_n = max(max_addr_n, end);
}
}
/*
* Align the max address to the next 4K boundary to satisfy iommus and
* XPUs that operate on 4K chunks.
*/
max_addr_n = ALIGN(max_addr_n, SZ_4K);
max_addr_r = ALIGN(max_addr_r, SZ_4K);
if (relocatable) {
ret = pil_alloc_region(priv, min_addr_r, max_addr_r, align);
} else {
priv->region_start = min_addr_n;
priv->region_end = max_addr_n;
priv->base_addr = min_addr_n;
}
writeq(priv->region_start, &priv->info->start);
writel_relaxed(priv->region_end - priv->region_start,
&priv->info->size);
return ret;
}
static int pil_cmp_seg(void *priv, struct list_head *a, struct list_head *b)
{
struct pil_seg *seg_a = list_entry(a, struct pil_seg, list);
struct pil_seg *seg_b = list_entry(b, struct pil_seg, list);
return seg_a->paddr - seg_b->paddr;
}
static int pil_init_mmap(struct pil_desc *desc, const struct pil_mdt *mdt)
{
struct pil_priv *priv = desc->priv;
const struct elf32_phdr *phdr;
struct pil_seg *seg;
int i, ret;
ret = pil_setup_region(priv, mdt);
if (ret)
return ret;
for (i = 0; i < mdt->hdr.e_phnum; i++) {
phdr = &mdt->phdr[i];
if (!segment_is_loadable(phdr))
continue;
seg = pil_init_seg(desc, phdr, i);
if (IS_ERR(seg))
return PTR_ERR(seg);
list_add_tail(&seg->list, &priv->segs);
}
list_sort(NULL, &priv->segs, pil_cmp_seg);
return pil_init_entry_addr(priv, mdt);
}
static void pil_release_mmap(struct pil_desc *desc)
{
struct pil_priv *priv = desc->priv;
struct pil_seg *p, *tmp;
writeq(0, &priv->info->start);
writel_relaxed(0, &priv->info->size);
list_for_each_entry_safe(p, tmp, &priv->segs, list) {
list_del(&p->list);
kfree(p);
}
}
#define IOMAP_SIZE SZ_1M
static int pil_load_seg(struct pil_desc *desc, struct pil_seg *seg)
{
int ret = 0, count;
phys_addr_t paddr;
char fw_name[30];
const struct firmware *fw = NULL;
const u8 *data;
int num = seg->num;
if (seg->filesz) {
snprintf(fw_name, ARRAY_SIZE(fw_name), "%s.b%02d",
desc->name, num);
ret = request_firmware(&fw, fw_name, desc->dev);
if (ret) {
pil_err(desc, "Failed to locate blob %s\n", fw_name);
return ret;
}
if (fw->size != seg->filesz) {
pil_err(desc, "Blob size %u doesn't match %lu\n",
fw->size, seg->filesz);
ret = -EPERM;
goto release_fw;
}
}
/* Load the segment into memory */
count = seg->filesz;
paddr = seg->paddr;
data = fw ? fw->data : NULL;
while (count > 0) {
int size;
u8 __iomem *buf;
size = min_t(size_t, IOMAP_SIZE, count);
buf = ioremap(paddr, size);
if (!buf) {
pil_err(desc, "Failed to map memory\n");
ret = -ENOMEM;
goto release_fw;
}
memcpy(buf, data, size);
iounmap(buf);
count -= size;
paddr += size;
data += size;
}
/* Zero out trailing memory */
count = seg->sz - seg->filesz;
while (count > 0) {
int size;
u8 __iomem *buf;
size = min_t(size_t, IOMAP_SIZE, count);
buf = ioremap(paddr, size);
if (!buf) {
pil_err(desc, "Failed to map memory\n");
ret = -ENOMEM;
goto release_fw;
}
memset(buf, 0, size);
iounmap(buf);
count -= size;
paddr += size;
}
if (desc->ops->verify_blob) {
ret = desc->ops->verify_blob(desc, seg->paddr, seg->sz);
if (ret)
pil_err(desc, "Blob%u failed verification\n", num);
}
release_fw:
release_firmware(fw);
return ret;
}
/* Synchronize request_firmware() with suspend */
static DECLARE_RWSEM(pil_pm_rwsem);
/**
* pil_boot() - Load a peripheral image into memory and boot it
* @desc: descriptor from pil_desc_init()
*
* Returns 0 on success or -ERROR on failure.
*/
int pil_boot(struct pil_desc *desc)
{
int ret;
char fw_name[30];
const struct pil_mdt *mdt;
const struct elf32_hdr *ehdr;
struct pil_seg *seg;
const struct firmware *fw;
struct pil_priv *priv = desc->priv;
/* Reinitialize for new image */
pil_release_mmap(desc);
down_read(&pil_pm_rwsem);
snprintf(fw_name, sizeof(fw_name), "%s.mdt", desc->name);
ret = request_firmware(&fw, fw_name, desc->dev);
if (ret) {
pil_err(desc, "Failed to locate %s\n", fw_name);
goto out;
}
if (fw->size < sizeof(*ehdr)) {
pil_err(desc, "Not big enough to be an elf header\n");
ret = -EIO;
goto release_fw;
}
mdt = (const struct pil_mdt *)fw->data;
ehdr = &mdt->hdr;
if (memcmp(ehdr->e_ident, ELFMAG, SELFMAG)) {
pil_err(desc, "Not an elf header\n");
ret = -EIO;
goto release_fw;
}
if (ehdr->e_phnum == 0) {
pil_err(desc, "No loadable segments\n");
ret = -EIO;
goto release_fw;
}
if (sizeof(struct elf32_phdr) * ehdr->e_phnum +
sizeof(struct elf32_hdr) > fw->size) {
pil_err(desc, "Program headers not within mdt\n");
ret = -EIO;
goto release_fw;
}
ret = pil_init_mmap(desc, mdt);
if (ret)
goto release_fw;
if (desc->ops->init_image)
ret = desc->ops->init_image(desc, fw->data, fw->size);
if (ret) {
pil_err(desc, "Invalid firmware metadata\n");
goto release_fw;
}
if (desc->ops->mem_setup)
ret = desc->ops->mem_setup(desc, priv->region_start,
priv->region_end - priv->region_start);
if (ret) {
pil_err(desc, "Memory setup error\n");
goto release_fw;
}
list_for_each_entry(seg, &desc->priv->segs, list) {
ret = pil_load_seg(desc, seg);
if (ret)
goto release_fw;
}
ret = pil_proxy_vote(desc);
if (ret) {
pil_err(desc, "Failed to proxy vote\n");
goto release_fw;
}
ret = desc->ops->auth_and_reset(desc);
if (ret) {
pil_err(desc, "Failed to bring out of reset\n");
goto err_boot;
}
pil_info(desc, "Brought out of reset\n");
err_boot:
pil_proxy_unvote(desc, ret);
release_fw:
release_firmware(fw);
out:
up_read(&pil_pm_rwsem);
if (ret) {
if (priv->region) {
ion_free(ion, priv->region);
priv->region = NULL;
}
pil_release_mmap(desc);
}
return ret;
}
EXPORT_SYMBOL(pil_boot);
/**
* pil_shutdown() - Shutdown a peripheral
* @desc: descriptor from pil_desc_init()
*/
void pil_shutdown(struct pil_desc *desc)
{
struct pil_priv *priv = desc->priv;
if (desc->ops->shutdown)
desc->ops->shutdown(desc);
if (proxy_timeout_ms == 0 && desc->ops->proxy_unvote)
desc->ops->proxy_unvote(desc);
else
flush_delayed_work(&priv->proxy);
}
EXPORT_SYMBOL(pil_shutdown);
static DEFINE_IDA(pil_ida);
/**
* pil_desc_init() - Initialize a pil descriptor
* @desc: descriptor to intialize
*
* Initialize a pil descriptor for use by other pil functions. This function
* must be called before calling pil_boot() or pil_shutdown().
*
* Returns 0 for success and -ERROR on failure.
*/
int pil_desc_init(struct pil_desc *desc)
{
struct pil_priv *priv;
int ret;
void __iomem *addr;
char buf[sizeof(priv->info->name)];
/* Ignore users who don't make any sense */
WARN(desc->ops->proxy_unvote && desc->proxy_unvote_irq == 0
&& !desc->proxy_timeout,
"Invalid proxy unvote callback or a proxy timeout of 0"
" was specified or no proxy unvote IRQ was specified.\n");
if (WARN(desc->ops->proxy_unvote && !desc->ops->proxy_vote,
"Invalid proxy voting. Ignoring\n"))
((struct pil_reset_ops *)desc->ops)->proxy_unvote = NULL;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
desc->priv = priv;
priv->desc = desc;
priv->id = ret = ida_simple_get(&pil_ida, 0, 10, GFP_KERNEL);
if (priv->id < 0)
goto err;
addr = PIL_IMAGE_INFO_BASE + sizeof(struct pil_image_info) * priv->id;
priv->info = (struct pil_image_info __iomem *)addr;
strncpy(buf, desc->name, sizeof(buf));
__iowrite32_copy(priv->info->name, buf, sizeof(buf) / 4);
if (desc->proxy_unvote_irq > 0) {
ret = request_irq(desc->proxy_unvote_irq,
proxy_unvote_intr_handler,
IRQF_TRIGGER_RISING|IRQF_SHARED,
desc->name, desc);
if (ret < 0) {
dev_err(desc->dev,
"Unable to request proxy unvote IRQ: %d\n",
ret);
goto err;
}
}
snprintf(priv->wname, sizeof(priv->wname), "pil-%s", desc->name);
wake_lock_init(&priv->wlock, WAKE_LOCK_SUSPEND, priv->wname);
INIT_DELAYED_WORK(&priv->proxy, pil_proxy_work);
INIT_LIST_HEAD(&priv->segs);
return 0;
err:
kfree(priv);
return ret;
}
EXPORT_SYMBOL(pil_desc_init);
/**
* pil_desc_release() - Release a pil descriptor
* @desc: descriptor to free
*/
void pil_desc_release(struct pil_desc *desc)
{
struct pil_priv *priv = desc->priv;
if (priv) {
ida_simple_remove(&pil_ida, priv->id);
flush_delayed_work(&priv->proxy);
wake_lock_destroy(&priv->wlock);
}
desc->priv = NULL;
kfree(priv);
}
EXPORT_SYMBOL(pil_desc_release);
static int pil_pm_notify(struct notifier_block *b, unsigned long event, void *p)
{
switch (event) {
case PM_SUSPEND_PREPARE:
down_write(&pil_pm_rwsem);
break;
case PM_POST_SUSPEND:
up_write(&pil_pm_rwsem);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block pil_pm_notifier = {
.notifier_call = pil_pm_notify,
};
static int __init msm_pil_init(void)
{
ion = msm_ion_client_create(UINT_MAX, "pil");
if (IS_ERR(ion)) /* Can't support relocatable images */
ion = NULL;
return register_pm_notifier(&pil_pm_notifier);
}
device_initcall(msm_pil_init);
static void __exit msm_pil_exit(void)
{
unregister_pm_notifier(&pil_pm_notifier);
if (ion)
ion_client_destroy(ion);
}
module_exit(msm_pil_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Load peripheral images and bring peripherals out of reset");
| gpl-2.0 |
FrancoisFinfe/bcm2835-1.9 | src/test.c | 559 | // Test program for bcm2835 library
// You can only expect this to run correctly
// as root on Raspberry Pi hardware
//
// Author: Mike McCauley ([email protected])
// Copyright (C) 2011 Mike McCauley
// $Id: test.c,v 1.2 2012/06/26 01:40:50 mikem Exp $
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (geteuid() == 0)
{
if (!bcm2835_init())
return 1;
if (!bcm2835_close())
return 1;
}
else
{
fprintf(stderr, "****You need to be root to properly run this test program\n");
}
return 0;
}
| gpl-2.0 |
masahir0y/barebox-yamada | arch/arm/boards/nvidia-jetson-tk1/board.c | 1285 | // SPDX-License-Identifier: GPL-2.0-only
// SPDX-FileCopyrightText: 2014 Lucas Stach <[email protected]>
#include <common.h>
#include <dt-bindings/gpio/tegra-gpio.h>
#include <gpio.h>
#include <i2c/i2c.h>
#include <init.h>
#include <mach/tegra-bbu.h>
#define AS3722_SD_VOLTAGE(n) (0x00 + (n))
#define AS3722_GPIO_CONTROL(n) (0x08 + (n))
#define AS3722_GPIO_CONTROL_MODE_OUTPUT_VDDH (1 << 0)
#define AS3722_GPIO_SIGNAL_OUT 0x20
#define AS3722_SD_CONTROL 0x4d
static int nvidia_jetson_tk1_fs_init(void)
{
struct i2c_client client;
u8 data;
if (!of_machine_is_compatible("nvidia,jetson-tk1"))
return 0;
client.adapter = i2c_get_adapter(4);
client.addr = 0x40;
/* AS3722: enable SD4 and set voltage to 1.05v */
i2c_read_reg(&client, AS3722_SD_CONTROL, &data, 1);
data |= 1 << 4;
i2c_write_reg(&client, AS3722_SD_CONTROL, &data, 1);
data = 0x24;
i2c_write_reg(&client, AS3722_SD_VOLTAGE(4), &data, 1);
return 0;
}
fs_initcall(nvidia_jetson_tk1_fs_init);
static int nvidia_jetson_tk1_device_init(void)
{
if (!of_machine_is_compatible("nvidia,jetson-tk1"))
return 0;
barebox_set_hostname("jetson-tk1");
tegra_bbu_register_emmc_handler("eMMC", "/dev/mmc3.boot0",
BBU_HANDLER_FLAG_DEFAULT);
return 0;
}
device_initcall(nvidia_jetson_tk1_device_init);
| gpl-2.0 |
neonatura/crotalus | php/ext/opcache/tests/bug67215.phpt | 721 | --TEST--
Bug #67215 (php-cgi work with opcache, may be segmentation fault happen)
--INI--
opcache.enable=1
opcache.enable_cli=1
opcache.file_update_protection=0
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
file_put_contents($file_c, "<?php require \"$file_p\"; class c extends p {} ?>");
file_put_contents($file_p, '<?php class p { protected $var = ""; } ?>');
require $file_c;
$a = new c();
require $file_c;
?>
--CLEAN--
<?php
$file_c = __DIR__ . "/bug67215.c.php";
$file_p = __DIR__ . "/bug67215.p.php";
unlink($file_c);
unlink($file_p);
?>
--EXPECTF--
Fatal error: Cannot redeclare class c in %sbug67215.c.php on line %d
| gpl-2.0 |
CyanogenMod/android_kernel_lge_dory | drivers/input/touchscreen/synaptics_i2c_rmi4.h | 10394 | /*
* Synaptics RMI4 touchscreen driver
*
* Copyright (C) 2012 Synaptics Incorporated
*
* Copyright (C) 2012 Alexandra Chin <[email protected]>
* Copyright (C) 2012 Scott Lin <[email protected]>
* Copyright (c) 2013-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 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.
*/
#ifndef _SYNAPTICS_DSX_RMI4_H_
#define _SYNAPTICS_DSX_RMI4_H_
#define SYNAPTICS_DS4 (1 << 0)
#define SYNAPTICS_DS5 (1 << 1)
#define SYNAPTICS_DSX_DRIVER_PRODUCT SYNAPTICS_DS4
#define SYNAPTICS_DSX_DRIVER_VERSION 0x1005
#include <linux/version.h>
#ifdef CONFIG_FB
#include <linux/notifier.h>
#include <linux/fb.h>
#elif defined CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif
#include <linux/debugfs.h>
#include <linux/time.h>
#define PDT_PROPS (0x00EF)
#define PDT_START (0x00E9)
#define PDT_END (0x000A)
#define PDT_ENTRY_SIZE (0x0006)
#define PAGES_TO_SERVICE (10)
#define PAGE_SELECT_LEN (2)
#define SYNAPTICS_RMI4_F01 (0x01)
#define SYNAPTICS_RMI4_F11 (0x11)
#define SYNAPTICS_RMI4_F12 (0x12)
#define SYNAPTICS_RMI4_F1A (0x1a)
#define SYNAPTICS_RMI4_F34 (0x34)
#define SYNAPTICS_RMI4_F54 (0x54)
#define SYNAPTICS_RMI4_F55 (0x55)
#define SYNAPTICS_RMI4_PRODUCT_INFO_SIZE 2
#define SYNAPTICS_RMI4_DATE_CODE_SIZE 3
#define SYNAPTICS_RMI4_PRODUCT_ID_SIZE 10
#define SYNAPTICS_RMI4_BUILD_ID_SIZE 3
#define MAX_NUMBER_OF_FINGERS 10
#define MAX_NUMBER_OF_BUTTONS 4
#define MAX_INTR_REGISTERS 4
#define MASK_16BIT 0xFFFF
#define MASK_8BIT 0xFF
#define MASK_7BIT 0x7F
#define MASK_6BIT 0x3F
#define MASK_5BIT 0x1F
#define MASK_4BIT 0x0F
#define MASK_3BIT 0x07
#define MASK_2BIT 0x03
#define MASK_1BIT 0x01
#define NAME_BUFFER_SIZE 256
/*
* struct synaptics_rmi4_fn_desc - function descriptor fields in PDT
* @query_base_addr: base address for query registers
* @cmd_base_addr: base address for command registers
* @ctrl_base_addr: base address for control registers
* @data_base_addr: base address for data registers
* @intr_src_count: number of interrupt sources
* @fn_number: function number
*/
struct synaptics_rmi4_fn_desc {
unsigned char query_base_addr;
unsigned char cmd_base_addr;
unsigned char ctrl_base_addr;
unsigned char data_base_addr;
unsigned char intr_src_count:3;
unsigned char reserved_b3_b4:2;
unsigned char version:2;
unsigned char reserved_b7:1;
unsigned char fn_number;
} __packed;
/*
* synaptics_rmi4_fn_full_addr - full 16-bit base addresses
* @query_base: 16-bit base address for query registers
* @cmd_base: 16-bit base address for data registers
* @ctrl_base: 16-bit base address for command registers
* @data_base: 16-bit base address for control registers
*/
struct synaptics_rmi4_fn_full_addr {
unsigned short query_base;
unsigned short cmd_base;
unsigned short ctrl_base;
unsigned short data_base;
};
/*
* struct synaptics_rmi4_fn - function handler data structure
* @fn_number: function number
* @num_of_data_sources: number of data sources
* @num_of_data_points: maximum number of fingers supported
* @size_of_data_register_block: data register block size
* @data1_offset: offset to data1 register from data base address
* @intr_reg_num: index to associated interrupt register
* @intr_mask: interrupt mask
* @full_addr: full 16-bit base addresses of function registers
* @link: linked list for function handlers
* @data_size: size of private data
* @data: pointer to private data
*/
struct synaptics_rmi4_fn {
unsigned char fn_number;
unsigned char num_of_data_sources;
unsigned char num_of_data_points;
unsigned char size_of_data_register_block;
unsigned char data1_offset;
unsigned char intr_reg_num;
unsigned char intr_mask;
struct synaptics_rmi4_fn_full_addr full_addr;
struct list_head link;
int data_size;
void *data;
void *extra;
};
/*
* struct synaptics_rmi4_device_info - device information
* @version_major: rmi protocol major version number
* @version_minor: rmi protocol minor version number
* @manufacturer_id: manufacturer id
* @product_props: product properties information
* @product_info: product info array
* @date_code: device manufacture date
* @tester_id: tester id array
* @serial_number: device serial number
* @product_id_string: device product id
* @support_fn_list: linked list for function handlers
*/
struct synaptics_rmi4_device_info {
unsigned int version_major;
unsigned int version_minor;
unsigned char manufacturer_id;
unsigned char product_props;
unsigned char product_info[SYNAPTICS_RMI4_PRODUCT_INFO_SIZE];
unsigned char date_code[SYNAPTICS_RMI4_DATE_CODE_SIZE];
unsigned short tester_id;
unsigned short serial_number;
unsigned char product_id_string[SYNAPTICS_RMI4_PRODUCT_ID_SIZE + 1];
unsigned char build_id[SYNAPTICS_RMI4_BUILD_ID_SIZE];
unsigned char config_id[3];
struct mutex support_fn_list_mutex;
struct list_head support_fn_list;
};
/*
* struct synaptics_rmi4_data - rmi4 device instance data
* @i2c_client: pointer to associated i2c client
* @input_dev: pointer to associated input device
* @board: constant pointer to platform data
* @rmi4_mod_info: device information
* @regulator: pointer to associated regulator
* @rmi4_io_ctrl_mutex: mutex for i2c i/o control
* @det_work: work thread instance for expansion function detection
* @det_workqueue: pointer to work queue for work thread instance
* @early_suspend: instance to support early suspend power management
* @current_page: current page in sensor to acess
* @button_0d_enabled: flag for 0d button support
* @full_pm_cycle: flag for full power management cycle in early suspend stage
* @num_of_intr_regs: number of interrupt registers
* @f01_query_base_addr: query base address for f01
* @f01_cmd_base_addr: command base address for f01
* @f01_ctrl_base_addr: control base address for f01
* @f01_data_base_addr: data base address for f01
* @irq: attention interrupt
* @sensor_max_x: sensor maximum x value
* @sensor_max_y: sensor maximum y value
* @disp_maxx: max x value of display
* @disp_maxy: max y value of display
* @disp_minx: min x value of display
* @disp_miny: min y value of display
* @irq_enabled: flag for indicating interrupt enable status
* @touch_stopped: flag to stop interrupt thread processing
* @fingers_on_2d: flag to indicate presence of fingers in 2d area
* @flip_x: set to TRUE if desired to flip direction on x-axis
* @flip_y: set to TRUE if desired to flip direction on y-axis
* @fw_updating: firmware is updating flag
* @sensor_sleep: flag to indicate sleep state of sensor
* @wait: wait queue for touch data polling in interrupt thread
* @i2c_read: pointer to i2c read function
* @i2c_write: pointer to i2c write function
* @irq_enable: pointer to irq enable function
*/
struct synaptics_rmi4_data {
struct i2c_client *i2c_client;
struct input_dev *input_dev;
const struct synaptics_rmi4_platform_data *board;
struct synaptics_rmi4_device_info rmi4_mod_info;
struct regulator *vdd;
struct regulator *vcc_i2c;
struct mutex rmi4_io_ctrl_mutex;
struct delayed_work det_work;
struct workqueue_struct *det_workqueue;
struct work_struct recovery_work;
struct delayed_work init_work;
#ifdef CONFIG_HAS_EARLYSUSPEND
struct early_suspend early_suspend;
#endif
struct dentry *dir;
char fw_image_name[NAME_BUFFER_SIZE];
unsigned char current_page;
unsigned char button_0d_enabled;
unsigned char full_pm_cycle;
unsigned char num_of_rx;
unsigned char num_of_tx;
unsigned char num_of_fingers;
unsigned char max_touch_width;
unsigned char report_enable;
unsigned char intr_mask[MAX_INTR_REGISTERS];
unsigned short num_of_intr_regs;
unsigned short f01_query_base_addr;
unsigned short f01_cmd_base_addr;
unsigned short f01_ctrl_base_addr;
unsigned short f01_data_base_addr;
int irq;
int sensor_max_x;
int sensor_max_y;
int disp_maxx;
int disp_maxy;
int disp_minx;
int disp_miny;
bool palm_detected;
struct timespec palm_debounce;
bool irq_enabled;
bool touch_stopped;
bool fingers_on_2d;
bool sensor_sleep;
bool flip_x;
bool flip_y;
bool fw_updating;
bool suspended;
wait_queue_head_t wait;
bool stay_awake;
bool staying_awake;
int (*i2c_read)(struct synaptics_rmi4_data *pdata, unsigned short addr,
unsigned char *data, unsigned short length);
int (*i2c_write)(struct synaptics_rmi4_data *pdata, unsigned short addr,
unsigned char *data, unsigned short length);
int (*irq_enable)(struct synaptics_rmi4_data *rmi4_data, bool enable);
int (*reset_device)(struct synaptics_rmi4_data *rmi4_data);
#ifdef CONFIG_FB
struct notifier_block fb_notif;
#else
#ifdef CONFIG_HAS_EARLYSUSPEND
struct early_suspend early_suspend;
#endif
#endif
struct pinctrl *ts_pinctrl;
struct pinctrl_state *gpio_state_active;
struct pinctrl_state *gpio_state_suspend;
};
enum exp_fn {
RMI_DEV = 0,
RMI_F34,
RMI_F54,
RMI_FW_UPDATER,
RMI_LAST,
};
struct synaptics_rmi4_exp_fn_ptr {
int (*read)(struct synaptics_rmi4_data *rmi4_data, unsigned short addr,
unsigned char *data, unsigned short length);
int (*write)(struct synaptics_rmi4_data *rmi4_data, unsigned short addr,
unsigned char *data, unsigned short length);
int (*enable)(struct synaptics_rmi4_data *rmi4_data, bool enable);
};
void synaptics_rmi4_new_function(enum exp_fn fn_type, bool insert,
int (*func_init)(struct synaptics_rmi4_data *rmi4_data),
void (*func_remove)(struct synaptics_rmi4_data *rmi4_data),
void (*func_attn)(struct synaptics_rmi4_data *rmi4_data,
unsigned char intr_mask));
static inline ssize_t synaptics_rmi4_store_error(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
dev_warn(dev, "%s Attempted to write to read-only attribute %s\n",
__func__, attr->attr.name);
return -EPERM;
}
static inline void batohs(unsigned short *dest, unsigned char *src)
{
*dest = src[1] * 0x100 + src[0];
}
static inline void hstoba(unsigned char *dest, unsigned short src)
{
dest[0] = src % 0x100;
dest[1] = src / 0x100;
}
#endif
| gpl-2.0 |
unicell/redpatch | fs/cifs/cifsglob.h | 29457 | /*
* fs/cifs/cifsglob.h
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French ([email protected])
* Jeremy Allison ([email protected])
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Lesser General Public License for more details.
*
*/
#ifndef _CIFS_GLOB_H
#define _CIFS_GLOB_H
#include <linux/in.h>
#include <linux/in6.h>
#include <linux/slow-work.h>
#include <linux/workqueue.h>
#include "cifs_fs_sb.h"
#include "cifsacl.h"
#include <crypto/internal/hash.h>
#include <linux/scatterlist.h>
/*
* The sizes of various internal tables and strings
*/
#define MAX_UID_INFO 16
#define MAX_SES_INFO 2
#define MAX_TCON_INFO 4
#define MAX_TREE_SIZE (2 + MAX_SERVER_SIZE + 1 + MAX_SHARE_SIZE + 1)
#define MAX_SERVER_SIZE 15
#define MAX_SHARE_SIZE 80
#define MAX_USERNAME_SIZE 256 /* reasonable maximum for current servers */
#define MAX_PASSWORD_SIZE 512 /* max for windows seems to be 256 wide chars */
#define CIFS_MIN_RCV_POOL 4
#define MAX_REOPEN_ATT 5 /* these many maximum attempts to reopen a file */
/*
* default attribute cache timeout (jiffies)
*/
#define CIFS_DEF_ACTIMEO (1 * HZ)
/*
* max attribute cache timeout (jiffies) - 2^30
*/
#define CIFS_MAX_ACTIMEO (1 << 30)
/*
* MAX_REQ is the maximum number of requests that WE will send
* on one socket concurently. It also matches the most common
* value of max multiplex returned by servers. We may
* eventually want to use the negotiated value (in case
* future servers can handle more) when we are more confident that
* we will not have problems oveloading the socket with pending
* write data.
*/
#define CIFS_MAX_REQ 50
#define RFC1001_NAME_LEN 15
#define RFC1001_NAME_LEN_WITH_NULL (RFC1001_NAME_LEN + 1)
/* currently length of NIP6_FMT */
#define SERVER_NAME_LENGTH 40
#define SERVER_NAME_LEN_WITH_NULL (SERVER_NAME_LENGTH + 1)
/* used to define string lengths for reversing unicode strings */
/* (256+1)*2 = 514 */
/* (max path length + 1 for null) * 2 for unicode */
#define MAX_NAME 514
#include "cifspdu.h"
#ifndef XATTR_DOS_ATTRIB
#define XATTR_DOS_ATTRIB "user.DOSATTRIB"
#endif
/*
* CIFS vfs client Status information (based on what we know.)
*/
/* associated with each tcp and smb session */
enum statusEnum {
CifsNew = 0,
CifsGood,
CifsExiting,
CifsNeedReconnect,
CifsNeedNegotiate
};
enum securityEnum {
LANMAN = 0, /* Legacy LANMAN auth */
NTLM, /* Legacy NTLM012 auth with NTLM hash */
NTLMv2, /* Legacy NTLM auth with NTLMv2 hash */
RawNTLMSSP, /* NTLMSSP without SPNEGO, NTLMv2 hash */
/* NTLMSSP, */ /* can use rawNTLMSSP instead of NTLMSSP via SPNEGO */
Kerberos, /* Kerberos via SPNEGO */
};
enum protocolEnum {
TCP = 0,
SCTP
/* Netbios frames protocol not supported at this time */
};
struct session_key {
unsigned int len;
char *response;
};
/* crypto security descriptor definition */
struct sdesc {
struct shash_desc shash;
char ctx[];
};
/* crypto hashing related structure/fields, not specific to a sec mech */
struct cifs_secmech {
struct crypto_shash *hmacmd5; /* hmac-md5 hash function */
struct crypto_shash *md5; /* md5 hash function */
struct sdesc *sdeschmacmd5; /* ctxt to generate ntlmv2 hash, CR1 */
struct sdesc *sdescmd5; /* ctxt to generate cifs/smb signature */
};
/* per smb session structure/fields */
struct ntlmssp_auth {
__u32 client_flags; /* sent by client in type 1 ntlmsssp exchange */
__u32 server_flags; /* sent by server in type 2 ntlmssp exchange */
unsigned char ciphertext[CIFS_CPHTXT_SIZE]; /* sent to server */
char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlmssp */
};
struct cifs_cred {
int uid;
int gid;
int mode;
int cecount;
struct cifs_sid osid;
struct cifs_sid gsid;
struct cifs_ntace *ntaces;
struct cifs_ace *aces;
};
/*
*****************************************************************
* Except the CIFS PDUs themselves all the
* globally interesting structs should go here
*****************************************************************
*/
struct smb_vol {
char *username;
char *password;
char *domainname;
char *UNC;
char *UNCip;
char *iocharset; /* local code page for mapping to and from Unicode */
char source_rfc1001_name[16]; /* netbios name of client */
char target_rfc1001_name[16]; /* netbios name of server for Win9x/ME */
uid_t cred_uid;
uid_t linux_uid;
gid_t linux_gid;
uid_t backupuid;
gid_t backupgid;
mode_t file_mode;
mode_t dir_mode;
unsigned secFlg;
bool retry:1;
bool intr:1;
bool setuids:1;
bool override_uid:1;
bool override_gid:1;
bool dynperm:1;
bool noperm:1;
bool no_psx_acl:1; /* set if posix acl support should be disabled */
bool cifs_acl:1;
bool backupuid_specified; /* mount option backupuid is specified */
bool backupgid_specified; /* mount option backupgid is specified */
bool no_xattr:1; /* set if xattr (EA) support should be disabled*/
bool server_ino:1; /* use inode numbers from server ie UniqueId */
bool direct_io:1;
bool strict_io:1; /* strict cache behavior */
bool remap:1; /* set to remap seven reserved chars in filenames */
bool posix_paths:1; /* unset to not ask for posix pathnames. */
bool no_linux_ext:1;
bool sfu_emul:1;
bool nullauth:1; /* attempt to authenticate with null user */
bool nocase:1; /* request case insensitive filenames */
bool nobrl:1; /* disable sending byte range locks to srv */
bool mand_lock:1; /* send mandatory not posix byte range lock reqs */
bool seal:1; /* request transport encryption on share */
bool nodfs:1; /* Do not request DFS, even if available */
bool local_lease:1; /* check leases only on local system, not remote */
bool noblocksnd:1;
bool noautotune:1;
bool nostrictsync:1; /* do not force expensive SMBflush on every sync */
bool fsc:1; /* enable fscache */
bool mfsymlinks:1; /* use Minshall+French Symlinks */
bool multiuser:1;
bool rwpidforward:1; /* pid forward for read/write operations */
unsigned int rsize;
unsigned int wsize;
bool sockopt_tcp_nodelay:1;
unsigned short int port;
unsigned long actimeo; /* attribute cache timeout (jiffies) */
char *prepath;
struct sockaddr_storage srcaddr; /* allow binding to a local IP */
struct nls_table *local_nls;
};
struct cifs_mnt_data {
struct cifs_sb_info *cifs_sb;
struct smb_vol *vol;
int flags;
};
struct TCP_Server_Info {
struct list_head tcp_ses_list;
struct list_head smb_ses_list;
int srv_count; /* reference counter */
/* 15 character server name + 0x20 16th byte indicating type = srv */
char server_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
enum statusEnum tcpStatus; /* what we think the status is */
char *hostname; /* hostname portion of UNC string */
struct socket *ssocket;
struct sockaddr_storage dstaddr;
struct sockaddr_storage srcaddr; /* locally bind to this IP */
wait_queue_head_t response_q;
wait_queue_head_t request_q; /* if more than maxmpx to srvr must block*/
struct list_head pending_mid_q;
bool noblocksnd; /* use blocking sendmsg */
bool noautotune; /* do not autotune send buf sizes */
bool tcp_nodelay;
atomic_t inFlight; /* number of requests on the wire to server */
struct mutex srv_mutex;
struct task_struct *tsk;
char server_GUID[16];
char sec_mode;
bool session_estab; /* mark when very first sess is established */
u16 dialect; /* dialect index that server chose */
enum securityEnum secType;
unsigned int maxReq; /* Clients should submit no more */
/* than maxReq distinct unanswered SMBs to the server when using */
/* multiplexed reads or writes */
unsigned int maxBuf; /* maxBuf specifies the maximum */
/* message size the server can send or receive for non-raw SMBs */
/* maxBuf is returned by SMB NegotiateProtocol so maxBuf is only 0 */
/* when socket is setup (and during reconnect) before NegProt sent */
unsigned int max_rw; /* maxRw specifies the maximum */
/* message size the server can send or receive for */
/* SMB_COM_WRITE_RAW or SMB_COM_READ_RAW. */
unsigned int max_vcs; /* maximum number of smb sessions, at least
those that can be specified uniquely with
vcnumbers */
int capabilities; /* allow selective disabling of caps by smb sess */
int timeAdj; /* Adjust for difference in server time zone in sec */
__u16 CurrentMid; /* multiplex id - rotating counter */
char cryptkey[CIFS_CRYPTO_KEY_SIZE]; /* used by ntlm, ntlmv2 etc */
/* 16th byte of RFC1001 workstation name is always null */
char workstation_RFC1001_name[RFC1001_NAME_LEN_WITH_NULL];
__u32 sequence_number; /* for signing, protected by srv_mutex */
struct session_key session_key;
unsigned long lstrp; /* when we got last response from this server */
struct cifs_secmech secmech; /* crypto sec mech functs, descriptors */
/* extended security flavors that server supports */
bool sec_ntlmssp; /* supports NTLMSSP */
bool sec_kerberosu2u; /* supports U2U Kerberos */
bool sec_kerberos; /* supports plain Kerberos */
bool sec_mskerberos; /* supports legacy MS Kerberos */
struct delayed_work echo; /* echo ping workqueue job */
#ifdef CONFIG_CIFS_FSCACHE
struct fscache_cookie *fscache; /* client index cache cookie */
#endif
#ifdef CONFIG_CIFS_STATS2
atomic_t inSend; /* requests trying to send */
atomic_t num_waiters; /* blocked waiting to get in sendrecv */
#endif
};
/*
* Session structure. One of these for each uid session with a particular host
*/
struct cifs_ses {
struct list_head smb_ses_list;
struct list_head tcon_list;
struct mutex session_mutex;
struct TCP_Server_Info *server; /* pointer to server info */
int ses_count; /* reference counter */
enum statusEnum status;
unsigned overrideSecFlg; /* if non-zero override global sec flags */
__u16 ipc_tid; /* special tid for connection to IPC share */
__u16 flags;
__u16 vcnum;
char *serverOS; /* name of operating system underlying server */
char *serverNOS; /* name of network operating system of server */
char *serverDomain; /* security realm of server */
int Suid; /* remote smb uid */
uid_t linux_uid; /* overriding owner of files on the mount */
uid_t cred_uid; /* owner of credentials */
int capabilities;
char serverName[SERVER_NAME_LEN_WITH_NULL * 2]; /* BB make bigger for
TCP names - will ipv6 and sctp addresses fit? */
char *user_name;
char *domainName;
char *password;
struct session_key auth_key;
struct ntlmssp_auth *ntlmssp; /* ciphertext, flags, server challenge */
bool need_reconnect:1; /* connection reset, uid now invalid */
};
/* no more than one of the following three session flags may be set */
#define CIFS_SES_NT4 1
#define CIFS_SES_OS2 2
#define CIFS_SES_W9X 4
/* following flag is set for old servers such as OS2 (and Win95?)
which do not negotiate NTLM or POSIX dialects, but instead
negotiate one of the older LANMAN dialects */
#define CIFS_SES_LANMAN 8
/*
* there is one of these for each connection to a resource on a particular
* session
*/
struct cifs_tcon {
struct list_head tcon_list;
int tc_count;
struct list_head openFileList;
struct cifs_ses *ses; /* pointer to session associated with */
char treeName[MAX_TREE_SIZE + 1]; /* UNC name of resource in ASCII */
char *nativeFileSystem;
char *password; /* for share-level security */
__u16 tid; /* The 2 byte tree id */
__u16 Flags; /* optional support bits */
enum statusEnum tidStatus;
#ifdef CONFIG_CIFS_STATS
atomic_t num_smbs_sent;
atomic_t num_writes;
atomic_t num_reads;
atomic_t num_flushes;
atomic_t num_oplock_brks;
atomic_t num_opens;
atomic_t num_closes;
atomic_t num_deletes;
atomic_t num_mkdirs;
atomic_t num_posixopens;
atomic_t num_posixmkdirs;
atomic_t num_rmdirs;
atomic_t num_renames;
atomic_t num_t2renames;
atomic_t num_ffirst;
atomic_t num_fnext;
atomic_t num_fclose;
atomic_t num_hardlinks;
atomic_t num_symlinks;
atomic_t num_locks;
atomic_t num_acl_get;
atomic_t num_acl_set;
#ifdef CONFIG_CIFS_STATS2
unsigned long long time_writes;
unsigned long long time_reads;
unsigned long long time_opens;
unsigned long long time_deletes;
unsigned long long time_closes;
unsigned long long time_mkdirs;
unsigned long long time_rmdirs;
unsigned long long time_renames;
unsigned long long time_t2renames;
unsigned long long time_ffirst;
unsigned long long time_fnext;
unsigned long long time_fclose;
#endif /* CONFIG_CIFS_STATS2 */
__u64 bytes_read;
__u64 bytes_written;
spinlock_t stat_lock;
#endif /* CONFIG_CIFS_STATS */
FILE_SYSTEM_DEVICE_INFO fsDevInfo;
FILE_SYSTEM_ATTRIBUTE_INFO fsAttrInfo; /* ok if fs name truncated */
FILE_SYSTEM_UNIX_INFO fsUnixInfo;
bool ipc:1; /* set if connection to IPC$ eg for RPC/PIPES */
bool retry:1;
bool nocase:1;
bool seal:1; /* transport encryption for this mounted share */
bool unix_ext:1; /* if false disable Linux extensions to CIFS protocol
for this mount even if server would support */
bool local_lease:1; /* check leases (only) on local system not remote */
bool broken_posix_open; /* e.g. Samba server versions < 3.3.2, 3.2.9 */
bool need_reconnect:1; /* connection reset, tid now invalid */
#ifdef CONFIG_CIFS_FSCACHE
u64 resource_id; /* server resource id */
struct fscache_cookie *fscache; /* cookie for share */
#endif
/* BB add field for back pointer to sb struct(s)? */
};
/*
* This is a refcounted and timestamped container for a tcon pointer. The
* container holds a tcon reference. It is considered safe to free one of
* these when the tl_count goes to 0. The tl_time is the time of the last
* "get" on the container.
*/
struct tcon_link {
struct rb_node tl_rbnode;
uid_t tl_uid;
unsigned long tl_flags;
#define TCON_LINK_MASTER 0
#define TCON_LINK_PENDING 1
#define TCON_LINK_IN_TREE 2
unsigned long tl_time;
atomic_t tl_count;
struct cifs_tcon *tl_tcon;
};
extern struct tcon_link *cifs_sb_tlink(struct cifs_sb_info *cifs_sb);
static inline struct cifs_tcon *
tlink_tcon(struct tcon_link *tlink)
{
return tlink->tl_tcon;
}
extern void cifs_put_tlink(struct tcon_link *tlink);
static inline struct tcon_link *
cifs_get_tlink(struct tcon_link *tlink)
{
if (tlink && !IS_ERR(tlink))
atomic_inc(&tlink->tl_count);
return tlink;
}
/* This function is always expected to succeed */
extern struct cifs_tcon *cifs_sb_master_tcon(struct cifs_sb_info *cifs_sb);
/*
* This info hangs off the cifsFileInfo structure, pointed to by llist.
* This is used to track byte stream locks on the file
*/
struct cifsLockInfo {
struct list_head llist; /* pointer to next cifsLockInfo */
__u64 offset;
__u64 length;
__u8 type;
};
/*
* One of these for each open instance of a file
*/
struct cifs_search_info {
loff_t index_of_last_entry;
__u16 entries_in_buffer;
__u16 info_level;
__u32 resume_key;
char *ntwrk_buf_start;
char *srch_entries_start;
char *last_entry;
char *presume_name;
unsigned int resume_name_len;
bool endOfSearch:1;
bool emptyDir:1;
bool unicode:1;
bool smallBuf:1; /* so we know which buf_release function to call */
};
struct cifsFileInfo {
struct list_head tlist; /* pointer to next fid owned by tcon */
struct list_head flist; /* next fid (file instance) for this inode */
unsigned int uid; /* allows finding which FileInfo structure */
__u32 pid; /* process id who opened file */
__u16 netfid; /* file id from remote */
/* BB add lock scope info here if needed */ ;
/* lock scope id (0 if none) */
struct dentry *dentry;
unsigned int f_flags;
struct tcon_link *tlink;
struct mutex lock_mutex;
struct list_head llist; /* list of byte range locks we have. */
bool invalidHandle:1; /* file closed via session abend */
bool oplock_break_cancelled:1;
int count; /* refcount protected by cifs_file_list_lock */
struct mutex fh_mutex; /* prevents reopen race after dead ses*/
struct cifs_search_info srch_inf;
struct slow_work oplock_break; /* slow_work job for oplock breaks */
};
struct cifs_io_parms {
__u16 netfid;
__u32 pid;
__u64 offset;
unsigned int length;
struct cifs_tcon *tcon;
};
/*
* Take a reference on the file private data. Must be called with
* cifs_file_list_lock held.
*/
static inline void cifsFileInfo_get(struct cifsFileInfo *cifs_file)
{
++cifs_file->count;
}
void cifsFileInfo_put(struct cifsFileInfo *cifs_file);
/*
* One of these for each file inode
*/
struct cifsInodeInfo {
struct list_head lockList;
/* BB add in lists for dirty pages i.e. write caching info for oplock */
struct list_head openFileList;
__u32 cifsAttrs; /* e.g. DOS archive bit, sparse, compressed, system */
unsigned long time; /* jiffies of last update/check of inode */
bool clientCanCacheRead:1; /* read oplock */
bool clientCanCacheAll:1; /* read and writebehind oplock */
bool delete_pending:1; /* DELETE_ON_CLOSE is set */
bool invalid_mapping:1; /* pagecache is invalid */
u64 server_eof; /* current file size on server */
u64 uniqueid; /* server inode number */
#ifdef CONFIG_CIFS_FSCACHE
struct fscache_cookie *fscache;
#endif
struct inode vfs_inode;
};
static inline struct cifsInodeInfo *
CIFS_I(struct inode *inode)
{
return container_of(inode, struct cifsInodeInfo, vfs_inode);
}
static inline struct cifs_sb_info *
CIFS_SB(struct super_block *sb)
{
return sb->s_fs_info;
}
static inline char CIFS_DIR_SEP(const struct cifs_sb_info *cifs_sb)
{
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)
return '/';
else
return '\\';
}
#ifdef CONFIG_CIFS_STATS
#define cifs_stats_inc atomic_inc
static inline void cifs_stats_bytes_written(struct cifs_tcon *tcon,
unsigned int bytes)
{
if (bytes) {
spin_lock(&tcon->stat_lock);
tcon->bytes_written += bytes;
spin_unlock(&tcon->stat_lock);
}
}
static inline void cifs_stats_bytes_read(struct cifs_tcon *tcon,
unsigned int bytes)
{
spin_lock(&tcon->stat_lock);
tcon->bytes_read += bytes;
spin_unlock(&tcon->stat_lock);
}
#else
#define cifs_stats_inc(field) do {} while (0)
#define cifs_stats_bytes_written(tcon, bytes) do {} while (0)
#define cifs_stats_bytes_read(tcon, bytes) do {} while (0)
#endif
struct mid_q_entry;
/*
* This is the prototype for the mid callback function. When creating one,
* take special care to avoid deadlocks. Things to bear in mind:
*
* - it will be called by cifsd, with no locks held
* - the mid will be removed from any lists
*/
typedef void (mid_callback_t)(struct mid_q_entry *mid);
/* one of these for every pending CIFS request to the server */
struct mid_q_entry {
struct list_head qhead; /* mids waiting on reply from this server */
__u16 mid; /* multiplex id */
__u16 pid; /* process id */
__u32 sequence_number; /* for CIFS signing */
unsigned long when_alloc; /* when mid was created */
#ifdef CONFIG_CIFS_STATS2
unsigned long when_sent; /* time when smb send finished */
unsigned long when_received; /* when demux complete (taken off wire) */
#endif
mid_callback_t *callback; /* call completion callback */
void *callback_data; /* general purpose pointer for callback */
struct smb_hdr *resp_buf; /* response buffer */
int midState; /* wish this were enum but can not pass to wait_event */
__u8 command; /* smb command code */
bool largeBuf:1; /* if valid response, is pointer to large buf */
bool multiRsp:1; /* multiple trans2 responses for one request */
bool multiEnd:1; /* both received */
};
struct oplock_q_entry {
struct list_head qhead;
struct inode *pinode;
struct cifs_tcon *tcon;
__u16 netfid;
};
/* for pending dnotify requests */
struct dir_notify_req {
struct list_head lhead;
__le16 Pid;
__le16 PidHigh;
__u16 Mid;
__u16 Tid;
__u16 Uid;
__u16 netfid;
__u32 filter; /* CompletionFilter (for multishot) */
int multishot;
struct file *pfile;
};
struct dfs_info3_param {
int flags; /* DFSREF_REFERRAL_SERVER, DFSREF_STORAGE_SERVER*/
int path_consumed;
int server_type;
int ref_flag;
char *path_name;
char *node_name;
};
/*
* common struct for holding inode info when searching for or updating an
* inode with new info
*/
#define CIFS_FATTR_DFS_REFERRAL 0x1
#define CIFS_FATTR_DELETE_PENDING 0x2
#define CIFS_FATTR_NEED_REVAL 0x4
#define CIFS_FATTR_INO_COLLISION 0x8
struct cifs_fattr {
u32 cf_flags;
u32 cf_cifsattrs;
u64 cf_uniqueid;
u64 cf_eof;
u64 cf_bytes;
uid_t cf_uid;
gid_t cf_gid;
umode_t cf_mode;
dev_t cf_rdev;
unsigned int cf_nlink;
unsigned int cf_dtype;
struct timespec cf_atime;
struct timespec cf_mtime;
struct timespec cf_ctime;
};
static inline void free_dfs_info_param(struct dfs_info3_param *param)
{
if (param) {
kfree(param->path_name);
kfree(param->node_name);
kfree(param);
}
}
static inline void free_dfs_info_array(struct dfs_info3_param *param,
int number_of_items)
{
int i;
if ((number_of_items == 0) || (param == NULL))
return;
for (i = 0; i < number_of_items; i++) {
kfree(param[i].path_name);
kfree(param[i].node_name);
}
kfree(param);
}
#define MID_FREE 0
#define MID_REQUEST_ALLOCATED 1
#define MID_REQUEST_SUBMITTED 2
#define MID_RESPONSE_RECEIVED 4
#define MID_RETRY_NEEDED 8 /* session closed while this request out */
#define MID_RESPONSE_MALFORMED 0x10
#define MID_SHUTDOWN 0x20
/* Types of response buffer returned from SendReceive2 */
#define CIFS_NO_BUFFER 0 /* Response buffer not returned */
#define CIFS_SMALL_BUFFER 1
#define CIFS_LARGE_BUFFER 2
#define CIFS_IOVEC 4 /* array of response buffers */
/* Type of Request to SendReceive2 */
#define CIFS_BLOCKING_OP 1 /* operation can block */
#define CIFS_ASYNC_OP 2 /* do not wait for response */
#define CIFS_TIMEOUT_MASK 0x003 /* only one of above set in req */
#define CIFS_LOG_ERROR 0x010 /* log NT STATUS if non-zero */
#define CIFS_LARGE_BUF_OP 0x020 /* large request buffer */
#define CIFS_NO_RESP 0x040 /* no response buffer required */
/* Security Flags: indicate type of session setup needed */
#define CIFSSEC_MAY_SIGN 0x00001
#define CIFSSEC_MAY_NTLM 0x00002
#define CIFSSEC_MAY_NTLMV2 0x00004
#define CIFSSEC_MAY_KRB5 0x00008
#ifdef CONFIG_CIFS_WEAK_PW_HASH
#define CIFSSEC_MAY_LANMAN 0x00010
#define CIFSSEC_MAY_PLNTXT 0x00020
#else
#define CIFSSEC_MAY_LANMAN 0
#define CIFSSEC_MAY_PLNTXT 0
#endif /* weak passwords */
#define CIFSSEC_MAY_SEAL 0x00040 /* not supported yet */
#define CIFSSEC_MAY_NTLMSSP 0x00080 /* raw ntlmssp with ntlmv2 */
#define CIFSSEC_MUST_SIGN 0x01001
/* note that only one of the following can be set so the
result of setting MUST flags more than once will be to
require use of the stronger protocol */
#define CIFSSEC_MUST_NTLM 0x02002
#define CIFSSEC_MUST_NTLMV2 0x04004
#define CIFSSEC_MUST_KRB5 0x08008
#ifdef CONFIG_CIFS_WEAK_PW_HASH
#define CIFSSEC_MUST_LANMAN 0x10010
#define CIFSSEC_MUST_PLNTXT 0x20020
#ifdef CONFIG_CIFS_UPCALL
#define CIFSSEC_MASK 0xBF0BF /* allows weak security but also krb5 */
#else
#define CIFSSEC_MASK 0xB70B7 /* current flags supported if weak */
#endif /* UPCALL */
#else /* do not allow weak pw hash */
#ifdef CONFIG_CIFS_UPCALL
#define CIFSSEC_MASK 0x8F08F /* flags supported if no weak allowed */
#else
#define CIFSSEC_MASK 0x87087 /* flags supported if no weak allowed */
#endif /* UPCALL */
#endif /* WEAK_PW_HASH */
#define CIFSSEC_MUST_SEAL 0x40040 /* not supported yet */
#define CIFSSEC_MUST_NTLMSSP 0x80080 /* raw ntlmssp with ntlmv2 */
#define CIFSSEC_DEF (CIFSSEC_MAY_SIGN | CIFSSEC_MAY_NTLM | CIFSSEC_MAY_NTLMV2)
#define CIFSSEC_MAX (CIFSSEC_MUST_SIGN | CIFSSEC_MUST_NTLMV2)
#define CIFSSEC_AUTH_MASK (CIFSSEC_MAY_NTLM | CIFSSEC_MAY_NTLMV2 | CIFSSEC_MAY_LANMAN | CIFSSEC_MAY_PLNTXT | CIFSSEC_MAY_KRB5 | CIFSSEC_MAY_NTLMSSP)
/*
*****************************************************************
* All constants go here
*****************************************************************
*/
#define UID_HASH (16)
/*
* Note that ONE module should define _DECLARE_GLOBALS_HERE to cause the
* following to be declared.
*/
/****************************************************************************
* Locking notes. All updates to global variables and lists should be
* protected by spinlocks or semaphores.
*
* Spinlocks
* ---------
* GlobalMid_Lock protects:
* list operations on pending_mid_q and oplockQ
* updates to XID counters, multiplex id and SMB sequence numbers
* cifs_file_list_lock protects:
* list operations on tcp and SMB session lists and tCon lists
* f_owner.lock protects certain per file struct operations
* mapping->page_lock protects certain per page operations
*
* Semaphores
* ----------
* sesSem operations on smb session
* tconSem operations on tree connection
* fh_sem file handle reconnection operations
*
****************************************************************************/
#ifdef DECLARE_GLOBALS_HERE
#define GLOBAL_EXTERN
#else
#define GLOBAL_EXTERN extern
#endif
/*
* the list of TCP_Server_Info structures, ie each of the sockets
* connecting our client to a distinct server (ip address), is
* chained together by cifs_tcp_ses_list. The list of all our SMB
* sessions (and from that the tree connections) can be found
* by iterating over cifs_tcp_ses_list
*/
GLOBAL_EXTERN struct list_head cifs_tcp_ses_list;
/*
* This lock protects the cifs_tcp_ses_list, the list of smb sessions per
* tcp session, and the list of tcon's per smb session. It also protects
* the reference counters for the server, smb session, and tcon. Finally,
* changes to the tcon->tidStatus should be done while holding this lock.
*/
GLOBAL_EXTERN spinlock_t cifs_tcp_ses_lock;
/*
* This lock protects the cifs_file->llist and cifs_file->flist
* list operations, and updates to some flags (cifs_file->invalidHandle)
* It will be moved to either use the tcon->stat_lock or equivalent later.
* If cifs_tcp_ses_lock and the lock below are both needed to be held, then
* the cifs_tcp_ses_lock must be grabbed first and released last.
*/
GLOBAL_EXTERN spinlock_t cifs_file_list_lock;
#ifdef CONFIG_CIFS_DNOTIFY_EXPERIMENTAL /* unused temporarily */
/* Outstanding dir notify requests */
GLOBAL_EXTERN struct list_head GlobalDnotifyReqList;
/* DirNotify response queue */
GLOBAL_EXTERN struct list_head GlobalDnotifyRsp_Q;
#endif /* was needed for dnotify, and will be needed for inotify when VFS fix */
/*
* Global transaction id (XID) information
*/
GLOBAL_EXTERN unsigned int GlobalCurrentXid; /* protected by GlobalMid_Sem */
GLOBAL_EXTERN unsigned int GlobalTotalActiveXid; /* prot by GlobalMid_Sem */
GLOBAL_EXTERN unsigned int GlobalMaxActiveXid; /* prot by GlobalMid_Sem */
GLOBAL_EXTERN spinlock_t GlobalMid_Lock; /* protects above & list operations */
/* on midQ entries */
GLOBAL_EXTERN char Local_System_Name[15];
/*
* Global counters, updated atomically
*/
GLOBAL_EXTERN atomic_t sesInfoAllocCount;
GLOBAL_EXTERN atomic_t tconInfoAllocCount;
GLOBAL_EXTERN atomic_t tcpSesAllocCount;
GLOBAL_EXTERN atomic_t tcpSesReconnectCount;
GLOBAL_EXTERN atomic_t tconInfoReconnectCount;
/* Various Debug counters */
GLOBAL_EXTERN atomic_t bufAllocCount; /* current number allocated */
#ifdef CONFIG_CIFS_STATS2
GLOBAL_EXTERN atomic_t totBufAllocCount; /* total allocated over all time */
GLOBAL_EXTERN atomic_t totSmBufAllocCount;
#endif
GLOBAL_EXTERN atomic_t smBufAllocCount;
GLOBAL_EXTERN atomic_t midCount;
/* Misc globals */
GLOBAL_EXTERN unsigned int multiuser_mount; /* if enabled allows new sessions
to be established on existing mount if we
have the uid/password or Kerberos credential
or equivalent for current user */
GLOBAL_EXTERN unsigned int oplockEnabled;
GLOBAL_EXTERN unsigned int lookupCacheEnabled;
GLOBAL_EXTERN unsigned int global_secflags; /* if on, session setup sent
with more secure ntlmssp2 challenge/resp */
GLOBAL_EXTERN unsigned int sign_CIFS_PDUs; /* enable smb packet signing */
GLOBAL_EXTERN unsigned int linuxExtEnabled;/*enable Linux/Unix CIFS extensions*/
GLOBAL_EXTERN unsigned int CIFSMaxBufSize; /* max size not including hdr */
GLOBAL_EXTERN unsigned int cifs_min_rcv; /* min size of big ntwrk buf pool */
GLOBAL_EXTERN unsigned int cifs_min_small; /* min size of small buf pool */
GLOBAL_EXTERN unsigned int cifs_max_pending; /* MAX requests at once to server*/
/* reconnect after this many failed echo attempts */
GLOBAL_EXTERN unsigned short echo_retries;
#ifdef CONFIG_CIFS_ACL
GLOBAL_EXTERN struct rb_root uidtree;
GLOBAL_EXTERN struct rb_root gidtree;
GLOBAL_EXTERN spinlock_t siduidlock;
GLOBAL_EXTERN spinlock_t sidgidlock;
GLOBAL_EXTERN struct rb_root siduidtree;
GLOBAL_EXTERN struct rb_root sidgidtree;
GLOBAL_EXTERN spinlock_t uidsidlock;
GLOBAL_EXTERN spinlock_t gidsidlock;
#endif /* CONFIG_CIFS_ACL */
extern const struct slow_work_ops cifs_oplock_break_ops;
extern struct workqueue_struct *cifsiod_workqueue;
#endif /* _CIFS_GLOB_H */
| gpl-2.0 |
RPCS3/rpcs3 | rpcs3/Emu/RSX/GL/GLGSRender.h | 6323 | #pragma once
#include "Emu/RSX/GSRender.h"
#include "GLHelpers.h"
#include "GLTexture.h"
#include "GLTextureCache.h"
#include "GLRenderTargets.h"
#include "GLProgramBuffer.h"
#include "GLTextOut.h"
#include "GLOverlays.h"
#include "GLShaderInterpreter.h"
#include <optional>
#include <unordered_map>
#ifdef _WIN32
#pragma comment(lib, "opengl32.lib")
#endif
namespace gl
{
using vertex_cache = rsx::vertex_cache::default_vertex_cache<rsx::vertex_cache::uploaded_range<GLenum>, GLenum>;
using weak_vertex_cache = rsx::vertex_cache::weak_vertex_cache<GLenum>;
using null_vertex_cache = vertex_cache;
using shader_cache = rsx::shaders_cache<void*, GLProgramBuffer>;
struct vertex_upload_info
{
u32 vertex_draw_count;
u32 allocated_vertex_count;
u32 first_vertex;
u32 vertex_index_base;
u32 vertex_index_offset;
u32 persistent_mapping_offset;
u32 volatile_mapping_offset;
std::optional<std::tuple<GLenum, u32> > index_info;
};
struct work_item
{
u32 address_to_flush = 0;
gl::texture_cache::thrashed_set section_data;
volatile bool processed = false;
volatile bool result = false;
volatile bool received = false;
void producer_wait()
{
while (!processed)
{
std::this_thread::yield();
}
received = true;
}
};
struct present_surface_info
{
u32 address;
u32 format;
u32 width;
u32 height;
u32 pitch;
};
}
class GLGSRender : public GSRender, public ::rsx::reports::ZCULL_control
{
private:
GLFragmentProgram m_fragment_prog;
GLVertexProgram m_vertex_prog;
gl::sampler_state m_fs_sampler_states[rsx::limits::fragment_textures_count]; // Fragment textures
gl::sampler_state m_fs_sampler_mirror_states[rsx::limits::fragment_textures_count]; // Alternate views of fragment textures with different format (e.g Depth vs Stencil for D24S8)
gl::sampler_state m_vs_sampler_states[rsx::limits::vertex_textures_count]; // Vertex textures
gl::glsl::program *m_program = nullptr;
u32 m_interpreter_state = 0;
gl::shader_interpreter m_shader_interpreter;
gl_render_targets m_rtts;
gl::texture_cache m_gl_texture_cache;
gl::buffer_view m_persistent_stream_view;
gl::buffer_view m_volatile_stream_view;
std::unique_ptr<gl::texture> m_gl_persistent_stream_buffer;
std::unique_ptr<gl::texture> m_gl_volatile_stream_buffer;
std::unique_ptr<gl::ring_buffer> m_attrib_ring_buffer;
std::unique_ptr<gl::ring_buffer> m_fragment_constants_buffer;
std::unique_ptr<gl::ring_buffer> m_transform_constants_buffer;
std::unique_ptr<gl::ring_buffer> m_fragment_env_buffer;
std::unique_ptr<gl::ring_buffer> m_vertex_env_buffer;
std::unique_ptr<gl::ring_buffer> m_texture_parameters_buffer;
std::unique_ptr<gl::ring_buffer> m_vertex_layout_buffer;
std::unique_ptr<gl::ring_buffer> m_index_ring_buffer;
std::unique_ptr<gl::ring_buffer> m_vertex_instructions_buffer;
std::unique_ptr<gl::ring_buffer> m_fragment_instructions_buffer;
std::unique_ptr<gl::ring_buffer> m_raster_env_ring_buffer;
// Identity buffer used to fix broken gl_VertexID on ATI stack
std::unique_ptr<gl::buffer> m_identity_index_buffer;
std::unique_ptr<gl::vertex_cache> m_vertex_cache;
std::unique_ptr<gl::shader_cache> m_shaders_cache;
GLint m_min_texbuffer_alignment = 256;
GLint m_uniform_buffer_offset_align = 256;
GLint m_max_texbuffer_size = 65536;
bool manually_flush_ring_buffers = false;
gl::text_writer m_text_printer;
gl::ui_overlay_renderer m_ui_renderer;
gl::video_out_calibration_pass m_video_output_pass;
shared_mutex queue_guard;
std::list<gl::work_item> work_queue;
GLProgramBuffer m_prog_buffer;
//buffer
gl::fbo* m_draw_fbo = nullptr;
std::list<gl::framebuffer_holder> m_framebuffer_cache;
gl::fbo m_flip_fbo;
std::unique_ptr<gl::texture> m_flip_tex_color;
//vaos are mandatory for core profile
gl::vao m_vao;
shared_mutex m_sampler_mutex;
atomic_t<bool> m_samplers_dirty = {true};
std::array<std::unique_ptr<rsx::sampled_image_descriptor_base>, rsx::limits::fragment_textures_count> fs_sampler_state = {};
std::array<std::unique_ptr<rsx::sampled_image_descriptor_base>, rsx::limits::vertex_textures_count> vs_sampler_state = {};
std::unordered_map<GLenum, std::unique_ptr<gl::texture>> m_null_textures;
std::vector<u8> m_scratch_buffer;
// Occlusion query type, can be SAMPLES_PASSED or ANY_SAMPLES_PASSED
GLenum m_occlusion_type = GL_ANY_SAMPLES_PASSED;
public:
u64 get_cycles() final;
GLGSRender();
private:
gl::driver_state gl_state;
// Return element to draw and in case of indexed draw index type and offset in index buffer
gl::vertex_upload_info set_vertex_buffer();
rsx::vertex_input_layout m_vertex_layout = {};
void init_buffers(rsx::framebuffer_creation_context context, bool skip_reading = false);
bool load_program();
void load_program_env();
void update_vertex_env(const gl::vertex_upload_info& upload_info);
void update_draw_state();
void load_texture_env();
void bind_texture_env();
gl::texture* get_present_source(gl::present_surface_info* info, const rsx::avconf& avconfig);
public:
void set_viewport();
void set_scissor(bool clip_viewport);
gl::work_item& post_flush_request(u32 address, gl::texture_cache::thrashed_set& flush_data);
bool scaled_image_from_memory(rsx::blit_src_info& src_info, rsx::blit_dst_info& dst_info, bool interpolate) override;
void begin_occlusion_query(rsx::reports::occlusion_query_info* query) override;
void end_occlusion_query(rsx::reports::occlusion_query_info* query) override;
bool check_occlusion_query_status(rsx::reports::occlusion_query_info* query) override;
void get_occlusion_query_result(rsx::reports::occlusion_query_info* query) override;
void discard_occlusion_query(rsx::reports::occlusion_query_info* query) override;
protected:
void clear_surface(u32 arg) override;
void begin() override;
void end() override;
void emit_geometry(u32 sub_index) override;
void on_init_thread() override;
void on_exit() override;
void flip(const rsx::display_flip_info_t& info) override;
void do_local_task(rsx::FIFO_state state) override;
bool on_access_violation(u32 address, bool is_writing) override;
void on_invalidate_memory_range(const utils::address_range &range, rsx::invalidation_cause cause) override;
void notify_tile_unbound(u32 tile) override;
void on_semaphore_acquire_wait() override;
};
| gpl-2.0 |
linusw/linux-bfq | drivers/mmc/host/sdhci-acpi.c | 14265 | /*
* Secure Digital Host Controller Interface ACPI driver.
*
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <linux/dma-mapping.h>
#include <linux/compiler.h>
#include <linux/stddef.h>
#include <linux/bitops.h>
#include <linux/types.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/acpi.h>
#include <linux/pm.h>
#include <linux/pm_runtime.h>
#include <linux/delay.h>
#include <linux/mmc/host.h>
#include <linux/mmc/pm.h>
#include <linux/mmc/slot-gpio.h>
#ifdef CONFIG_X86
#include <asm/cpu_device_id.h>
#include <asm/intel-family.h>
#include <asm/iosf_mbi.h>
#endif
#include "sdhci.h"
enum {
SDHCI_ACPI_SD_CD = BIT(0),
SDHCI_ACPI_RUNTIME_PM = BIT(1),
SDHCI_ACPI_SD_CD_OVERRIDE_LEVEL = BIT(2),
};
struct sdhci_acpi_chip {
const struct sdhci_ops *ops;
unsigned int quirks;
unsigned int quirks2;
unsigned long caps;
unsigned int caps2;
mmc_pm_flag_t pm_caps;
};
struct sdhci_acpi_slot {
const struct sdhci_acpi_chip *chip;
unsigned int quirks;
unsigned int quirks2;
unsigned long caps;
unsigned int caps2;
mmc_pm_flag_t pm_caps;
unsigned int flags;
int (*probe_slot)(struct platform_device *, const char *, const char *);
int (*remove_slot)(struct platform_device *);
};
struct sdhci_acpi_host {
struct sdhci_host *host;
const struct sdhci_acpi_slot *slot;
struct platform_device *pdev;
bool use_runtime_pm;
};
static inline bool sdhci_acpi_flag(struct sdhci_acpi_host *c, unsigned int flag)
{
return c->slot && (c->slot->flags & flag);
}
static void sdhci_acpi_int_hw_reset(struct sdhci_host *host)
{
u8 reg;
reg = sdhci_readb(host, SDHCI_POWER_CONTROL);
reg |= 0x10;
sdhci_writeb(host, reg, SDHCI_POWER_CONTROL);
/* For eMMC, minimum is 1us but give it 9us for good measure */
udelay(9);
reg &= ~0x10;
sdhci_writeb(host, reg, SDHCI_POWER_CONTROL);
/* For eMMC, minimum is 200us but give it 300us for good measure */
usleep_range(300, 1000);
}
static const struct sdhci_ops sdhci_acpi_ops_dflt = {
.set_clock = sdhci_set_clock,
.set_bus_width = sdhci_set_bus_width,
.reset = sdhci_reset,
.set_uhs_signaling = sdhci_set_uhs_signaling,
};
static const struct sdhci_ops sdhci_acpi_ops_int = {
.set_clock = sdhci_set_clock,
.set_bus_width = sdhci_set_bus_width,
.reset = sdhci_reset,
.set_uhs_signaling = sdhci_set_uhs_signaling,
.hw_reset = sdhci_acpi_int_hw_reset,
};
static const struct sdhci_acpi_chip sdhci_acpi_chip_int = {
.ops = &sdhci_acpi_ops_int,
};
#ifdef CONFIG_X86
static bool sdhci_acpi_byt(void)
{
static const struct x86_cpu_id byt[] = {
{ X86_VENDOR_INTEL, 6, INTEL_FAM6_ATOM_SILVERMONT1 },
{}
};
return x86_match_cpu(byt);
}
#define BYT_IOSF_SCCEP 0x63
#define BYT_IOSF_OCP_NETCTRL0 0x1078
#define BYT_IOSF_OCP_TIMEOUT_BASE GENMASK(10, 8)
static void sdhci_acpi_byt_setting(struct device *dev)
{
u32 val = 0;
if (!sdhci_acpi_byt())
return;
if (iosf_mbi_read(BYT_IOSF_SCCEP, MBI_CR_READ, BYT_IOSF_OCP_NETCTRL0,
&val)) {
dev_err(dev, "%s read error\n", __func__);
return;
}
if (!(val & BYT_IOSF_OCP_TIMEOUT_BASE))
return;
val &= ~BYT_IOSF_OCP_TIMEOUT_BASE;
if (iosf_mbi_write(BYT_IOSF_SCCEP, MBI_CR_WRITE, BYT_IOSF_OCP_NETCTRL0,
val)) {
dev_err(dev, "%s write error\n", __func__);
return;
}
dev_dbg(dev, "%s completed\n", __func__);
}
static bool sdhci_acpi_byt_defer(struct device *dev)
{
if (!sdhci_acpi_byt())
return false;
if (!iosf_mbi_available())
return true;
sdhci_acpi_byt_setting(dev);
return false;
}
#else
static inline void sdhci_acpi_byt_setting(struct device *dev)
{
}
static inline bool sdhci_acpi_byt_defer(struct device *dev)
{
return false;
}
#endif
static int bxt_get_cd(struct mmc_host *mmc)
{
int gpio_cd = mmc_gpio_get_cd(mmc);
struct sdhci_host *host = mmc_priv(mmc);
unsigned long flags;
int ret = 0;
if (!gpio_cd)
return 0;
spin_lock_irqsave(&host->lock, flags);
if (host->flags & SDHCI_DEVICE_DEAD)
goto out;
ret = !!(sdhci_readl(host, SDHCI_PRESENT_STATE) & SDHCI_CARD_PRESENT);
out:
spin_unlock_irqrestore(&host->lock, flags);
return ret;
}
static int sdhci_acpi_emmc_probe_slot(struct platform_device *pdev,
const char *hid, const char *uid)
{
struct sdhci_acpi_host *c = platform_get_drvdata(pdev);
struct sdhci_host *host;
if (!c || !c->host)
return 0;
host = c->host;
/* Platform specific code during emmc probe slot goes here */
if (hid && uid && !strcmp(hid, "80860F14") && !strcmp(uid, "1") &&
sdhci_readl(host, SDHCI_CAPABILITIES) == 0x446cc8b2 &&
sdhci_readl(host, SDHCI_CAPABILITIES_1) == 0x00000807)
host->timeout_clk = 1000; /* 1000 kHz i.e. 1 MHz */
return 0;
}
static int sdhci_acpi_sdio_probe_slot(struct platform_device *pdev,
const char *hid, const char *uid)
{
struct sdhci_acpi_host *c = platform_get_drvdata(pdev);
struct sdhci_host *host;
if (!c || !c->host)
return 0;
host = c->host;
/* Platform specific code during sdio probe slot goes here */
return 0;
}
static int sdhci_acpi_sd_probe_slot(struct platform_device *pdev,
const char *hid, const char *uid)
{
struct sdhci_acpi_host *c = platform_get_drvdata(pdev);
struct sdhci_host *host;
if (!c || !c->host || !c->slot)
return 0;
host = c->host;
/* Platform specific code during sd probe slot goes here */
if (hid && !strcmp(hid, "80865ACA")) {
host->mmc_host_ops.get_cd = bxt_get_cd;
host->mmc->caps |= MMC_CAP_AGGRESSIVE_PM;
}
return 0;
}
static const struct sdhci_acpi_slot sdhci_acpi_slot_int_emmc = {
.chip = &sdhci_acpi_chip_int,
.caps = MMC_CAP_8_BIT_DATA | MMC_CAP_NONREMOVABLE |
MMC_CAP_HW_RESET | MMC_CAP_1_8V_DDR |
MMC_CAP_WAIT_WHILE_BUSY,
.caps2 = MMC_CAP2_HC_ERASE_SZ,
.flags = SDHCI_ACPI_RUNTIME_PM,
.quirks = SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC,
.quirks2 = SDHCI_QUIRK2_PRESET_VALUE_BROKEN |
SDHCI_QUIRK2_STOP_WITH_TC |
SDHCI_QUIRK2_CAPS_BIT63_FOR_HS400,
.probe_slot = sdhci_acpi_emmc_probe_slot,
};
static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sdio = {
.quirks = SDHCI_QUIRK_BROKEN_CARD_DETECTION |
SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC,
.quirks2 = SDHCI_QUIRK2_HOST_OFF_CARD_ON,
.caps = MMC_CAP_NONREMOVABLE | MMC_CAP_POWER_OFF_CARD |
MMC_CAP_WAIT_WHILE_BUSY,
.flags = SDHCI_ACPI_RUNTIME_PM,
.pm_caps = MMC_PM_KEEP_POWER,
.probe_slot = sdhci_acpi_sdio_probe_slot,
};
static const struct sdhci_acpi_slot sdhci_acpi_slot_int_sd = {
.flags = SDHCI_ACPI_SD_CD | SDHCI_ACPI_SD_CD_OVERRIDE_LEVEL |
SDHCI_ACPI_RUNTIME_PM,
.quirks = SDHCI_QUIRK_NO_ENDATTR_IN_NOPDESC,
.quirks2 = SDHCI_QUIRK2_CARD_ON_NEEDS_BUS_ON |
SDHCI_QUIRK2_STOP_WITH_TC,
.caps = MMC_CAP_WAIT_WHILE_BUSY,
.probe_slot = sdhci_acpi_sd_probe_slot,
};
static const struct sdhci_acpi_slot sdhci_acpi_slot_qcom_sd_3v = {
.quirks = SDHCI_QUIRK_BROKEN_CARD_DETECTION,
.quirks2 = SDHCI_QUIRK2_NO_1_8_V,
.caps = MMC_CAP_NONREMOVABLE,
};
static const struct sdhci_acpi_slot sdhci_acpi_slot_qcom_sd = {
.quirks = SDHCI_QUIRK_BROKEN_CARD_DETECTION,
.caps = MMC_CAP_NONREMOVABLE,
};
struct sdhci_acpi_uid_slot {
const char *hid;
const char *uid;
const struct sdhci_acpi_slot *slot;
};
static const struct sdhci_acpi_uid_slot sdhci_acpi_uids[] = {
{ "80865ACA", NULL, &sdhci_acpi_slot_int_sd },
{ "80865ACC", NULL, &sdhci_acpi_slot_int_emmc },
{ "80865AD0", NULL, &sdhci_acpi_slot_int_sdio },
{ "80860F14" , "1" , &sdhci_acpi_slot_int_emmc },
{ "80860F14" , "3" , &sdhci_acpi_slot_int_sd },
{ "80860F16" , NULL, &sdhci_acpi_slot_int_sd },
{ "INT33BB" , "2" , &sdhci_acpi_slot_int_sdio },
{ "INT33BB" , "3" , &sdhci_acpi_slot_int_sd },
{ "INT33C6" , NULL, &sdhci_acpi_slot_int_sdio },
{ "INT3436" , NULL, &sdhci_acpi_slot_int_sdio },
{ "INT344D" , NULL, &sdhci_acpi_slot_int_sdio },
{ "PNP0FFF" , "3" , &sdhci_acpi_slot_int_sd },
{ "PNP0D40" },
{ "QCOM8051", NULL, &sdhci_acpi_slot_qcom_sd_3v },
{ "QCOM8052", NULL, &sdhci_acpi_slot_qcom_sd },
{ },
};
static const struct acpi_device_id sdhci_acpi_ids[] = {
{ "80865ACA" },
{ "80865ACC" },
{ "80865AD0" },
{ "80860F14" },
{ "80860F16" },
{ "INT33BB" },
{ "INT33C6" },
{ "INT3436" },
{ "INT344D" },
{ "PNP0D40" },
{ "QCOM8051" },
{ "QCOM8052" },
{ },
};
MODULE_DEVICE_TABLE(acpi, sdhci_acpi_ids);
static const struct sdhci_acpi_slot *sdhci_acpi_get_slot(const char *hid,
const char *uid)
{
const struct sdhci_acpi_uid_slot *u;
for (u = sdhci_acpi_uids; u->hid; u++) {
if (strcmp(u->hid, hid))
continue;
if (!u->uid)
return u->slot;
if (uid && !strcmp(u->uid, uid))
return u->slot;
}
return NULL;
}
static int sdhci_acpi_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
acpi_handle handle = ACPI_HANDLE(dev);
struct acpi_device *device, *child;
struct sdhci_acpi_host *c;
struct sdhci_host *host;
struct resource *iomem;
resource_size_t len;
const char *hid;
const char *uid;
int err;
if (acpi_bus_get_device(handle, &device))
return -ENODEV;
/* Power on the SDHCI controller and its children */
acpi_device_fix_up_power(device);
list_for_each_entry(child, &device->children, node)
acpi_device_fix_up_power(child);
if (acpi_bus_get_status(device) || !device->status.present)
return -ENODEV;
if (sdhci_acpi_byt_defer(dev))
return -EPROBE_DEFER;
hid = acpi_device_hid(device);
uid = device->pnp.unique_id;
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!iomem)
return -ENOMEM;
len = resource_size(iomem);
if (len < 0x100)
dev_err(dev, "Invalid iomem size!\n");
if (!devm_request_mem_region(dev, iomem->start, len, dev_name(dev)))
return -ENOMEM;
host = sdhci_alloc_host(dev, sizeof(struct sdhci_acpi_host));
if (IS_ERR(host))
return PTR_ERR(host);
c = sdhci_priv(host);
c->host = host;
c->slot = sdhci_acpi_get_slot(hid, uid);
c->pdev = pdev;
c->use_runtime_pm = sdhci_acpi_flag(c, SDHCI_ACPI_RUNTIME_PM);
platform_set_drvdata(pdev, c);
host->hw_name = "ACPI";
host->ops = &sdhci_acpi_ops_dflt;
host->irq = platform_get_irq(pdev, 0);
host->ioaddr = devm_ioremap_nocache(dev, iomem->start,
resource_size(iomem));
if (host->ioaddr == NULL) {
err = -ENOMEM;
goto err_free;
}
if (c->slot) {
if (c->slot->probe_slot) {
err = c->slot->probe_slot(pdev, hid, uid);
if (err)
goto err_free;
}
if (c->slot->chip) {
host->ops = c->slot->chip->ops;
host->quirks |= c->slot->chip->quirks;
host->quirks2 |= c->slot->chip->quirks2;
host->mmc->caps |= c->slot->chip->caps;
host->mmc->caps2 |= c->slot->chip->caps2;
host->mmc->pm_caps |= c->slot->chip->pm_caps;
}
host->quirks |= c->slot->quirks;
host->quirks2 |= c->slot->quirks2;
host->mmc->caps |= c->slot->caps;
host->mmc->caps2 |= c->slot->caps2;
host->mmc->pm_caps |= c->slot->pm_caps;
}
host->mmc->caps2 |= MMC_CAP2_NO_PRESCAN_POWERUP;
if (sdhci_acpi_flag(c, SDHCI_ACPI_SD_CD)) {
bool v = sdhci_acpi_flag(c, SDHCI_ACPI_SD_CD_OVERRIDE_LEVEL);
if (mmc_gpiod_request_cd(host->mmc, NULL, 0, v, 0, NULL)) {
dev_warn(dev, "failed to setup card detect gpio\n");
c->use_runtime_pm = false;
}
}
err = sdhci_add_host(host);
if (err)
goto err_free;
if (c->use_runtime_pm) {
pm_runtime_set_active(dev);
pm_suspend_ignore_children(dev, 1);
pm_runtime_set_autosuspend_delay(dev, 50);
pm_runtime_use_autosuspend(dev);
pm_runtime_enable(dev);
}
device_enable_async_suspend(dev);
return 0;
err_free:
sdhci_free_host(c->host);
return err;
}
static int sdhci_acpi_remove(struct platform_device *pdev)
{
struct sdhci_acpi_host *c = platform_get_drvdata(pdev);
struct device *dev = &pdev->dev;
int dead;
if (c->use_runtime_pm) {
pm_runtime_get_sync(dev);
pm_runtime_disable(dev);
pm_runtime_put_noidle(dev);
}
if (c->slot && c->slot->remove_slot)
c->slot->remove_slot(pdev);
dead = (sdhci_readl(c->host, SDHCI_INT_STATUS) == ~0);
sdhci_remove_host(c->host, dead);
sdhci_free_host(c->host);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int sdhci_acpi_suspend(struct device *dev)
{
struct sdhci_acpi_host *c = dev_get_drvdata(dev);
return sdhci_suspend_host(c->host);
}
static int sdhci_acpi_resume(struct device *dev)
{
struct sdhci_acpi_host *c = dev_get_drvdata(dev);
sdhci_acpi_byt_setting(&c->pdev->dev);
return sdhci_resume_host(c->host);
}
#else
#define sdhci_acpi_suspend NULL
#define sdhci_acpi_resume NULL
#endif
#ifdef CONFIG_PM
static int sdhci_acpi_runtime_suspend(struct device *dev)
{
struct sdhci_acpi_host *c = dev_get_drvdata(dev);
return sdhci_runtime_suspend_host(c->host);
}
static int sdhci_acpi_runtime_resume(struct device *dev)
{
struct sdhci_acpi_host *c = dev_get_drvdata(dev);
sdhci_acpi_byt_setting(&c->pdev->dev);
return sdhci_runtime_resume_host(c->host);
}
#endif
static const struct dev_pm_ops sdhci_acpi_pm_ops = {
.suspend = sdhci_acpi_suspend,
.resume = sdhci_acpi_resume,
SET_RUNTIME_PM_OPS(sdhci_acpi_runtime_suspend,
sdhci_acpi_runtime_resume, NULL)
};
static struct platform_driver sdhci_acpi_driver = {
.driver = {
.name = "sdhci-acpi",
.acpi_match_table = sdhci_acpi_ids,
.pm = &sdhci_acpi_pm_ops,
},
.probe = sdhci_acpi_probe,
.remove = sdhci_acpi_remove,
};
module_platform_driver(sdhci_acpi_driver);
MODULE_DESCRIPTION("Secure Digital Host Controller Interface ACPI driver");
MODULE_AUTHOR("Adrian Hunter");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
CORE-POS/IS4C | documentation/doxy/output/fannie/html/class_hourly_sales_report-members.html | 22579 | <!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"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>CORE POS - Fannie: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() {
if ($('.searchresults').length > 0) { searchBox.DOMSearchField().focus(); }
});
</script>
<link rel="search" href="search-opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="CORE POS - Fannie"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">CORE POS - Fannie
</div>
<div id="projectbrief">The CORE POS back end</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.6 -->
<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 Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<div class="left">
<form id="FSearchBox" action="search.php" method="get">
<img id="MSearchSelect" src="search/mag.png" alt=""/>
<input type="text" id="MSearchField" name="query" value="Search" size="20" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"/>
</form>
</div><div class="right"></div>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">HourlySalesReport Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a8c18e6b6be02d2fd3b392dcd4764c3d3">$chart_data_columns</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#abc6fd3e288684d41ae986c26e15ca8fc">$chart_label_column</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a9178f720dfd22f092153e385537e8923">$content_function</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$description</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$discoverable</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$form</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$header</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$header_index</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$multi_counter</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#ab6a53bcdec2ea4b70a9d9efac46b14b4">$multi_report_mode</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$new_tablesorter</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a1f7180336d45b712c8a53e183015f6fc">$no_jquery</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$no_sort_but_style</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$page_set</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a17459f79988e52b4822f2160227e4fdc">$report_cache</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a7a74b79150232a4c9d84e898ae59f2aa">$report_format</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a778a9099f86c69d74b3080023ff28ed2">$report_headers</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$report_set</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$required</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$required_fields</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#af745911d23a57b8cd8252380e2e375e4">$sort_column</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a4e4971e890f1d191957d0bf4c0cd40d5">$sort_direction</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$sortable</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>$themed</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>$title</b> (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>__construct</b>() (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a67220c2c9ab40b44a908b0abe3b3e37f">assign_headers</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>baseUnitTest</b>($phpunit) (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>bodyContent</b>() (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a6c6884feb101ee3bb0b6a50a0ca1ae9f">both_content</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>calculate_footers</b>($data) (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a33e6a022c84174e8da7feafec276dbec">checkDataCache</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a026a5a708f2416b54778d58c0e9507fa">csvLine</a>($row)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#acc1e087bb8912522e7dc76db6a09954c">defaultDescriptionContent</a>($rowcount, $datefields=array())</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a600893788d54f81a5fe9b77c0b8db916">dekey_array</a>($arr)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>draw_page</b>() (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#abecf70ea862f3f873d0fe1c83097e687">drawPage</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a802e2685a4f4cdd3f7a5f0b26ca71cb3">excelFormat</a>($item, $style='')</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_hourly_sales_report.html#aa0bdd68a99f6a34a7bd1b43878b7485e">fetch_report_data</a>()</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>form_content</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a5466978ed93863d1e9547271cab300f8">format</a>($data)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a0d8ee58d5e6679648f530dae760a86bd">formatCheck</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a17b0679b255292887eaf2d1e626b2501">freshenCache</a>($data)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#ab65e0bafcb427e8c98ea5181e6547ea1">getData</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>hasAllFields</b>($fields) (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>hasWarehouseSource</b>() (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>helpContent</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a1b58f9a51964e0041a28c9e7cc5ec47d">htmlLine</a>($row, $header=False)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>javascriptContent</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>META_BLANK</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#aac63168ec254452b9f97ae25d30e05eb">META_BOLD</a></td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>META_CHART_DATA</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>META_COLOR</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>META_REPEAT_HEADERS</b> (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#aa48a14869dc2c94b742ce2658b9834aa">multiContent</a>($data)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>preprocess</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#a84569cf5e732eefc5d09e74336554f40">render_data</a>($data, $headers=array(), $footers=array(), $format='html')</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>report_content</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>report_description_content</b>() (defined in <a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a>)</td><td class="entry"><a class="el" href="class_hourly_sales_report.html">HourlySalesReport</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a149f49976402042f5112aba99f5469cc">report_end_content</a>()</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>requiredFields</b>() (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="class_fannie_report_page.html#a46e068859e901bde5a888884eee74944">select_headers</a>($incrIndex=False)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#aabb05bfbab7ee2686b67932de4ec0bae">setForm</a>(COREPOS\common\mvc\ValueContainer $f)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>singleContent</b>($data) (defined in <a class="el" href="class_fannie_report_page.html">FannieReportPage</a>)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"><span class="mlabel">protected</span></td></tr>
<tr class="even"><td class="entry"><a class="el" href="class_fannie_report_page.html#ade4dad4c4ca8e1e171b4ef09f4459a31">xlsMeta</a>($data)</td><td class="entry"><a class="el" href="class_fannie_report_page.html">FannieReportPage</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Sep 2 2016 11:31:07 for CORE POS - Fannie by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.6
</small></address>
</body>
</html>
| gpl-2.0 |
DmitryDrozdik/ppdorg | docroot/sites/all/modules/custom/ppgetstat/ppcc/plugins/content_types/ppcc_visualization.js | 1739 | // Example taken from http://bl.ocks.org/mbostock/3883245
jQuery( document ).ready(function() {
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 620 - margin.left - margin.right,
height = 330 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select(".core-commits-vizualization").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv(Drupal.settings.ppcc.data, function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Number");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
});
| gpl-2.0 |
harshitamistry/calligraRepository | krita/ui/input/config/kis_key_input_editor.h | 1443 | /*
* This file is part of the KDE project
* Copyright (C) 2013 Arjen Hiemstra <[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.
*/
#ifndef KISKEYINPUTEDITOR_H
#define KISKEYINPUTEDITOR_H
#include <KPushButton>
namespace Ui
{
class KisKeyInputEditor;
}
/**
* \brief An editor widget for a list of keys.
*/
class KisKeyInputEditor : public KPushButton
{
Q_OBJECT
public:
KisKeyInputEditor(QWidget *parent = 0);
~KisKeyInputEditor();
QList<Qt::Key> keys() const;
void setKeys(const QList<Qt::Key> &newKeys);
Qt::MouseButtons buttons() const;
void setButtons(Qt::MouseButtons newButtons);
private Q_SLOTS:
void updateLabel();
private:
class Private;
Private *const d;
};
#endif // KISKEYINPUTEDITOR_H
| gpl-2.0 |
glocalcoop/activist-network | wp-content/plugins/civicrm/civicrm/CRM/Report/Form/Event/ParticipantListing.php | 30656 | <?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2015
* $Id$
*
*/
class CRM_Report_Form_Event_ParticipantListing extends CRM_Report_Form_Event {
protected $_summary = NULL;
protected $_contribField = FALSE;
protected $_lineitemField = FALSE;
protected $_groupFilter = TRUE;
protected $_tagFilter = TRUE;
protected $_balance = FALSE;
protected $activeCampaigns;
protected $_customGroupExtends = array(
'Participant',
'Contact',
'Individual',
'Event',
);
public $_drilldownReport = array('event/income' => 'Link to Detail Report');
/**
*/
/**
*/
public function __construct() {
$this->_autoIncludeIndexedFieldsAsOrderBys = 1;
// Check if CiviCampaign is a) enabled and b) has active campaigns
$config = CRM_Core_Config::singleton();
$campaignEnabled = in_array("CiviCampaign", $config->enableComponents);
if ($campaignEnabled) {
$getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, TRUE, FALSE, TRUE);
$this->activeCampaigns = $getCampaigns['campaigns'];
asort($this->activeCampaigns);
}
$this->_columns = array(
'civicrm_contact' => array(
'dao' => 'CRM_Contact_DAO_Contact',
'fields' => array_merge(array(
// CRM-17115 - to avoid changing report output at this stage re-instate
// old field name for sort name
'sort_name_linked' => array(
'title' => ts('Participant Name'),
'required' => TRUE,
'no_repeat' => TRUE,
'dbAlias' => 'contact_civireport.sort_name',
)),
$this->getBasicContactFields(),
array(
'age_at_event' => array(
'title' => ts('Age at Event'),
'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, event_civireport.start_date)',
),
)
),
'grouping' => 'contact-fields',
'order_bys' => array(
'sort_name' => array(
'title' => ts('Last Name, First Name'),
'default' => '1',
'default_weight' => '0',
'default_order' => 'ASC',
),
'first_name' => array(
'name' => 'first_name',
'title' => ts('First Name'),
),
'gender_id' => array(
'name' => 'gender_id',
'title' => ts('Gender'),
),
'birth_date' => array(
'name' => 'birth_date',
'title' => ts('Birth Date'),
),
'age_at_event' => array(
'name' => 'age_at_event',
'title' => ts('Age at Event'),
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
'filters' => array(
'sort_name' => array(
'title' => ts('Participant Name'),
'operator' => 'like',
),
'gender_id' => array(
'title' => ts('Gender'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
),
'birth_date' => array(
'title' => ts('Birth Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
'contact_type' => array(
'title' => ts('Contact Type'),
),
'contact_sub_type' => array(
'title' => ts('Contact Subtype'),
),
),
),
'civicrm_email' => array(
'dao' => 'CRM_Core_DAO_Email',
'fields' => array(
'email' => array(
'title' => ts('Email'),
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
'filters' => array(
'email' => array(
'title' => ts('Participant E-mail'),
'operator' => 'like',
),
),
),
'civicrm_address' => array(
'dao' => 'CRM_Core_DAO_Address',
'fields' => array(
'street_address' => NULL,
'city' => NULL,
'postal_code' => NULL,
'state_province_id' => array(
'title' => ts('State/Province'),
),
'country_id' => array(
'title' => ts('Country'),
),
),
'grouping' => 'contact-fields',
),
'civicrm_participant' => array(
'dao' => 'CRM_Event_DAO_Participant',
'fields' => array(
'participant_id' => array('title' => 'Participant ID'),
'participant_record' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
),
'event_id' => array(
'default' => TRUE,
'type' => CRM_Utils_Type::T_STRING,
),
'status_id' => array(
'title' => ts('Status'),
'default' => TRUE,
),
'role_id' => array(
'title' => ts('Role'),
'default' => TRUE,
),
'fee_currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'participant_fee_level' => NULL,
'participant_fee_amount' => NULL,
'participant_register_date' => array('title' => ts('Registration Date')),
'total_paid' => array(
'title' => ts('Total Paid'),
'dbAlias' => 'SUM(ft.total_amount)',
'type' => 1024,
),
'balance' => array(
'title' => ts('Balance'),
'dbAlias' => 'participant_civireport.fee_amount - SUM(ft.total_amount)',
'type' => 1024,
),
),
'grouping' => 'event-fields',
'filters' => array(
'event_id' => array(
'name' => 'event_id',
'title' => ts('Event'),
'operatorType' => CRM_Report_Form::OP_ENTITYREF,
'type' => CRM_Utils_Type::T_INT,
'attributes' => array(
'entity' => 'event',
'select' => array('minimumInputLength' => 0),
),
),
'sid' => array(
'name' => 'status_id',
'title' => ts('Participant Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantStatus(NULL, NULL, 'label'),
),
'rid' => array(
'name' => 'role_id',
'title' => ts('Participant Role'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Event_PseudoConstant::participantRole(),
),
'participant_register_date' => array(
'title' => 'Registration Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'fee_currency' => array(
'title' => ts('Fee Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
),
'order_bys' => array(
'participant_register_date' => array(
'title' => ts('Registration Date'),
'default_weight' => '1',
'default_order' => 'ASC',
),
'event_id' => array(
'title' => ts('Event'),
'default_weight' => '1',
'default_order' => 'ASC',
),
),
),
'civicrm_phone' => array(
'dao' => 'CRM_Core_DAO_Phone',
'fields' => array(
'phone' => array(
'title' => ts('Phone'),
'default' => TRUE,
'no_repeat' => TRUE,
),
),
'grouping' => 'contact-fields',
),
'civicrm_event' => array(
'dao' => 'CRM_Event_DAO_Event',
'fields' => array(
'event_type_id' => array('title' => ts('Event Type')),
'event_start_date' => array('title' => ts('Event Start Date')),
),
'grouping' => 'event-fields',
'filters' => array(
'eid' => array(
'name' => 'event_type_id',
'title' => ts('Event Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('event_type'),
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
'operatorType' => CRM_Report_Form::OP_DATE,
),
),
'order_bys' => array(
'event_type_id' => array(
'title' => ts('Event Type'),
'default_weight' => '2',
'default_order' => 'ASC',
),
'event_start_date' => array(
'title' => ts('Event Start Date'),
),
),
),
'civicrm_contribution' => array(
'dao' => 'CRM_Contribute_DAO_Contribution',
'fields' => array(
'contribution_id' => array(
'name' => 'id',
'no_display' => TRUE,
'required' => TRUE,
'csv_display' => TRUE,
'title' => ts('Contribution ID'),
),
'financial_type_id' => array('title' => ts('Financial Type')),
'receive_date' => array('title' => ts('Payment Date')),
'contribution_status_id' => array('title' => ts('Contribution Status')),
'payment_instrument_id' => array('title' => ts('Payment Type')),
'contribution_source' => array(
'name' => 'source',
'title' => ts('Contribution Source'),
),
'currency' => array(
'required' => TRUE,
'no_display' => TRUE,
),
'trxn_id' => NULL,
'fee_amount' => array('title' => ts('Transaction Fee')),
'net_amount' => NULL,
),
'grouping' => 'contrib-fields',
'filters' => array(
'receive_date' => array(
'title' => 'Payment Date',
'operatorType' => CRM_Report_Form::OP_DATE,
),
'financial_type_id' => array(
'title' => ts('Financial Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::financialType(),
),
'currency' => array(
'title' => ts('Contribution Currency'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Core_OptionGroup::values('currencies_enabled'),
'default' => NULL,
'type' => CRM_Utils_Type::T_STRING,
),
'payment_instrument_id' => array(
'title' => ts('Payment Type'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::paymentInstrument(),
),
'contribution_status_id' => array(
'title' => ts('Contribution Status'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => CRM_Contribute_PseudoConstant::contributionStatus(),
'default' => NULL,
),
),
),
'civicrm_line_item' => array(
'dao' => 'CRM_Price_DAO_LineItem',
'grouping' => 'priceset-fields',
'filters' => array(
'price_field_value_id' => array(
'name' => 'price_field_value_id',
'title' => ts('Fee Level'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->getPriceLevels(),
),
),
),
);
$this->_options = array(
'blank_column_begin' => array(
'title' => ts('Blank column at the Begining'),
'type' => 'checkbox',
),
'blank_column_end' => array(
'title' => ts('Blank column at the End'),
'type' => 'select',
'options' => array(
'' => '-select-',
1 => ts('One'),
2 => ts('Two'),
3 => ts('Three'),
),
),
);
// CRM-17115 avoid duplication of sort_name - would be better to standardise name
// & behaviour across reports but trying for no change at this point.
$this->_columns['civicrm_contact']['fields']['sort_name']['no_display'] = TRUE;
// If we have active campaigns add those elements to both the fields and filters
if ($campaignEnabled && !empty($this->activeCampaigns)) {
$this->_columns['civicrm_participant']['fields']['campaign_id'] = array(
'title' => ts('Campaign'),
'default' => 'false',
);
$this->_columns['civicrm_participant']['filters']['campaign_id'] = array(
'title' => ts('Campaign'),
'operatorType' => CRM_Report_Form::OP_MULTISELECT,
'options' => $this->activeCampaigns,
);
$this->_columns['civicrm_participant']['order_bys']['campaign_id'] = array(
'title' => ts('Campaign'),
);
}
$this->_currencyColumn = 'civicrm_participant_fee_currency';
parent::__construct();
}
/**
* Searches database for priceset values.
*
* @return array
*/
public function getPriceLevels() {
$query = "
SELECT CONCAT(cv.label, ' (', ps.title, ')') label, cv.id
FROM civicrm_price_field_value cv
LEFT JOIN civicrm_price_field cf
ON cv.price_field_id = cf.id
LEFT JOIN civicrm_price_set_entity ce
ON ce.price_set_id = cf.price_set_id
LEFT JOIN civicrm_price_set ps
ON ce.price_set_id = ps.id
WHERE ce.entity_table = 'civicrm_event'
ORDER BY cv.label
";
$dao = CRM_Core_DAO::executeQuery($query);
$elements = array();
while ($dao->fetch()) {
$elements[$dao->id] = "$dao->label\n";
}
return $elements;
}
public function preProcess() {
parent::preProcess();
}
public function select() {
$select = array();
$this->_columnHeaders = array();
//add blank column at the Start
if (array_key_exists('options', $this->_params) &&
!empty($this->_params['options']['blank_column_begin'])
) {
$select[] = " '' as blankColumnBegin";
$this->_columnHeaders['blankColumnBegin']['title'] = '_ _ _ _';
}
foreach ($this->_columns as $tableName => $table) {
if ($tableName == 'civicrm_line_item') {
$this->_lineitemField = TRUE;
}
if (array_key_exists('fields', $table)) {
foreach ($table['fields'] as $fieldName => $field) {
if (!empty($field['required']) ||
!empty($this->_params['fields'][$fieldName])
) {
if ($tableName == 'civicrm_contribution') {
$this->_contribField = TRUE;
}
if ($fieldName == 'total_paid' || $fieldName == 'balance') {
$this->_balance = TRUE;
}
$alias = "{$tableName}_{$fieldName}";
$select[] = "{$field['dbAlias']} as $alias";
$this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['no_display'] = CRM_Utils_Array::value('no_display', $field);
$this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
$this->_selectAliases[] = $alias;
}
}
}
}
//add blank column at the end
$blankcols = CRM_Utils_Array::value('blank_column_end', $this->_params);
if ($blankcols) {
for ($i = 1; $i <= $blankcols; $i++) {
$select[] = " '' as blankColumnEnd_{$i}";
$this->_columnHeaders["blank_{$i}"]['title'] = "_ _ _ _";
}
}
$this->_select = "SELECT " . implode(', ', $select) . " ";
}
/**
* @param $fields
* @param $files
* @param $self
*
* @return array
*/
public static function formRule($fields, $files, $self) {
$errors = $grouping = array();
return $errors;
}
public function from() {
$this->_from = "
FROM civicrm_participant {$this->_aliases['civicrm_participant']}
LEFT JOIN civicrm_event {$this->_aliases['civicrm_event']}
ON ({$this->_aliases['civicrm_event']}.id = {$this->_aliases['civicrm_participant']}.event_id ) AND
{$this->_aliases['civicrm_event']}.is_template = 0
LEFT JOIN civicrm_contact {$this->_aliases['civicrm_contact']}
ON ({$this->_aliases['civicrm_participant']}.contact_id = {$this->_aliases['civicrm_contact']}.id )
{$this->_aclFrom}
LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id AND
{$this->_aliases['civicrm_address']}.is_primary = 1
LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id AND
{$this->_aliases['civicrm_email']}.is_primary = 1)
LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id AND
{$this->_aliases['civicrm_phone']}.is_primary = 1
";
if ($this->_contribField) {
$this->_from .= "
LEFT JOIN civicrm_participant_payment pp
ON ({$this->_aliases['civicrm_participant']}.id = pp.participant_id)
LEFT JOIN civicrm_contribution {$this->_aliases['civicrm_contribution']}
ON (pp.contribution_id = {$this->_aliases['civicrm_contribution']}.id)
";
}
if ($this->_lineitemField) {
$this->_from .= "
LEFT JOIN civicrm_line_item line_item_civireport
ON line_item_civireport.entity_table = 'civicrm_participant' AND
line_item_civireport.entity_id = {$this->_aliases['civicrm_participant']}.id AND
line_item_civireport.qty > 0
";
}
if ($this->_balance) {
$this->_from .= "
LEFT JOIN civicrm_entity_financial_trxn eft
ON (eft.entity_id = {$this->_aliases['civicrm_contribution']}.id)
LEFT JOIN civicrm_financial_account fa
ON (fa.account_type_code = 'AR')
LEFT JOIN civicrm_financial_trxn ft
ON (ft.id = eft.financial_trxn_id AND eft.entity_table = 'civicrm_contribution') AND
(ft.to_financial_account_id != fa.id)
";
}
}
public function where() {
$clauses = array();
foreach ($this->_columns as $tableName => $table) {
if (array_key_exists('filters', $table)) {
foreach ($table['filters'] as $fieldName => $field) {
$clause = NULL;
if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
$relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
$from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
$to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
if ($relative || $from || $to) {
$clause = $this->dateClause($field['name'], $relative, $from, $to, $field['type']);
}
}
else {
$op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
if ($fieldName == 'rid') {
$value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
if (!empty($value)) {
$operator = '';
if ($op == 'notin') {
$operator = 'NOT';
}
$regexp = "[[:cntrl:]]*" . implode('[[:>:]]*|[[:<:]]*', $value) . "[[:cntrl:]]*";
$clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
}
$op = NULL;
}
if ($op) {
$clause = $this->whereClause($field,
$op,
CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
);
}
}
if (!empty($clause)) {
$clauses[] = $clause;
}
}
}
}
if (empty($clauses)) {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 ";
}
else {
$this->_where = "WHERE {$this->_aliases['civicrm_participant']}.is_test = 0 AND " .
implode(' AND ', $clauses);
}
if ($this->_aclWhere) {
$this->_where .= " AND {$this->_aclWhere} ";
}
}
public function groupBy() {
$this->_groupBy = "GROUP BY {$this->_aliases['civicrm_participant']}.id";
}
public function postProcess() {
// get ready with post process params
$this->beginPostProcess();
// get the acl clauses built before we assemble the query
$this->buildACLClause($this->_aliases['civicrm_contact']);
// build query
$sql = $this->buildQuery(TRUE);
// build array of result based on column headers. This method also allows
// modifying column headers before using it to build result set i.e $rows.
$rows = array();
$this->buildRows($sql, $rows);
// format result set.
$this->formatDisplay($rows);
// assign variables to templates
$this->doTemplateAssignment($rows);
// do print / pdf / instance stuff if needed
$this->endPostProcess($rows);
}
/**
* @param $rows
* @param $entryFound
* @param $row
* @param int $rowId
* @param $rowNum
* @param $types
*
* @return bool
*/
private function _initBasicRow(&$rows, &$entryFound, $row, $rowId, $rowNum, $types) {
if (!array_key_exists($rowId, $row)) {
return FALSE;
}
$value = $row[$rowId];
if ($value) {
$rows[$rowNum][$rowId] = $types[$value];
}
$entryFound = TRUE;
}
/**
* Alter display of rows.
*
* Iterate through the rows retrieved via SQL and make changes for display purposes,
* such as rendering contacts as links.
*
* @param array $rows
* Rows generated by SQL, with an array for each row.
*/
public function alterDisplay(&$rows) {
$entryFound = FALSE;
$eventType = CRM_Core_OptionGroup::values('event_type');
$financialTypes = CRM_Contribute_PseudoConstant::financialType();
$contributionStatus = CRM_Contribute_PseudoConstant::contributionStatus();
$paymentInstruments = CRM_Contribute_PseudoConstant::paymentInstrument();
foreach ($rows as $rowNum => $row) {
// make count columns point to detail report
// convert display name to links
if (array_key_exists('civicrm_participant_event_id', $row)) {
$eventId = $row['civicrm_participant_event_id'];
if ($eventId) {
$rows[$rowNum]['civicrm_participant_event_id'] = CRM_Event_PseudoConstant::event($eventId, FALSE);
$url = CRM_Report_Utils_Report::getNextUrl('event/income',
'reset=1&force=1&id_op=in&id_value=' . $eventId,
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$rows[$rowNum]['civicrm_participant_event_id_link'] = $url;
$rows[$rowNum]['civicrm_participant_event_id_hover'] = ts("View Event Income Details for this Event");
}
$entryFound = TRUE;
}
// handle event type id
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_event_event_type_id', $rowNum, $eventType);
// handle participant status id
if (array_key_exists('civicrm_participant_status_id', $row)) {
$statusId = $row['civicrm_participant_status_id'];
if ($statusId) {
$rows[$rowNum]['civicrm_participant_status_id'] = CRM_Event_PseudoConstant::participantStatus($statusId, FALSE, 'label');
}
$entryFound = TRUE;
}
// handle participant role id
if (array_key_exists('civicrm_participant_role_id', $row)) {
$roleId = $row['civicrm_participant_role_id'];
if ($roleId) {
$roles = explode(CRM_Core_DAO::VALUE_SEPARATOR, $roleId);
$roleId = array();
foreach ($roles as $role) {
$roleId[$role] = CRM_Event_PseudoConstant::participantRole($role, FALSE);
}
$rows[$rowNum]['civicrm_participant_role_id'] = implode(', ', $roleId);
}
$entryFound = TRUE;
}
// Handel value seperator in Fee Level
if (array_key_exists('civicrm_participant_participant_fee_level', $row)) {
$feeLevel = $row['civicrm_participant_participant_fee_level'];
if ($feeLevel) {
CRM_Event_BAO_Participant::fixEventLevel($feeLevel);
$rows[$rowNum]['civicrm_participant_participant_fee_level'] = $feeLevel;
}
$entryFound = TRUE;
}
// Convert display name to link
$displayName = CRM_Utils_Array::value('civicrm_contact_sort_name_linked', $row);
$cid = CRM_Utils_Array::value('civicrm_contact_id', $row);
$id = CRM_Utils_Array::value('civicrm_participant_participant_record', $row);
if ($displayName && $cid && $id) {
$url = CRM_Report_Utils_Report::getNextUrl('contact/detail',
"reset=1&force=1&id_op=eq&id_value=$cid",
$this->_absoluteUrl, $this->_id, $this->_drilldownReport
);
$viewUrl = CRM_Utils_System::url("civicrm/contact/view/participant",
"reset=1&id=$id&cid=$cid&action=view&context=participant"
);
$contactTitle = ts('View Contact Details');
$participantTitle = ts('View Participant Record');
$rows[$rowNum]['civicrm_contact_sort_name_linked'] = "<a title='$contactTitle' href=$url>$displayName</a>";
if ($this->_outputMode !== 'csv') {
$rows[$rowNum]['civicrm_contact_sort_name_linked'] .=
"<span style='float: right;'><a title='$participantTitle' href=$viewUrl>" .
ts('View') . "</a></span>";
}
$entryFound = TRUE;
}
// Handle country id
if (array_key_exists('civicrm_address_country_id', $row)) {
$countryId = $row['civicrm_address_country_id'];
if ($countryId) {
$rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($countryId, TRUE);
}
$entryFound = TRUE;
}
// Handle state/province id
if (array_key_exists('civicrm_address_state_province_id', $row)) {
$provinceId = $row['civicrm_address_state_province_id'];
if ($provinceId) {
$rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($provinceId, TRUE);
}
$entryFound = TRUE;
}
// Handle employer id
if (array_key_exists('civicrm_contact_employer_id', $row)) {
$employerId = $row['civicrm_contact_employer_id'];
if ($employerId) {
$rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
$url = CRM_Utils_System::url('civicrm/contact/view',
'reset=1&cid=' . $employerId, $this->_absoluteUrl
);
$rows[$rowNum]['civicrm_contact_employer_id_link'] = $url;
$rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for this Contact.');
}
}
// Convert campaign_id to campaign title
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_participant_campaign_id', $rowNum, $this->activeCampaigns);
// handle contribution status
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_contribution_status_id', $rowNum, $contributionStatus);
// handle payment instrument
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_payment_instrument_id', $rowNum, $paymentInstruments);
// handle financial type
$this->_initBasicRow($rows, $entryFound, $row, 'civicrm_contribution_financial_type_id', $rowNum, $financialTypes);
$entryFound = $this->alterDisplayContactFields($row, $rows, $rowNum, 'event/participantListing', 'View Event Income Details') ? TRUE : $entryFound;
// display birthday in the configured custom format
if (array_key_exists('civicrm_contact_birth_date', $row)) {
$birthDate = $row['civicrm_contact_birth_date'];
if ($birthDate) {
$rows[$rowNum]['civicrm_contact_birth_date'] = CRM_Utils_Date::customFormat($birthDate, '%Y%m%d');
}
$entryFound = TRUE;
}
// skip looking further in rows, if first row itself doesn't
// have the column we need
if (!$entryFound) {
break;
}
}
}
}
| gpl-2.0 |
MichaelQQ/Wireshark-PE | plugins/profinet/packet-pn-ptcp.c | 35467 | /* packet-pn-ptcp.c
* Routines for PN-PTCP (PROFINET Precision Time Clock Protocol)
* packet dissection.
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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 <epan/packet.h>
#include <epan/oui.h>
#include <epan/dissectors/packet-dcerpc.h>
#include "packet-pn.h"
void proto_register_pn_ptcp(void);
void proto_reg_handoff_pn_ptcp(void);
static int proto_pn_ptcp = -1;
static int hf_pn_ptcp_header = -1;
static int hf_pn_ptcp_block = -1;
static int hf_pn_ptcp_block_tlvheader = -1;
static int hf_pn_ptcp_res1 = -1;
static int hf_pn_ptcp_res2 = -1;
static int hf_pn_ptcp_delay10ns = -1;
static int hf_pn_ptcp_seq_id = -1;
static int hf_pn_ptcp_delay1ns_byte = -1;
static int hf_pn_ptcp_delay1ns_fup = -1;
static int hf_pn_ptcp_delay1ns = -1;
static int hf_pn_ptcp_tl_length = -1;
static int hf_pn_ptcp_tl_type = -1;
static int hf_pn_ptcp_master_source_address = -1;
static int hf_pn_ptcp_subdomain_uuid = -1;
static int hf_pn_ptcp_port_mac_address = -1;
static int hf_pn_ptcp_t2portrxdelay = -1;
static int hf_pn_ptcp_t3porttxdelay = -1;
static int hf_pn_ptcp_t2timestamp = -1;
static int hf_pn_ptcp_epoch_number = -1;
static int hf_pn_ptcp_seconds = -1;
static int hf_pn_ptcp_nanoseconds = -1;
static int hf_pn_ptcp_flags = -1;
static int hf_pn_ptcp_currentutcoffset = -1;
static int hf_pn_ptcp_master_priority1 = -1;
static int hf_pn_ptcp_master_priority_level = -1;
static int hf_pn_ptcp_master_priority1_res = -1;
static int hf_pn_ptcp_master_priority1_act =-1;
static int hf_pn_ptcp_master_priority2 = -1;
static int hf_pn_ptcp_clock_class = -1;
static int hf_pn_ptcp_clock_accuracy = -1;
static int hf_pn_ptcp_clockvariance = -1;
static int hf_pn_ptcp_oui = -1;
static int hf_pn_ptcp_profinet_subtype = -1;
static int hf_pn_ptcp_irdata_uuid = -1;
static gint ett_pn_ptcp = -1;
static gint ett_pn_ptcp_header = -1;
static gint ett_pn_ptcp_block = -1;
static gint ett_pn_ptcp_block_header = -1;
#define OUI_PROFINET_MULTICAST 0x010ECF /* PROFIBUS Nutzerorganisation e.V. */
#define PN_PTCP_BT_END 0x00
#define PN_PTCP_BT_SUBDOMAIN 0x01
#define PN_PTCP_BT_TIME 0x02
#define PN_PTCP_BT_TIME_EXTENSION 0x03
#define PN_PTCP_BT_MASTER 0x04
#define PN_PTCP_BT_PORT_PARAMETER 0x05
#define PN_PTCP_BT_DELAY_PARAMETER 0x06
#define PN_PTCP_BT_PORT_TIME 0x07
#define PN_PTCP_BT_OPTION 0x7F
#define PN_PTCP_BT_RTDATA 0x7F
static const value_string pn_ptcp_block_type[] = {
{ PN_PTCP_BT_END, "End" },
{ PN_PTCP_BT_SUBDOMAIN, "Subdomain"},
{ PN_PTCP_BT_TIME, "Time"},
{ PN_PTCP_BT_TIME_EXTENSION, "TimeExtension"},
{ PN_PTCP_BT_MASTER, "Master"},
{ PN_PTCP_BT_PORT_PARAMETER, "PortParameter"},
{ PN_PTCP_BT_DELAY_PARAMETER, "DelayParameter"},
{ PN_PTCP_BT_PORT_TIME, "PortTime"},
/*0x08 - 0x7E Reserved */
{ PN_PTCP_BT_OPTION, "Organizationally Specific"},
{ 0, NULL }
};
static const value_string pn_ptcp_oui_vals[] = {
{ OUI_PROFINET, "PROFINET" },
{ OUI_PROFINET_MULTICAST, "PROFINET" },
{ 0, NULL }
};
static const value_string pn_ptcp_master_prio1_vals[] = {
{ 0x00, "Sync slave" },
{ 0x01, "Primary master" },
{ 0x02, "Secondary master" },
{ 0x03, "Reserved" },
{ 0x04, "Reserved" },
{ 0x05, "Reserved" },
{ 0x06, "Reserved" },
{ 0x07, "Reserved" },
{ 0, NULL }
};
static const value_string pn_ptcp_master_prio1_levels[] = {
{ 0x00, "Level 0 (highest)" },
{ 0x01, "Level 1" },
{ 0x02, "Level 2" },
{ 0x03, "Level 3" },
{ 0x04, "Level 4" },
{ 0x05, "Level 5" },
{ 0x06, "Level 6" },
{ 0x07, "Level 7 (lowest)" },
{ 0, NULL }
};
static const value_string pn_ptcp_master_prio1_vals_active[] = {
{ 0x00, "inactive" },
{ 0x01, "active" },
{ 0, NULL }
};
#if 0
static const value_string pn_ptcp_master_prio1_short_vals[] = {
{ 0x01, "Primary" },
{ 0x02, "Secondary" },
{ 0, NULL }
};
#endif
static const value_string pn_ptcp_master_prio2_vals[] = {
{ 0xFF, "Default" },
{ 0, NULL }
};
static const value_string pn_ptcp_clock_class_vals[] = {
{ 0xFF, "Slave-only clock" },
{ 0, NULL }
};
static const value_string pn_ptcp_clock_accuracy_vals[] = {
{ 0x20, "25ns" },
{ 0x21, "100ns (Default)" },
{ 0x22, "250ns" },
{ 0x23, "1us" },
{ 0x24, "2.5us" },
{ 0x25, "10us" },
{ 0x26, "25us" },
{ 0x27, "100us" },
{ 0x28, "250us" },
{ 0x29, "1ms" },
{ 0xFE, "Unknown" },
{ 0, NULL }
};
static const value_string pn_ptcp_profinet_subtype_vals[] = {
{ 0x01, "RTData" },
{ 0, NULL }
};
static int
dissect_PNPTCP_TLVHeader(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item _U_, guint16 *type, guint16 *length)
{
guint16 tl_type;
guint16 tl_length;
/* Type */
dissect_pn_uint16(tvb, offset, pinfo, tree, hf_pn_ptcp_tl_type, &tl_type);
*type = tl_type >> 9;
/* Length */
offset = dissect_pn_uint16(tvb, offset, pinfo, tree, hf_pn_ptcp_tl_length, &tl_length);
*length = tl_length & 0x1FF;
return offset;
}
static int
dissect_PNPTCP_Subdomain(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID)
{
guint8 mac[6];
e_guid_t uuid;
/* MasterSourceAddress */
offset = dissect_pn_mac(tvb, offset, pinfo, tree, hf_pn_ptcp_master_source_address, mac);
/* SubdomainUUID */
offset = dissect_pn_uuid(tvb, offset, pinfo, tree, hf_pn_ptcp_subdomain_uuid, &uuid);
if ((u16FrameID == 0xff00) || (u16FrameID == 0xff01)) {
col_append_fstr(pinfo->cinfo, COL_INFO, ", Master=%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
}
proto_item_append_text(item, ": MasterSource=%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
proto_item_append_text(item, ", Subdomain=%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid.data1, uuid.data2, uuid.data3,
uuid.data4[0], uuid.data4[1],
uuid.data4[2], uuid.data4[3],
uuid.data4[4], uuid.data4[5],
uuid.data4[6], uuid.data4[7]);
return offset;
}
static int
dissect_PNPTCP_Time(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint16 EpochNumber;
guint32 Seconds;
guint32 NanoSeconds;
/* EpochNumber */
offset = dissect_pn_uint16(tvb, offset, pinfo, tree, hf_pn_ptcp_epoch_number, &EpochNumber);
/* Seconds */
offset = dissect_pn_uint32(tvb, offset, pinfo, tree, hf_pn_ptcp_seconds, &Seconds);
/* NanoSeconds */
offset = dissect_pn_uint32(tvb, offset, pinfo, tree, hf_pn_ptcp_nanoseconds, &NanoSeconds);
proto_item_append_text(item, ": Seconds=%u NanoSeconds=%u EpochNumber=%u",
Seconds, NanoSeconds, EpochNumber);
col_append_fstr(pinfo->cinfo, COL_INFO, ", Time: %4us %09uns, Epoch: %u",
Seconds, NanoSeconds, EpochNumber);
return offset;
}
static int
dissect_PNPTCP_TimeExtension(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint16 Flags;
guint16 CurrentUTCOffset;
/* Flags */
offset = dissect_pn_uint16(tvb, offset, pinfo, tree, hf_pn_ptcp_flags, &Flags);
/* CurrentUTCOffset */
offset = dissect_pn_uint16(tvb, offset, pinfo, tree, hf_pn_ptcp_currentutcoffset, &CurrentUTCOffset);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
proto_item_append_text(item, ": Flags=0x%x, CurrentUTCOffset=%u", Flags, CurrentUTCOffset);
return offset;
}
static int
dissect_PNPTCP_Master(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint8 MasterPriority1;
guint8 MasterPriority2;
guint8 ClockClass;
guint8 ClockAccuracy;
gint16 ClockVariance;
/* MasterPriority1 is a bit field */
/* Bit 0 - 2: PTCP_MasterPriority1.Priority */
dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_master_priority1, &MasterPriority1);
/* Bit 3 - 5: PTCP_MasterPriority1.Level */
dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_master_priority_level, &MasterPriority1);
/* Bit 6: PTCP_MasterPriority1.Reserved */
dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_master_priority1_res, &MasterPriority1);
/* Bit 7: PTCP_MasterPriority1.Active */
offset = dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_master_priority1_act, &MasterPriority1);
/* MasterPriority2 */
offset = dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_master_priority2, &MasterPriority2);
/* ClockClass */
offset = dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_clock_class, &ClockClass);
/* ClockAccuracy */
offset = dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_clock_accuracy, &ClockAccuracy);
/* ClockVariance */
offset = dissect_pn_int16(tvb, offset, pinfo, tree, hf_pn_ptcp_clockvariance, &ClockVariance);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
col_append_fstr(pinfo->cinfo, COL_INFO, ", Prio1=\"%s\"",
val_to_str(MasterPriority1 & 0x7, pn_ptcp_master_prio1_vals, "(Reserved: 0x%x)"));
if ((MasterPriority1 & 0x80) == 0) {
proto_item_append_text(item, ": Prio1=\"%s\", Prio2=%s, Clock: Class=\"%s\", Accuracy=%s, Variance=%d",
val_to_str(MasterPriority1 & 0x7, pn_ptcp_master_prio1_vals, "(Reserved: 0x%x)"),
val_to_str(MasterPriority2, pn_ptcp_master_prio2_vals, "(Reserved: 0x%x)"),
val_to_str(ClockClass, pn_ptcp_clock_class_vals, "(Reserved: 0x%x)"),
val_to_str(ClockAccuracy, pn_ptcp_clock_accuracy_vals, "(Reserved: 0x%x)"),
ClockVariance);
}
else {
col_append_str(pinfo->cinfo, COL_INFO, " active");
proto_item_append_text(item, ": Prio1=\"%s\" is active, Prio2=%s, Clock: Class=\"%s\", Accuracy=%s, Variance=%d",
val_to_str(MasterPriority1 & 0x7, pn_ptcp_master_prio1_vals, "(Reserved: 0x%x)"),
val_to_str(MasterPriority2, pn_ptcp_master_prio2_vals, "(Reserved: 0x%x)"),
val_to_str(ClockClass, pn_ptcp_clock_class_vals, "(Reserved: 0x%x)"),
val_to_str(ClockAccuracy, pn_ptcp_clock_accuracy_vals, "(Reserved: 0x%x)"),
ClockVariance);
}
return offset;
}
static int
dissect_PNPTCP_PortParameter(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint32 t2portrxdelay;
guint32 t3porttxdelay;
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
/* T2PortRxDelay */
offset = dissect_pn_uint32(tvb, offset, pinfo, tree, hf_pn_ptcp_t2portrxdelay, &t2portrxdelay);
/* T3PortTxDelay */
offset = dissect_pn_uint32(tvb, offset, pinfo, tree, hf_pn_ptcp_t3porttxdelay, &t3porttxdelay);
proto_item_append_text(item, ": T2PortRxDelay=%uns, T3PortTxDelay=%uns",
t2portrxdelay, t3porttxdelay);
col_append_fstr(pinfo->cinfo, COL_INFO, ", T2Rx=%uns, T3Tx=%uns",
t2portrxdelay, t3porttxdelay);
return offset;
}
static int
dissect_PNPTCP_DelayParameter(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint8 mac[6];
/* PortMACAddress */
offset = dissect_pn_mac(tvb, offset, pinfo, tree, hf_pn_ptcp_port_mac_address, mac);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
proto_item_append_text(item, ": PortMAC=%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
col_append_fstr(pinfo->cinfo, COL_INFO, ", PortMAC=%02x:%02x:%02x:%02x:%02x:%02x",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
return offset;
}
static int
dissect_PNPTCP_PortTime(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item)
{
guint32 t2timestamp;
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
/* T2TimeStamp */
offset = dissect_pn_uint32(tvb, offset, pinfo, tree, hf_pn_ptcp_t2timestamp, &t2timestamp);
proto_item_append_text(item, ": T2TimeStamp=%uns", t2timestamp);
col_append_fstr(pinfo->cinfo, COL_INFO, ", T2TS=%uns", t2timestamp);
return offset;
}
static int
dissect_PNPTCP_Option_PROFINET(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 length)
{
guint8 subType;
e_guid_t uuid;
/* OUI already dissected! */
/* SubType */
offset = dissect_pn_uint8(tvb, offset, pinfo, tree, hf_pn_ptcp_profinet_subtype, &subType);
length -= 1;
switch (subType) {
case 1: /* RTData */
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
/* IRDataUUID */
offset = dissect_pn_uuid(tvb, offset, pinfo, tree, hf_pn_ptcp_irdata_uuid, &uuid);
proto_item_append_text(item, ": IRDataUUID=%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
uuid.data1, uuid.data2, uuid.data3,
uuid.data4[0], uuid.data4[1],
uuid.data4[2], uuid.data4[3],
uuid.data4[4], uuid.data4[5],
uuid.data4[6], uuid.data4[7]);
break;
default:
offset = dissect_pn_undecoded(tvb, offset, pinfo, tree, length);
break;
}
return offset;
}
static int
dissect_PNPTCP_Option(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 length)
{
guint32 oui;
/* verify remaining TLV length */
if (length < 4)
{
/* too short */
offset = dissect_pn_undecoded(tvb, offset, pinfo, tree, length);
return (offset);
}
/* OUI (organizational unique id) */
offset = dissect_pn_oid(tvb, offset, pinfo,tree, hf_pn_ptcp_oui, &oui);
length -= 3;
switch (oui)
{
case OUI_PROFINET:
case OUI_PROFINET_MULTICAST:
proto_item_append_text(item, ": PROFINET");
offset = dissect_PNPTCP_Option_PROFINET(tvb, offset, pinfo, tree, item, length);
break;
default:
/* SubType */
offset = dissect_pn_undecoded(tvb, offset, pinfo, tree, length);
}
return (offset);
}
static int
dissect_PNPTCP_block(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item _U_, gboolean *end, guint16 u16FrameID)
{
guint16 type;
guint16 length;
proto_item *sub_item;
proto_tree *sub_tree;
proto_item *tlvheader_item;
proto_tree *tlvheader_tree;
guint32 u32SubStart;
*end = FALSE;
/* block subtree */
sub_item = proto_tree_add_item(tree, hf_pn_ptcp_block, tvb, offset, 0, ENC_NA);
sub_tree = proto_item_add_subtree(sub_item, ett_pn_ptcp_block);
u32SubStart = offset;
/* tlvheader subtree */
tlvheader_item = proto_tree_add_item(sub_tree, hf_pn_ptcp_block_tlvheader, tvb, offset, 2 /* len */, ENC_NA);
tlvheader_tree = proto_item_add_subtree(tlvheader_item, ett_pn_ptcp_block_header);
offset = dissect_PNPTCP_TLVHeader(tvb, offset, pinfo, tlvheader_tree, sub_item, &type, &length);
proto_item_set_text(sub_item, "%s",
val_to_str(type, pn_ptcp_block_type, "Unknown"));
proto_item_append_text(tlvheader_item, ": Type=%s (%x), Length=%u",
val_to_str(type, pn_ptcp_block_type, "Unknown"), type, length);
switch (type) {
case 0x00: /* End, no content */
*end = TRUE;
break;
case 0x01: /* Subdomain */
dissect_PNPTCP_Subdomain(tvb, offset, pinfo, sub_tree, sub_item, u16FrameID);
break;
case 0x02: /* Time */
dissect_PNPTCP_Time(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x03: /* TimeExtension */
dissect_PNPTCP_TimeExtension(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x04: /* Master */
dissect_PNPTCP_Master(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x05: /* PortParameter */
dissect_PNPTCP_PortParameter(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x06: /* DelayParameter */
dissect_PNPTCP_DelayParameter(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x07: /* PortTime */
dissect_PNPTCP_PortTime(tvb, offset, pinfo, sub_tree, sub_item);
break;
case 0x7F: /* Organizational Specific */
dissect_PNPTCP_Option(tvb, offset, pinfo, sub_tree, sub_item, length);
break;
default:
offset = dissect_pn_undecoded(tvb, offset, pinfo, tree, length);
}
offset += length;
proto_item_set_len(sub_item, offset - u32SubStart);
return offset;
}
static int
dissect_PNPTCP_blocks(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID)
{
gboolean end = FALSE;
/* as long as we have some bytes, try a new block */
while (!end) {
offset = dissect_PNPTCP_block(tvb, offset, pinfo, tree, item, &end, u16FrameID);
}
return offset;
}
static int
dissect_PNPTCP_FollowUpPDU(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID,
const char *name, const char *name_short)
{
proto_item *header_item;
proto_tree *header_tree;
guint16 seq_id;
gint32 delay1ns_fup;
/* dissect the header */
header_item = proto_tree_add_item(tree, hf_pn_ptcp_header, tvb, offset, 20 /* len */, ENC_NA);
header_tree = proto_item_add_subtree(header_item, ett_pn_ptcp_header);
/* Padding 12 bytes */
offset = dissect_pn_padding(tvb, offset, pinfo, header_tree, 12);
/* SequenceID */
offset = dissect_pn_uint16(tvb, offset, pinfo, header_tree, hf_pn_ptcp_seq_id, &seq_id);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, header_tree);
/* Delay1ns_FUP */
offset = dissect_pn_int32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_delay1ns_fup, &delay1ns_fup);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq=%3u, Delay=%11dns", name, seq_id, delay1ns_fup);
proto_item_append_text(item, "%s: Sequence=%u, Delay=%dns", name_short, seq_id, delay1ns_fup);
proto_item_append_text(header_item, ": Sequence=%u, Delay=%dns", seq_id, delay1ns_fup);
/* dissect the TLV blocks */
offset = dissect_PNPTCP_blocks(tvb, offset, pinfo, tree, item, u16FrameID);
return offset;
}
static int
dissect_PNPTCP_RTSyncPDU(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID,
const char *name, const char *name_short)
{
proto_item *header_item;
proto_tree *header_tree;
guint32 res_1;
guint32 res_2;
guint32 delay10ns;
guint16 seq_id;
guint8 delay1ns_8;
guint64 delay1ns_64;
guint32 delay1ns_32;
guint32 delayms;
header_item = proto_tree_add_item(tree, hf_pn_ptcp_header, tvb, offset, 20 /* len */, ENC_NA);
header_tree = proto_item_add_subtree(header_item, ett_pn_ptcp_header);
/* Reserved_1 */
offset = dissect_pn_uint32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_res1, &res_1);
/* Reserved_2 */
offset = dissect_pn_uint32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_res2, &res_2);
/* Delay10ns */
offset = dissect_pn_uint32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_delay10ns, &delay10ns);
/* SequenceID */
offset = dissect_pn_uint16(tvb, offset, pinfo, header_tree, hf_pn_ptcp_seq_id, &seq_id);
/* Delay1ns */
offset = dissect_pn_uint8(tvb, offset, pinfo, header_tree, hf_pn_ptcp_delay1ns_byte, &delay1ns_8);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, header_tree);
/* Delay1ns */
offset = dissect_pn_uint32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_delay1ns, &delay1ns_32);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, tree);
delay1ns_64 = ((guint64) delay10ns) * 10 + delay1ns_8 + delay1ns_32;
delayms = (guint32) (delay1ns_64 / (1000 * 1000));
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq=%3u, Delay=%11" G_GINT64_MODIFIER "uns",
name, seq_id, delay1ns_64);
proto_item_append_text(item, "%s: Sequence=%u, Delay=%" G_GINT64_MODIFIER "uns",
name_short, seq_id, delay1ns_64);
proto_item_append_text(header_item, ": Sequence=%u, Delay=%" G_GINT64_MODIFIER "uns",
seq_id, delay1ns_64);
if (delay1ns_64 != 0)
proto_item_append_text(header_item, " (%u.%03u,%03u,%03u sec)",
delayms / 1000,
delayms % 1000,
(delay10ns % (1000*100)) / 100,
delay10ns % 100 * 10 + delay1ns_8);
/* dissect the PDU */
offset = dissect_PNPTCP_blocks(tvb, offset, pinfo, tree, item, u16FrameID);
return offset;
}
static int
dissect_PNPTCP_AnnouncePDU(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID,
const char *name, const char *name_short)
{
proto_item *header_item;
proto_tree *header_tree;
guint16 seq_id;
/* dissect the header */
header_item = proto_tree_add_item(tree, hf_pn_ptcp_header, tvb, offset, 20 /* len */, ENC_NA);
header_tree = proto_item_add_subtree(header_item, ett_pn_ptcp_header);
/* Padding 12 bytes */
offset = dissect_pn_padding(tvb, offset, pinfo, header_tree, 12);
/* SequenceID */
offset = dissect_pn_uint16(tvb, offset, pinfo, header_tree, hf_pn_ptcp_seq_id, &seq_id);
/* Padding 6 bytes */
offset = dissect_pn_padding(tvb, offset, pinfo, header_tree, 6);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq=%3u", name, seq_id);
proto_item_append_text(item, "%s: Sequence=%u", name_short, seq_id);
proto_item_append_text(header_item, ": Sequence=%u", seq_id);
/* dissect the PDU */
offset = dissect_PNPTCP_blocks(tvb, offset, pinfo, tree, item, u16FrameID);
return offset;
}
static int
dissect_PNPTCP_DelayPDU(tvbuff_t *tvb, int offset,
packet_info *pinfo, proto_tree *tree, proto_item *item, guint16 u16FrameID,
const char *name, const char *name_short)
{
proto_item *header_item;
proto_tree *header_tree;
guint16 seq_id;
guint32 delay1ns;
/* dissect the header */
header_item = proto_tree_add_item(tree, hf_pn_ptcp_header, tvb, offset, 20 /* len */, ENC_NA);
header_tree = proto_item_add_subtree(header_item, ett_pn_ptcp_header);
/* Padding 12 bytes */
offset = dissect_pn_padding(tvb, offset, pinfo, header_tree, 12);
/* SequenceID */
offset = dissect_pn_uint16(tvb, offset, pinfo, header_tree, hf_pn_ptcp_seq_id, &seq_id);
/* Padding */
offset = dissect_pn_align4(tvb, offset, pinfo, header_tree);
/* Delay1ns_FUP */
offset = dissect_pn_uint32(tvb, offset, pinfo, header_tree, hf_pn_ptcp_delay1ns, &delay1ns);
col_append_fstr(pinfo->cinfo, COL_INFO, "%s, Seq=%3u, Delay=%11uns", name, seq_id, delay1ns);
proto_item_append_text(item, "%s: Sequence=%u, Delay=%uns", name_short, seq_id, delay1ns);
proto_item_append_text(header_item, ": Sequence=%u, Delay=%uns", seq_id, delay1ns);
/* dissect the PDU */
offset = dissect_PNPTCP_blocks(tvb, offset, pinfo, tree, item, u16FrameID);
return offset;
}
/* possibly dissect a PN-RT packet (frame ID must be in the appropriate range) */
static gboolean
dissect_PNPTCP_Data_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
/* the tvb will NOT contain the frame_id here, so get it from dissector data! */
guint16 u16FrameID = GPOINTER_TO_UINT(data);
proto_item *item;
proto_tree *ptcp_tree;
int offset = 0;
guint32 u32SubStart;
/* frame id must be in valid range (acyclic Real-Time, PTCP) */
/* 0x0000 - 0x007F: RTSyncPDU (with follow up) */
/* 0x0080 - 0x00FF: RTSyncPDU (without follow up) */
/* 0xFF00 - 0xFF1F: AnnouncePDU */
/* 0xFF20 - 0xFF3F: FollowUpPDU */
/* 0xFF40 - 0xFF5F: Delay...PDU */
if ( ((u16FrameID >= 0x0100) && (u16FrameID < 0xFF00)) || (u16FrameID > 0xFF5F) ) {
/* we are not interested in this packet */
return FALSE;
}
col_set_str(pinfo->cinfo, COL_PROTOCOL, "PN-PTCP");
col_clear(pinfo->cinfo, COL_INFO);
/* subtree for PTCP */
item = proto_tree_add_protocol_format(tree, proto_pn_ptcp, tvb, 0, 0, "PROFINET PTCP, ");
ptcp_tree = proto_item_add_subtree(item, ett_pn_ptcp);
u32SubStart = offset;
switch (u16FrameID) {
/* range 1 (0x0000 - 0x007F) */
/* 0x0000 - 0x001F reserved */
case 0x0020:
offset = dissect_PNPTCP_RTSyncPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"RTSync FU (Clock)", "RTSync FU (Clock)");
break;
case 0x0021:
offset = dissect_PNPTCP_RTSyncPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"RTSync FU (Time)", "RTSync FU (Time)");
break;
/* 0x0022 - 0x007F reserved */
/* range 2 (0x0080 - 0x00FF) */
case 0x0080:
offset = dissect_PNPTCP_RTSyncPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"RTSync (Clock)", "RTSync (Clock)");
break;
case 0x0081:
offset = dissect_PNPTCP_RTSyncPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"RTSync (Time)", "RTSync (Time)");
break;
/* 0x0081 - 0x00FF reserved */
/* range 7 (0xFF00 - 0xFF5F) */
case 0xff00:
offset = dissect_PNPTCP_AnnouncePDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"Announce (Clock)", "Announce (Clock)");
break;
case 0xff01:
offset = dissect_PNPTCP_AnnouncePDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"Announce (Time)", "Announce (Time)");
break;
/* 0xFF02 - 0xFF1F reserved */
case 0xff20:
offset = dissect_PNPTCP_FollowUpPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"FollowUp (Clock)", "FollowUp (Clock)");
break;
case 0xff21:
offset = dissect_PNPTCP_FollowUpPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"FollowUp (Time)", "FollowUp (Time)");
break;
/* 0xFF22 - 0xFF3F reserved */
case 0xff40:
offset = dissect_PNPTCP_DelayPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"DelayReq ", "DelayReq");
break;
case 0xff41:
offset = dissect_PNPTCP_DelayPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"DelayRes ", "DelayRes");
break;
case 0xff42:
offset = dissect_PNPTCP_DelayPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"DelayFuRes ", "DelayFuRes");
break;
case 0xff43:
offset = dissect_PNPTCP_DelayPDU(tvb, offset, pinfo, ptcp_tree, item, u16FrameID,
"DelayRes ", "DelayRes");
break;
/* 0xFF44 - 0xFF5F reserved */
default:
offset = dissect_pn_undecoded(tvb, offset, pinfo, tree, tvb_captured_length_remaining(tvb, offset));
col_append_fstr(pinfo->cinfo, COL_INFO, "Reserved FrameID 0x%04x", u16FrameID);
proto_item_append_text(item, "Reserved FrameID 0x%04x", u16FrameID);
offset += tvb_captured_length_remaining(tvb, offset);
break;
}
proto_item_set_len(item, offset - u32SubStart);
return TRUE;
}
void
proto_register_pn_ptcp (void)
{
static hf_register_info hf[] = {
{ &hf_pn_ptcp_header,
{ "Header", "pn_ptcp.header",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_block,
{ "Block", "pn_ptcp.block",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_block_tlvheader,
{ "TLVHeader", "pn_ptcp.tlvheader",
FT_NONE, BASE_NONE, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_res1,
{ "Reserved 1", "pn_ptcp.res1",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_res2,
{ "Reserved 2", "pn_ptcp.res2",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_delay10ns,
{ "Delay10ns", "pn_ptcp.delay10ns",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_seq_id,
{ "SequenceID", "pn_ptcp.sequence_id",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_delay1ns_byte,
{ "Delay1ns_Byte", "pn_ptcp.delay1ns_byte",
FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_delay1ns,
{ "Delay1ns", "pn_ptcp.delay1ns",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_delay1ns_fup,
{ "Delay1ns_FUP", "pn_ptcp.delay1ns_fup",
FT_INT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_tl_length,
{ "TypeLength.Length", "pn_ptcp.tl_length",
FT_UINT16, BASE_DEC, 0x0, 0x1FF,
NULL, HFILL }},
{ &hf_pn_ptcp_tl_type,
{ "TypeLength.Type", "pn_ptcp.tl_type",
FT_UINT16, BASE_DEC, 0x0, 0xFE00,
NULL, HFILL }},
{ &hf_pn_ptcp_master_source_address,
{ "MasterSourceAddress", "pn_ptcp.master_source_address",
FT_ETHER, BASE_NONE, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_subdomain_uuid,
{ "SubdomainUUID", "pn_ptcp.subdomain_uuid",
FT_GUID, BASE_NONE, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_port_mac_address,
{ "PortMACAddress", "pn_ptcp.port_mac_address",
FT_ETHER, BASE_NONE, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_t2portrxdelay,
{ "T2PortRxDelay (ns)", "pn_ptcp.t2portrxdelay",
FT_UINT32, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_t3porttxdelay,
{ "T3PortTxDelay (ns)", "pn_ptcp.t3porttxdelay",
FT_UINT32, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_t2timestamp,
{ "T2TimeStamp (ns)", "pn_ptcp.t2timestamp",
FT_UINT32, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_epoch_number,
{ "EpochNumber", "pn_ptcp.epoch_number",
FT_UINT16, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_seconds,
{ "Seconds", "pn_ptcp.seconds",
FT_UINT32, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_nanoseconds,
{ "NanoSeconds", "pn_ptcp.nanoseconds",
FT_UINT32, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_flags,
{ "Flags", "pn_ptcp.flags",
FT_UINT16, BASE_HEX, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_currentutcoffset,
{ "CurrentUTCOffset", "pn_ptcp.currentutcoffset",
FT_UINT16, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_master_priority1,
{ "MasterPriority1.Priority", "pn_ptcp.master_priority1_prio",
FT_UINT8, BASE_HEX, VALS(pn_ptcp_master_prio1_vals), 0x07,
NULL, HFILL }},
{ &hf_pn_ptcp_master_priority_level,
{ "MasterPriority1.Level", "pn_ptcp.master_priority1_level",
FT_UINT8, BASE_HEX, VALS(pn_ptcp_master_prio1_levels), 0x38,
NULL, HFILL }},
{ &hf_pn_ptcp_master_priority1_res,
{ "MasterPriority1.Reserved", "pn_ptcp.master_priority1_res",
FT_UINT8, BASE_HEX, 0x0, 0x40,
NULL, HFILL }},
{ &hf_pn_ptcp_master_priority1_act,
{ "MasterPriority1.Active", "pn_ptcp.master_priority1_act",
FT_UINT8, BASE_HEX, VALS(pn_ptcp_master_prio1_vals_active), 0x80,
NULL, HFILL }},
{ &hf_pn_ptcp_master_priority2,
{ "MasterPriority2", "pn_ptcp.master_priority2",
FT_UINT8, BASE_DEC, VALS(pn_ptcp_master_prio2_vals), 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_clock_class,
{ "ClockClass", "pn_ptcp.clock_class",
FT_UINT8, BASE_DEC, VALS(pn_ptcp_clock_class_vals), 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_clock_accuracy,
{ "ClockAccuracy", "pn_ptcp.clock_accuracy",
FT_UINT8, BASE_DEC, VALS(pn_ptcp_clock_accuracy_vals), 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_clockvariance,
{ "ClockVariance", "pn_ptcp.clockvariance",
FT_INT16, BASE_DEC, 0x0, 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_oui,
{ "Organizationally Unique Identifier", "pn_ptcp.oui",
FT_UINT24, BASE_HEX, VALS(pn_ptcp_oui_vals), 0x0,
NULL, HFILL }},
{ &hf_pn_ptcp_profinet_subtype,
{ "Subtype", "pn_ptcp.subtype",
FT_UINT8, BASE_HEX, VALS(pn_ptcp_profinet_subtype_vals), 0x0,
"PROFINET Subtype", HFILL }},
{ &hf_pn_ptcp_irdata_uuid,
{ "IRDataUUID", "pn_ptcp.irdata_uuid",
FT_GUID, BASE_NONE, 0x0, 0x0,
NULL, HFILL }},
};
static gint *ett[] = {
&ett_pn_ptcp,
&ett_pn_ptcp_header,
&ett_pn_ptcp_block,
&ett_pn_ptcp_block_header
};
proto_pn_ptcp = proto_register_protocol ("PROFINET PTCP", "PN-PTCP", "pn_ptcp");
proto_register_field_array (proto_pn_ptcp, hf, array_length (hf));
proto_register_subtree_array (ett, array_length (ett));
}
void
proto_reg_handoff_pn_ptcp (void)
{
/* register ourself as an heuristic pn-rt payload dissector */
heur_dissector_add("pn_rt", dissect_PNPTCP_Data_heur, proto_pn_ptcp);
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| gpl-2.0 |
ArrozAlba/huayra | cxp/reportes/sigesp_cxp_rfs_solicitudes_minfra.php | 37861 | <?php
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// REPORTE: Formato de salida de Solicitud de Pago
// ORGANISMO: MINISTERIO DEL PODER POPULAR PARA LA INFRAESTRUCTURA.
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
session_start();
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
if(!array_key_exists("la_logusr",$_SESSION))
{
print "<script language=JavaScript>";
print "close();";
print "opener.document.form1.submit();";
print "</script>";
}
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_seguridad($as_titulo)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_seguridad
// Access: private
// Arguments: as_titulo // Título del reporte
// Description: función que guarda la seguridad de quien generó el reporte
// Creado Por: Ing. Yesenia Moreno/ Ing. Luis Lang
// Fecha Creación: 11/03/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $io_fun_cxp;
$ls_descripcion="Generó el Reporte ".$as_titulo;
$lb_valido=$io_fun_cxp->uf_load_seguridad_reporte("CXP","sigesp_cxp_p_solicitudpago.php",$ls_descripcion);
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_encabezado_pagina($as_titulo,$as_numsol,$ad_fecregsol,&$io_pdf)
{
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_encabezado_pagina
// Access: private
// Arguments: as_titulo // Título del Reporte
// as_numsol // numero de la solicitud
// ad_fecregsol // fecha de registro de la solicitud
// io_pdf // Instancia de objeto pdf
// Description: Función que imprime los encabezados por página
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 11/03/2007
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_encabezado=$io_pdf->openObject();
$io_pdf->saveState();
$io_pdf->setStrokeColor(0,0,0);
$io_pdf->line(20,40,590,40);
$io_pdf->line(480,655,480,700);
$io_pdf->line(480,677,590,677);
$io_pdf->Rectangle(105,655,485,45);
$io_pdf->addJpegFromFile('../../shared/imagebank/banner_minfra.jpg',20,708,570,50); // Agregar Banner.
$io_pdf->addJpegFromFile('../../shared/imagebank/'.$_SESSION["ls_logo"],20,655,$_SESSION["ls_width"],$_SESSION["ls_height"]); // Agregar Logo
$li_tm=$io_pdf->getTextWidth(11,$as_titulo);
$tm=285-($li_tm/2);
$io_pdf->addText($tm,673,12,$as_titulo); // Agregar el título
$io_pdf->addText(485,685,9,"<b>No.</b> ".$as_numsol); // Agregar el título
$io_pdf->addText(485,663,9,"<b>Fecha</b> ".$ad_fecregsol); // Agregar el título
$io_pdf->addText(540,770,7,date("d/m/Y")); // Agregar la Fecha
$io_pdf->addText(546,764,6,date("h:i a")); // Agregar la Hora
// cuadro inferior
$io_pdf->Rectangle(20,60,570,70);
$io_pdf->line(20,73,590,73);
$io_pdf->line(20,117,590,117);
$io_pdf->line(130,60,130,130);
$io_pdf->line(240,60,240,130);
$io_pdf->line(380,60,380,130);
$io_pdf->addText(40,122,7,"ELABORADO POR"); // Agregar el título
$io_pdf->addText(42,63,7,"FIRMA / SELLO"); // Agregar el título
$io_pdf->addText(157,122,7,"VERIFICADO POR"); // Agregar el título
$io_pdf->addText(145,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->addText(275,122,7,"AUTORIZADO POR"); // Agregar el título
$io_pdf->addText(257,63,7,"ADMINISTRACIÓN Y FINANZAS"); // Agregar el título
$io_pdf->addText(440,122,7,"CONTRALORIA INTERNA"); // Agregar el título
$io_pdf->addText(445,63,7,"FIRMA / SELLO / FECHA"); // Agregar el título
$io_pdf->restoreState();
$io_pdf->closeObject();
$io_pdf->addObject($io_encabezado,'all');
}// end function uf_print_encabezado_pagina
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_cabecera($as_numsol,$as_codigo,$as_nombre,$as_denfuefin,$ad_fecemisol,$as_consol,$as_obssol,
$ai_monsol,$as_monto,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_cabecera
// Access: private
// Arguments: as_numsol // Numero de la Solicitud de Pago
// as_codigo // Codigo del Proveedor / Beneficiario
// as_nombre // Nombre del Proveedor / Beneficiario
// as_denfuefin // Denominacion de la fuente de financiamiento
// ad_fecemisol // Fecha de Emision de la Solicitud
// as_consol // Concepto de la Solicitud
// as_obssol // Observaciones de la Solicitud
// ai_monsol // Monto de la Solicitud
// as_monto // Monto de la Solicitud en letras
// io_pdf // Instancia de objeto pdf
// Description: función que imprime la cabecera
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 17/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$la_data[1]=array('titulo'=>'<b>Beneficiario</b>');
$la_data[2]=array('titulo'=>" ".$as_nombre);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b> Concepto: </b>'.$as_consol);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
$la_data[1]=array('titulo'=>'<b>Monto en Letras: </b>'.$as_monto,);
$la_columnas=array('titulo'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'left','width'=>570))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$la_data[1]=array('titulo'=>'<b>'.$ls_titulo.'</b>','contenido'=>$ai_monsol,);
$la_columnas=array('titulo'=>'',
'contenido'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'shadeCol2'=>array((249/255),(249/255),(249/255)), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>400), // Justificación y ancho de la columna
'contenido'=>array('justification'=>'center','width'=>170))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
unset($la_data);
unset($la_columnas);
unset($la_config);
}// end function uf_print_cabecera
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_recepcion($la_data,$ai_totsubtot,$ai_tottot,$ai_totcar,$ai_totded,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle
// Access: private
// Arguments: la_data // arreglo de información
// ai_totsubtot // acumulado del subtotal
// ai_tottot // acumulado del total
// ai_totcar // acumulado de los cargos
// ai_totded // acumulado de las deducciones
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 20/05/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datatit[1]=array('numrecdoc'=>'<b>Factura</b>','fecemisol'=>'<b>Fecha</b>','subtotdoc'=>'<b>Monto</b>',
'moncardoc'=>'<b>Cargos</b>','mondeddoc'=>'<b>Deducciones</b>','montotdoc'=>'<b>Total</b>');
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre líneas
'shadeCol2'=>array(0.9,0.9,0.9), // Color de la sombra
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'center','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'center','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'center','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatit,$la_columnas,'<b>RECEPCIONES DE DOCUMENTOS</b>',$la_config);
$la_columnas=array('numrecdoc'=>'','fecemisol'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'center','width'=>130), // Justificación y ancho de la columna
'fecemisol'=>array('justification'=>'left','width'=>70), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('numrecdoc'=>'<b>Totales '.$ls_titulo.'</b>','subtotdoc'=>$ai_totsubtot,
'moncardoc'=>$ai_totcar,'mondeddoc'=>$ai_totded,'montotdoc'=>$ai_tottot);
$la_columnas=array('numrecdoc'=>'','subtotdoc'=>'','moncardoc'=>'','mondeddoc'=>'','montotdoc'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('numrecdoc'=>array('justification'=>'right','width'=>200), // Justificación y ancho de la columna
'subtotdoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'moncardoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'mondeddoc'=>array('justification'=>'right','width'=>92), // Justificación y ancho de la columna
'montotdoc'=>array('justification'=>'right','width'=>92))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_spg($aa_data,$ai_totpre,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// ai_totpre // monto total de presupuesto
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle presupuestario
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/04/2006
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_estmodest;
global $ls_tiporeporte;
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_datasercon= array(array('estpro'=>"<b>".$ls_titcuentas."</b>",
'spg_cuenta'=>"<b>Cuenta</b>",
'denominacion'=>"<b>Denominación</b>",
'monto'=>"<b>Total ".$ls_titulo."</b>"));
$la_columna=array('estpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los titulos
'showLines'=>1, // Mostrar Lineas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Minimo de la tabla
'xOrientation'=>'center', // Orientacion de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness'=>0.5,
'cols'=>array('estpro'=>array('justification'=>'center','width'=>165),
'spg_cuenta'=>array('justification'=>'center','width'=>84),
'denominacion'=>array('justification'=>'center','width'=>236),
'monto'=>array('justification'=>'center','width'=>85))); // Justificacion y ancho de la columna
$io_pdf->ezTable($la_datasercon,$la_columna,'<b>DETALLE PRESUPUESTARIO</b>',$la_config);
unset($la_datasercon);
unset($la_columna);
unset($la_config);
$la_columnas=array('codestpro'=>'','spg_cuenta'=>'','denominacion'=>'','monto'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('codestpro'=>array('justification'=>'center','width'=>165), // Justificación y ancho de la columna
'spg_cuenta'=>array('justification'=>'center','width'=>84), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>236), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totpre'=>$ai_totpre);
$la_columnas=array('titulo'=>'','totpre'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>485), // Justificación y ancho de la columna
'totpre'=>array('justification'=>'right','width'=>85))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_detalle_scg($aa_data,$ai_totdeb,$ai_tothab,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: aa_data // arreglo de información
// si_totdeb // total monto debe
// si_tothab // total monto haber
// io_pdf // Instancia de objeto pdf
// Description: función que imprime el detalle contable
// Creado Por: Ing. Yesenia Moreno / Ing. Luis Lang
// Fecha Creación: 27/05/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
global $ls_tiporeporte;
if($ls_tiporeporte==1)
{
$ls_titulo=" Bs.F.";
}
else
{
$ls_titulo=" Bs.";
}
$io_pdf->ezSetDy(-2);
$la_data[1]=array('sc_cuenta'=>'<b>Cuenta</b>','denominacion'=>'<b>Denominacion</b>','mondeb'=>'<b>Debe</b>','monhab'=>'<b>Haber</b>');
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize'=>9, // Tamaño de Letras
'titleFontSize'=>9, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>2, // Sombra entre lineas
'shadeCol2'=>array(0.9,0.9,0.9), // Sombra entre lineas
'width'=>570, // Ancho de la tabla
'maxWidth'=>570, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'center','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'center','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_data,$la_columnas,'<b>DETALLE CONTABLE</b>',$la_config);
unset($la_datatit);
unset($la_columnas);
unset($la_config);
$la_columnas=array('sc_cuenta'=>'','denominacion'=>'','mondeb'=>'','monhab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre lineas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('sc_cuenta'=>array('justification'=>'center','width'=>90), // Justificación y ancho de la columna
'denominacion'=>array('justification'=>'left','width'=>300), // Justificación y ancho de la columna
'mondeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'monhab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($aa_data,$la_columnas,'',$la_config);
$la_datatot[1]=array('titulo'=>'<b>Totales '.$ls_titulo.'</b>','totdeb'=>$ai_totdeb,'tothab'=>$ai_tothab);
$la_columnas=array('titulo'=>'','totdeb'=>'','tothab'=>'');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>1, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>390), // Justificación y ancho de la columna
'totdeb'=>array('justification'=>'right','width'=>90), // Justificación y ancho de la columna
'tothab'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_detalle
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_print_total_bsf($ai_monsolaux,&$io_pdf)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_print_detalle_cuentas
// Access: private
// Arguments: ai_monsolaux // Monto Auxiliar en Bs.F.
// io_pdf // Instancia de objeto pdf
// Description: Funcion que imprime el monto total de la solicitud en Bs.F.
// Creado Por: Ing. Luis Anibal Lang
// Fecha Creación: 26/09/2007
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$io_pdf->ezSetDy(-5);
$la_datatot[1]=array('titulo'=>'<b>Total Bs.F.</b>','monto'=>$ai_monsolaux);
$la_columnas=array('titulo'=>'<b>Factura</b>',
'monto'=>'<b>Total</b>');
$la_config=array('showHeadings'=>0, // Mostrar encabezados
'fontSize' => 9, // Tamaño de Letras
'titleFontSize' => 12, // Tamaño de Letras de los títulos
'showLines'=>0, // Mostrar Líneas
'shaded'=>0, // Sombra entre líneas
'width'=>540, // Ancho de la tabla
'maxWidth'=>540, // Ancho Máximo de la tabla
'xOrientation'=>'center', // Orientación de la tabla
'outerLineThickness'=>0.5,
'innerLineThickness' =>0.5,
'cols'=>array('titulo'=>array('justification'=>'right','width'=>480), // Justificación y ancho de la columna
'monto'=>array('justification'=>'right','width'=>90))); // Justificación y ancho de la columna
$io_pdf->ezTable($la_datatot,$la_columnas,'',$la_config);
}// end function uf_print_total_bsf
//-----------------------------------------------------------------------------------------------------------------------------------
//----------------------------------------------------- Instancia de las clases ------------------------------------------------
require_once("../../shared/ezpdf/class.ezpdf.php");
require_once("../../shared/class_folder/class_funciones.php");
$io_funciones=new class_funciones();
require_once("../class_folder/class_funciones_cxp.php");
$io_fun_cxp=new class_funciones_cxp();
$ls_estmodest=$_SESSION["la_empresa"]["estmodest"];
//Instancio a la clase de conversión de numeros a letras.
include("../../shared/class_folder/class_numero_a_letra.php");
$numalet= new class_numero_a_letra();
//imprime numero con los valore por defecto
//cambia a minusculas
$numalet->setMayusculas(1);
//cambia a femenino
$numalet->setGenero(1);
//cambia moneda
$numalet->setMoneda("Bolivares");
//cambia prefijo
$numalet->setPrefijo("***");
//cambia sufijo
$numalet->setSufijo("***");
if($ls_estmodest==1)
{
$ls_titcuentas="Estructura Presupuestaria";
}
else
{
$ls_titcuentas="Estructura Programatica";
}
//---------------------------------------------------- Parámetros del encabezado -----------------------------------------------
$ls_titulo="<b>SOLICITUD DE ORDEN DE PAGO</b>";
//-------------------------------------------------- Parámetros para Filtar el Reporte -----------------------------------------
$ls_numsol=$io_fun_cxp->uf_obtenervalor_get("numsol","");
$ls_tiporeporte=$io_fun_cxp->uf_obtenervalor_get("tiporeporte",0);
global $ls_tiporeporte;
require_once("../../shared/ezpdf/class.ezpdf.php");
if($ls_tiporeporte==1)
{
require_once("sigesp_cxp_class_reportbsf.php");
$io_report=new sigesp_cxp_class_reportbsf();
}
else
{
require_once("sigesp_cxp_class_report.php");
$io_report=new sigesp_cxp_class_report();
}
//--------------------------------------------------------------------------------------------------------------------------------
$lb_valido=uf_insert_seguridad($ls_titulo); // Seguridad de Reporte
if($lb_valido)
{
$lb_valido=$io_report->uf_select_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido==false) // Existe algún error ó no hay registros
{
print("<script language=JavaScript>");
print(" alert('No hay nada que Reportar');");
print(" close();");
print("</script>");
}
else // Imprimimos el reporte
{
error_reporting(E_ALL);
set_time_limit(1800);
$io_pdf=new Cezpdf('LETTER','portrait'); // Instancia de la clase PDF
$io_pdf->selectFont('../../shared/ezpdf/fonts/Helvetica.afm'); // Seleccionamos el tipo de letra
$io_pdf->ezSetCmMargins(5,5,3.3,3); // Configuración de los margenes en centímetros
$io_pdf->ezStartPageNumbers(570,47,8,'','',1); // Insertar el número de página
$li_totrow=$io_report->DS->getRowCount("numsol");
for($li_i=1;$li_i<=$li_totrow;$li_i++)
{
$ls_numsol=$io_report->DS->data["numsol"][$li_i];
$ls_codpro=$io_report->DS->data["cod_pro"][$li_i];
$ls_cedbene=$io_report->DS->data["ced_bene"][$li_i];
$ls_denfuefin=$io_report->DS->data["denfuefin"][$li_i];
$ls_nombre=$io_report->DS->data["nombre"][$li_i];
$ld_fecemisol=$io_report->DS->data["fecemisol"][$li_i];
$ls_consol=$io_report->DS->data["consol"][$li_i];
$ls_obssol=$io_report->DS->data["obssol"][$li_i];
$li_monsol=$io_report->DS->data["monsol"][$li_i];
$numalet->setNumero($li_monsol);
$ls_monto= $numalet->letra();
$li_monsol=number_format($li_monsol,2,",",".");
$ld_fecemisol=$io_funciones->uf_convertirfecmostrar($ld_fecemisol);
if($ls_codpro!="----------")
{
$ls_codigo=$ls_codpro;
}
else
{
$ls_codigo=$ls_cedbene;
}
/* if($ls_tiporeporte==0)
{
$li_monsolaux=$io_report->DS->data["monsolaux"][$li_i];
$li_monsolaux=number_format($li_monsolaux,2,",",".");
}
*/ uf_print_encabezado_pagina($ls_titulo,$ls_numsol,$ld_fecemisol,&$io_pdf);
uf_print_cabecera($ls_numsol,$ls_codigo,$ls_nombre,$ls_denfuefin,$ld_fecemisol,$ls_consol,$ls_obssol,$li_monsol,$ls_monto,&$io_pdf);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
$io_report->ds_detalle->reset_ds();
$lb_valido=$io_report->uf_select_rec_doc_solicitud($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowdet=$io_report->ds_detalle_rec->getRowCount("numrecdoc");
$la_data="";
$li_totsubtot=0;
$li_tottot=0;
$li_totcar=0;
$li_totded=0;
for($li_s=1;$li_s<=$li_totrowdet;$li_s++)
{
$ls_numrecdoc=trim($io_report->ds_detalle_rec->data["numrecdoc"][$li_s]);
$ld_fecemidoc=trim($io_report->ds_detalle_rec->data["fecemidoc"][$li_s]);
$ls_numdoccomspg=$io_report->ds_detalle_rec->data["numdoccomspg"][$li_s];
$li_mondeddoc=$io_report->ds_detalle_rec->data["mondeddoc"][$li_s];
$li_moncardoc=$io_report->ds_detalle_rec->data["moncardoc"][$li_s];
$li_montotdoc=$io_report->ds_detalle_rec->data["montotdoc"][$li_s];
$li_subtotdoc=($li_montotdoc-$li_moncardoc+$li_mondeddoc);
$li_totsubtot=$li_totsubtot + $li_subtotdoc;
$li_tottot=$li_tottot + $li_montotdoc;
$li_totcar=$li_totcar + $li_moncardoc;
$li_totded=$li_totded + $li_mondeddoc;
$ld_fecemidoc=$io_funciones->uf_convertirfecmostrar($ld_fecemidoc);
$li_mondeddoc=number_format($li_mondeddoc,2,",",".");
$li_moncardoc=number_format($li_moncardoc,2,",",".");
$li_montotdoc=number_format($li_montotdoc,2,",",".");
$li_subtotdoc=number_format($li_subtotdoc,2,",",".");
$la_data[$li_s]=array('numrecdoc'=>$ls_numrecdoc,'fecemisol'=>$ld_fecemidoc,'mondeddoc'=>$li_mondeddoc,
'moncardoc'=>$li_moncardoc,'montotdoc'=>$li_montotdoc,'subtotdoc'=>$li_subtotdoc);
}
$li_totsubtot=number_format($li_totsubtot,2,",",".");
$li_tottot=number_format($li_tottot,2,",",".");
$li_totcar=number_format($li_totcar,2,",",".");
$li_totded=number_format($li_totded,2,",",".");
uf_print_detalle_recepcion($la_data,$li_totsubtot,$li_tottot,$li_totcar,$li_totded,&$io_pdf);
unset($la_data);
////////////////////////// GRID RECEPCIONES DE DOCUMENTOS //////////////////////////////////////
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_spg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowspg=$io_report->ds_detalle_spg->getRowCount("codestpro");
$la_data="";
$li_totpre=0;
for($li_s=1;$li_s<=$li_totrowspg;$li_s++)
{
$ls_codestpro = trim($io_report->ds_detalle_spg->data["codestpro"][$li_s]);
$ls_spgcuenta = trim($io_report->ds_detalle_spg->data["spg_cuenta"][$li_s]);
$ls_denominacion = $io_report->ds_detalle_spg->data["denominacion"][$li_s];
$li_monto = $io_report->ds_detalle_spg->data["monto"][$li_s];
$li_totpre = $li_totpre+$li_monto;
$li_monto=number_format($li_monto,2,",",".");
$io_fun_cxp->uf_formatoprogramatica($ls_codestpro,&$ls_programatica);
$la_data[$li_s]=array('codestpro'=>$ls_programatica,'spg_cuenta'=>$ls_spgcuenta,
'denominacion'=>$ls_denominacion,'monto'=>$li_monto);
}
$li_totpre=number_format($li_totpre,2,",",".");
uf_print_detalle_spg($la_data,$li_totpre,&$io_pdf);
unset($la_data);
}
////////////////////////// GRID DETALLE PRESUPUESTARIO //////////////////////////////////////
////////////////////////// GRID DETALLE CONTABLE //////////////////////////////////////
$lb_valido=$io_report->uf_select_detalle_scg($ls_numsol); // Cargar el DS con los datos del reporte
if($lb_valido)
{
$li_totrowscg=$io_report->ds_detalle_scg->getRowCount("sc_cuenta");
$la_data="";
$li_totdeb=0;
$li_tothab=0;
for($li_s=1;$li_s<=$li_totrowscg;$li_s++)
{
$ls_sccuenta=trim($io_report->ds_detalle_scg->data["sc_cuenta"][$li_s]);
$ls_debhab=trim($io_report->ds_detalle_scg->data["debhab"][$li_s]);
$ls_denominacion=trim($io_report->ds_detalle_scg->data["denominacion"][$li_s]);
$li_monto=$io_report->ds_detalle_scg->data["monto"][$li_s];
if($ls_debhab=="D")
{
$li_montodebe=$li_monto;
$li_montohab="";
$li_totdeb=$li_totdeb+$li_montodebe;
$li_montodebe=number_format($li_montodebe,2,",",".");
}
else
{
$li_montodebe="";
$li_montohab=$li_monto;
$li_tothab=$li_tothab+$li_montohab;
$li_montohab=number_format($li_montohab,2,",",".");
}
$la_data[$li_s]=array('sc_cuenta'=>$ls_sccuenta,'denominacion'=>$ls_denominacion,
'mondeb'=>$li_montodebe,'monhab'=>$li_montohab);
}
$li_totdeb=number_format($li_totdeb,2,",",".");
$li_tothab=number_format($li_tothab,2,",",".");
uf_print_detalle_scg($la_data,$li_totdeb,$li_tothab,&$io_pdf);
unset($la_data);
}
}
}
}
/* if($ls_tiporeporte==0)
{
uf_print_total_bsf($li_monsolaux,&$io_pdf);
}
*/ if($lb_valido) // Si no ocurrio ningún error
{
$io_pdf->ezStopPageNumbers(1,1); // Detenemos la impresión de los números de página
$io_pdf->ezStream(); // Mostramos el reporte
}
else // Si hubo algún error
{
print("<script language=JavaScript>");
print(" alert('Ocurrio un error al generar el reporte. Intente de Nuevo');");
print(" close();");
print("</script>");
}
}
?>
| gpl-2.0 |
paul-chambers/netgear-r7800 | package/qca-ssdk-shell/src/src/fal_uk/fal_nat.c | 8398 | /*
* Copyright (c) 2014, 2015, The Linux Foundation. All rights reserved.
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
* OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "sw.h"
#include "sw_ioctl.h"
#include "fal_nat.h"
#include "fal_uk_if.h"
sw_error_t
fal_nat_add(a_uint32_t dev_id, fal_nat_entry_t * nat_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_ADD, dev_id, (a_uint32_t) nat_entry);
return rv;
}
sw_error_t
fal_nat_del(a_uint32_t dev_id, a_uint32_t del_mode, fal_nat_entry_t * nat_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_DEL, dev_id, del_mode, (a_uint32_t) nat_entry);
return rv;
}
sw_error_t
fal_nat_get(a_uint32_t dev_id, a_uint32_t get_mode, fal_nat_entry_t * nat_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_GET, dev_id, get_mode, (a_uint32_t) nat_entry);
return rv;
}
sw_error_t
fal_nat_next(a_uint32_t dev_id, a_uint32_t next_mode, fal_nat_entry_t * nat_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_NEXT, dev_id, next_mode, (a_uint32_t) nat_entry);
return rv;
}
sw_error_t
fal_nat_counter_bind(a_uint32_t dev_id, a_uint32_t entry_id, a_uint32_t cnt_id, a_bool_t enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_COUNTER_BIND, dev_id, entry_id, cnt_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_napt_add(a_uint32_t dev_id, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_ADD, dev_id, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_napt_del(a_uint32_t dev_id, a_uint32_t del_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_DEL, dev_id, del_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_napt_get(a_uint32_t dev_id, a_uint32_t get_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_GET, dev_id, get_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_napt_next(a_uint32_t dev_id, a_uint32_t next_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_NEXT, dev_id, next_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_napt_counter_bind(a_uint32_t dev_id, a_uint32_t entry_id, a_uint32_t cnt_id, a_bool_t enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_COUNTER_BIND, dev_id, entry_id, cnt_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_flow_add(a_uint32_t dev_id, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_ADD, dev_id, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_flow_del(a_uint32_t dev_id, a_uint32_t del_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_DEL, dev_id, del_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_flow_get(a_uint32_t dev_id, a_uint32_t get_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_GET, dev_id, get_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_flow_next(a_uint32_t dev_id, a_uint32_t next_mode, fal_napt_entry_t * napt_entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_NEXT, dev_id, next_mode, (a_uint32_t) napt_entry);
return rv;
}
sw_error_t
fal_flow_counter_bind(a_uint32_t dev_id, a_uint32_t entry_id, a_uint32_t cnt_id, a_bool_t enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_COUNTER_BIND, dev_id, entry_id, cnt_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_nat_status_set(a_uint32_t dev_id, a_bool_t enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_STATUS_SET, dev_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_nat_status_get(a_uint32_t dev_id, a_bool_t * enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_STATUS_GET, dev_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_nat_hash_mode_set(a_uint32_t dev_id, a_uint32_t mode)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_HASH_MODE_SET, dev_id, mode);
return rv;
}
sw_error_t
fal_nat_hash_mode_get(a_uint32_t dev_id, a_uint32_t * mode)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_HASH_MODE_GET, dev_id, (a_uint32_t) mode);
return rv;
}
sw_error_t
fal_napt_status_set(a_uint32_t dev_id, a_bool_t enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_STATUS_SET, dev_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_napt_status_get(a_uint32_t dev_id, a_bool_t * enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_STATUS_GET, dev_id, (a_uint32_t) enable);
return rv;
}
sw_error_t
fal_napt_mode_set(a_uint32_t dev_id, fal_napt_mode_t mode)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_MODE_SET, dev_id, (a_uint32_t) mode);
return rv;
}
sw_error_t
fal_napt_mode_get(a_uint32_t dev_id, fal_napt_mode_t * mode)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAPT_MODE_GET, dev_id, (a_uint32_t) mode);
return rv;
}
sw_error_t
fal_nat_prv_base_addr_set(a_uint32_t dev_id, fal_ip4_addr_t addr)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_BASE_ADDR_SET, dev_id, (a_uint32_t) addr);
return rv;
}
sw_error_t
fal_nat_prv_base_addr_get(a_uint32_t dev_id, fal_ip4_addr_t * addr)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_BASE_ADDR_GET, dev_id, (a_uint32_t) addr);
return rv;
}
sw_error_t
fal_nat_prv_base_mask_set(a_uint32_t dev_id, fal_ip4_addr_t addr)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_BASE_MASK_SET, dev_id, (a_uint32_t) addr);
return rv;
}
sw_error_t
fal_nat_prv_base_mask_get(a_uint32_t dev_id, fal_ip4_addr_t * addr)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_BASE_MASK_GET, dev_id, (a_uint32_t) addr);
return rv;
}
sw_error_t
fal_nat_prv_addr_mode_set(a_uint32_t dev_id, a_bool_t map_en)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_ADDR_MODE_SET, dev_id, (a_uint32_t) map_en);
return rv;
}
sw_error_t
fal_nat_prv_addr_mode_get(a_uint32_t dev_id, a_bool_t * map_en)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PRV_ADDR_MODE_GET, dev_id, (a_uint32_t) map_en);
return rv;
}
sw_error_t
fal_nat_pub_addr_add(a_uint32_t dev_id, fal_nat_pub_addr_t * entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PUB_ADDR_ENTRY_ADD, dev_id, (a_uint32_t) entry);
return rv;
}
sw_error_t
fal_nat_pub_addr_del(a_uint32_t dev_id, a_uint32_t del_mode, fal_nat_pub_addr_t * entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PUB_ADDR_ENTRY_DEL, dev_id, del_mode, (a_uint32_t) entry);
return rv;
}
sw_error_t
fal_nat_pub_addr_next(a_uint32_t dev_id, a_uint32_t next_mode, fal_nat_pub_addr_t * entry)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_PUB_ADDR_ENTRY_NEXT, dev_id, next_mode, (a_uint32_t) entry);
return rv;
}
sw_error_t
fal_nat_unk_session_cmd_set(a_uint32_t dev_id, fal_fwd_cmd_t cmd)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_UNK_SESSION_CMD_SET, dev_id, (a_uint32_t) cmd);
return rv;
}
sw_error_t
fal_nat_unk_session_cmd_get(a_uint32_t dev_id, fal_fwd_cmd_t * cmd)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_UNK_SESSION_CMD_GET, dev_id, (a_uint32_t) cmd);
return rv;
}
sw_error_t
fal_nat_global_set(a_uint32_t dev_id, a_bool_t enable, a_bool_t sync_cnt_enable)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_NAT_GLOBAL_SET, dev_id, (a_uint32_t) enable, (a_uint32_t) sync_cnt_enable);
return rv;
}
sw_error_t
fal_flow_cookie_set(a_uint32_t dev_id, fal_flow_cookie_t * flow_cookie)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_COOKIE_SET, dev_id, (a_uint32_t) flow_cookie);
return rv;
}
sw_error_t
fal_flow_rfs_set(a_uint32_t dev_id, a_uint8_t action, fal_flow_rfs_t * rfs)
{
sw_error_t rv;
rv = sw_uk_exec(SW_API_FLOW_RFS_SET, dev_id, (a_uint32_t)action, (a_uint32_t)rfs);
return rv;
}
| gpl-2.0 |
skiz/warzone2100 | lib/framework/utf.cpp | 14247 | /*
This file is part of Warzone 2100.
Copyright (C) 2007 Giel van Schijndel
Copyright (C) 2007-2015 Warzone 2100 Project
Warzone 2100 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.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
$Revision$
$Id$
$HeadURL$
*/
/** \file
* Functions to convert between different Unicode Transformation Formats (UTF for short)
*/
#include "utf.h"
#include <assert.h>
#include <stdlib.h>
#if defined(LIB_COMPILE)
# define ASSERT(expr, ...) (assert(expr))
# define debug(part, ...) ((void)0)
#else
# include "debug.h"
#endif
// Assert that non-starting octets are of the form 10xxxxxx
#define ASSERT_NON_START_OCTET(octet) \
assert((octet & 0xC0) == 0x80 && "invalid non-start UTF-8 octet")
// Assert that starting octets are either of the form 0xxxxxxx (ASCII) or 11xxxxxx
#define ASSERT_START_OCTECT(octet) \
assert((octet & 0x80) == 0x00 || (octet & 0xC0) == 0xC0 || !"invalid starting UTF-8 octet")
// Assert that hexadect (16bit sequence) 1 of UTF-16 surrogate pair sequences are of the form 110110XXXXXXXXXX
#define ASSERT_START_HEXADECT(hexadect) \
assert(((hexadect) & 0xD800) == 0xD800 && "invalid first UTF-16 hexadect")
// Assert that hexadect (16bit sequence) 2 of UTF-16 surrogate pair sequences are of the form 110111XXXXXXXXXX
#define ASSERT_FINAL_HEXADECT(hexadect) \
assert(((hexadect) & 0xDC00) == 0xDC00 && "invalid first UTF-16 hexadect")
utf_32_char UTF8DecodeChar(const char *utf8_char, const char **next_char)
{
utf_32_char decoded = '\0';
*next_char = utf8_char;
ASSERT_START_OCTECT(*utf8_char);
// first octect: 0xxxxxxx: 7 bit (ASCII)
if ((*utf8_char & 0x80) == 0x00)
{
// 1 byte long encoding
decoded = *((*next_char)++);
}
// first octect: 110xxxxx: 11 bit
else if ((*utf8_char & 0xe0) == 0xc0)
{
// 2 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
decoded = (*((*next_char)++) & 0x1f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 1110xxxx: 16 bit
else if ((*utf8_char & 0xf0) == 0xe0)
{
// 3 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
decoded = (*((*next_char)++) & 0x0f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
// first octect: 11110xxx: 21 bit
else if ((*utf8_char & 0xf8) == 0xf0)
{
// 4 byte long encoding
ASSERT_NON_START_OCTET(utf8_char[1]);
ASSERT_NON_START_OCTET(utf8_char[2]);
ASSERT_NON_START_OCTET(utf8_char[3]);
decoded = (*((*next_char)++) & 0x07) << 18;
decoded |= (*((*next_char)++) & 0x3f) << 12;
decoded |= (*((*next_char)++) & 0x3f) << 6;
decoded |= (*((*next_char)++) & 0x3f) << 0;
}
else
{
// apparently this character uses more than 21 bit
// this decoder is not developed to cope with those
// characters so error out
ASSERT(!"out-of-range UTF-8 character", "this UTF-8 character is too large (> 21bits) for this UTF-8 decoder and too large to be a valid Unicode codepoint");
}
return decoded;
}
size_t UTF8CharacterCount(const char *utf8_string)
{
size_t length = 0;
while (*utf8_string != '\0')
{
UTF8DecodeChar(utf8_string, &utf8_string);
++length;
}
return length;
}
size_t UTF16CharacterCount(const uint16_t *utf16)
{
size_t length = 0;
while (*utf16)
{
UTF16DecodeChar(utf16, &utf16);
++length;
}
return length;
}
static size_t unicode_utf8_char_length(const utf_32_char unicode_char)
{
// an ASCII character, which uses 7 bit at most, which is one byte in UTF-8
if (unicode_char < 0x00000080)
{
return 1; // stores 7 bits
}
else if (unicode_char < 0x00000800)
{
return 2; // stores 11 bits
}
else if (unicode_char < 0x00010000)
{
return 3; // stores 16 bits
}
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
return 4; // stores 21 bits
}
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
// Dummy value to prevent warnings about missing return from function
return 0;
}
char *UTF8CharacterAtOffset(const char *utf8_string, size_t index)
{
while (*utf8_string != '\0'
&& index != 0)
{
// Move to the next character
UTF8DecodeChar(utf8_string, &utf8_string);
--index;
}
if (*utf8_string == '\0')
{
return NULL;
}
return (char *)utf8_string;
}
/** Encodes a single Unicode character to a UTF-8 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-8. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-8
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-8 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf8_char().
*/
static char *encode_utf8_char(const utf_32_char unicode_char, char *out_char)
{
char *next_char = out_char;
// 7 bits
if (unicode_char < 0x00000080)
{
*(next_char++) = unicode_char;
}
// 11 bits
else if (unicode_char < 0x00000800)
{
// 0xc0 provides the counting bits: 110
// then append the 5 most significant bits
*(next_char++) = 0xc0 | (unicode_char >> 6);
// Put the next 6 bits in a byte of their own
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 16 bits
else if (unicode_char < 0x00010000)
{
// 0xe0 provides the counting bits: 1110
// then append the 4 most significant bits
*(next_char++) = 0xe0 | (unicode_char >> 12);
// Put the next 12 bits in two bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
// 21 bits
/* This encoder can deal with < 0x00200000, but Unicode only ranges
* from 0x0 to 0x10FFFF. Thus we don't accept anything else.
*/
else if (unicode_char < 0x00110000)
{
// 0xf0 provides the counting bits: 11110
// then append the 3 most significant bits
*(next_char++) = 0xf0 | (unicode_char >> 18);
// Put the next 18 bits in three bytes of their own
*(next_char++) = 0x80 | ((unicode_char >> 12) & 0x3f);
*(next_char++) = 0x80 | ((unicode_char >> 6) & 0x3f);
*(next_char++) = 0x80 | (unicode_char & 0x3f);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, so don't accept it.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
utf_32_char UTF16DecodeChar(const utf_16_char *utf16_char, const utf_16_char **next_char)
{
utf_32_char decoded;
*next_char = utf16_char;
// Are we dealing with a surrogate pair
if (*utf16_char >= 0xD800
&& *utf16_char <= 0xDFFF)
{
ASSERT_START_HEXADECT(utf16_char[0]);
ASSERT_FINAL_HEXADECT(utf16_char[1]);
decoded = (*((*next_char)++) & 0x3ff) << 10;
decoded |= *((*next_char)++) & 0x3ff;
decoded += 0x10000;
}
// Not a surrogate pair, so it's a valid Unicode codepoint right away
else
{
decoded = *((*next_char)++);
}
return decoded;
}
/** Encodes a single Unicode character to a UTF-16 encoded string.
*
* \param unicode_char A UTF-32 encoded Unicode codepoint that will be encoded
* into UTF-16. This should be a valid Unicode codepoint
* (i.e. ranging from 0x0 to 0x10FFFF inclusive).
* \param out_char Points to the position in a buffer where the UTF-16
* encoded character can be stored.
*
* \return A pointer pointing to the first byte <em>after</em> the encoded
* UTF-16 sequence. This can be used as the \c out_char parameter for a
* next invocation of encode_utf16_char().
*/
static utf_16_char *encode_utf16_char(const utf_32_char unicode_char, utf_16_char *out_char)
{
utf_16_char *next_char = out_char;
// 16 bits
if (unicode_char < 0x10000)
{
*(next_char++) = unicode_char;
}
else if (unicode_char < 0x110000)
{
const utf_16_char v = unicode_char - 0x10000;
*(next_char++) = 0xD800 | (v >> 10);
*(next_char++) = 0xDC00 | (v & 0x3ff);
ASSERT_START_HEXADECT(out_char[0]);
ASSERT_FINAL_HEXADECT(out_char[1]);
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint is too large (%u > 0x10FFFF) to be a valid Unicode codepoint", (unsigned int)unicode_char);
}
return next_char;
}
static size_t utf16_utf8_buffer_length(const utf_16_char *unicode_string)
{
const utf_16_char *curChar = unicode_string;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
while (*curChar)
{
length += unicode_utf8_char_length(UTF16DecodeChar(curChar, &curChar));
}
return length;
}
char *UTF16toUTF8(const utf_16_char *unicode_string, size_t *nbytes)
{
const utf_16_char *curChar;
const size_t utf8_length = utf16_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
curChar = unicode_string;
while (*curChar)
{
curOutPos = encode_utf8_char(UTF16DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
static size_t utf8_as_utf16_buf_size(const char *utf8_string)
{
const char *curChar = utf8_string;
size_t length = 0;
while (*curChar != '\0')
{
const utf_32_char unicode_char = UTF8DecodeChar(curChar, &curChar);
if (unicode_char < 0x10000)
{
length += 1;
}
else if (unicode_char < 0x110000)
{
length += 2;
}
else
{
/* Apparently this character lies outside the 0x0 - 0x10FFFF
* Unicode range, and UTF-16 cannot cope with that, so error
* out.
*/
ASSERT(!"out-of-range Unicode codepoint", "This Unicode codepoint too large (%u > 0x10FFFF) for the UTF-16 encoding", (unsigned int)unicode_char);
}
}
return length;
}
utf_16_char *UTF8toUTF16(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = utf8_as_utf16_buf_size(utf8_string);
// Allocate memory to hold the UTF-16 encoded string (plus a terminating nul)
utf_16_char *unicode_string = (utf_16_char *)malloc(sizeof(utf_16_char) * (unicode_length + 1));
utf_16_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
curOutPos = encode_utf16_char(UTF8DecodeChar(curChar, &curChar), curOutPos);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_16_char) * (unicode_length + 1);
}
return unicode_string;
}
utf_16_char *UTF16CharacterAtOffset(const utf_16_char *utf16_string, size_t index)
{
while (*utf16_string != '\0'
&& index != 0)
{
// Move to the next character
UTF16DecodeChar(utf16_string, &utf16_string);
--index;
}
if (*utf16_string == '\0')
{
return NULL;
}
return (utf_16_char *)utf16_string;
}
static size_t utf32_utf8_buffer_length(const utf_32_char *unicode_string)
{
const utf_32_char *curChar;
// Determine length of string (in octets) when encoded in UTF-8
size_t length = 0;
for (curChar = unicode_string; *curChar != '\0'; ++curChar)
{
length += unicode_utf8_char_length(*curChar);
}
return length;
}
char *UTF32toUTF8(const utf_32_char *unicode_string, size_t *nbytes)
{
const utf_32_char *curChar;
const size_t utf8_length = utf32_utf8_buffer_length(unicode_string);
// Allocate memory to hold the UTF-8 encoded string (plus a terminating nul char)
char *utf8_string = (char *)malloc(utf8_length + 1);
char *curOutPos = utf8_string;
if (utf8_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
for (curChar = unicode_string; *curChar != 0; ++curChar)
{
curOutPos = encode_utf8_char(*curChar, curOutPos);
}
// Terminate the string with a nul character
utf8_string[utf8_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = utf8_length + 1;
}
return utf8_string;
}
utf_32_char *UTF8toUTF32(const char *utf8_string, size_t *nbytes)
{
const char *curChar = utf8_string;
const size_t unicode_length = UTF8CharacterCount(utf8_string);
// Allocate memory to hold the UTF-32 encoded string (plus a terminating nul)
utf_32_char *unicode_string = (utf_32_char *)malloc(sizeof(utf_32_char) * (unicode_length + 1));
utf_32_char *curOutPos = unicode_string;
if (unicode_string == NULL)
{
debug(LOG_ERROR, "Out of memory");
return NULL;
}
while (*curChar != '\0')
{
*(curOutPos++) = UTF8DecodeChar(curChar, &curChar);
}
// Terminate the string with a nul
unicode_string[unicode_length] = '\0';
// Set the number of bytes allocated
if (nbytes)
{
*nbytes = sizeof(utf_32_char) * (unicode_length + 1);
}
return unicode_string;
}
| gpl-2.0 |
neonatura/crotalus | php/ext/pdo_mysql/tests/bug66141.phpt | 1288 | --TEST--
Bug #66141 (mysqlnd quote function is wrong with NO_BACKSLASH_ESCAPES after failed query)
--SKIPIF--
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'skipif.inc');
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc');
MySQLPDOTest::skip();
?>
--FILE--
<?php
include __DIR__ . DIRECTORY_SEPARATOR . 'mysql_pdo_test.inc';
$db = MySQLPDOTest::factory();
$input = 'Something\', 1 as one, 2 as two FROM dual; -- f';
$quotedInput0 = $db->quote($input);
$db->query('set session sql_mode="NO_BACKSLASH_ESCAPES"');
// injection text from some user input
$quotedInput1 = $db->quote($input);
$db->query('something that throws an exception');
$quotedInput2 = $db->quote($input);
var_dump($quotedInput0);
var_dump($quotedInput1);
var_dump($quotedInput2);
?>
done
--EXPECTF--
Warning: PDO::query(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your %s server version for the right syntax to use near 'something that throws an exception' at line %d in %s on line %d
string(50) "'Something\', 1 as one, 2 as two FROM dual; -- f'"
string(50) "'Something'', 1 as one, 2 as two FROM dual; -- f'"
string(50) "'Something'', 1 as one, 2 as two FROM dual; -- f'"
done | gpl-2.0 |
ccompiler4pic32/pic32-gcc | gcc/testsuite/g++.dg/cpp0x/defaulted14.C | 326 | // PR c++/39866
// { dg-options "-std=c++0x" }
struct A {
A& operator=(const A&) = delete; // { dg-bogus "" }
void operator=(int) {} // { dg-message "" }
void operator=(char) {} // { dg-message "" }
};
struct B {};
int main()
{
A a;
a = B(); // { dg-error "no match" }
a = 1.0; // { dg-error "ambiguous" }
}
| gpl-2.0 |
emiliojsf/sogo | SOPE/NGCards/iCalPerson.h | 2924 | /*
Copyright (C) 2000-2005 SKYRIX Software AG
This file is part of SOPE.
SOPE 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, or (at your option) any
later version.
SOPE 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 SOPE; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
*/
#ifndef __NGCards_iCalPerson_H__
#define __NGCards_iCalPerson_H__
#import "CardElement.h"
typedef enum {
iCalPersonPartStatUndefined = -1, /* empty/undefined */
iCalPersonPartStatNeedsAction = 0, /* NEEDS-ACTION (DEFAULT) */
iCalPersonPartStatAccepted = 1, /* ACCEPTED */
iCalPersonPartStatDeclined = 2, /* DECLINED */
/* up to here defined for VJOURNAL */
iCalPersonPartStatTentative = 3, /* TENTATIVE */
iCalPersonPartStatDelegated = 4, /* DELEGATED */
/* up to here defined for VEVENT */
iCalPersonPartStatCompleted = 5, /* COMPLETED */
iCalPersonPartStatInProcess = 6, /* IN-PROCESS */
/* up to there defined for VTODO */
/* these are also defined for VJOURNAL, VEVENT and VTODO */
iCalPersonPartStatExperimental = 7, /* x-name */
iCalPersonPartStatOther = 8 /* iana-token */
} iCalPersonPartStat;
@interface iCalPerson : CardElement
+ (NSString *) descriptionForParticipationStatus: (iCalPersonPartStat) _status;
/* accessors */
- (void)setCn:(NSString *)_s;
- (NSString *)cn;
- (NSString *)cnWithoutQuotes;
- (void)setEmail:(NSString *)_s;
- (NSString *)email;
- (NSString *)rfc822Email; /* email without 'mailto:' prefix */
- (void)setRsvp:(NSString *)_s;
- (NSString *)rsvp;
// - (void)setXuid:(NSString *)_s;
// - (NSString *)xuid;
- (void)setRole:(NSString *)_s;
- (NSString *)role;
- (void)setPartStat:(NSString *)_s;
- (NSString *)partStat;
- (NSString *)partStatWithDefault;
- (void) setDelegatedTo: (NSString *) newDelegate;
- (NSString *) delegatedTo;
- (void) setDelegatedFrom: (NSString *) newDelegatee;
- (NSString *) delegatedFrom;
- (void) setSentBy: (NSString *) newDelegatee;
- (NSString *) sentBy;
- (void)setParticipationStatus:(iCalPersonPartStat)_status;
- (iCalPersonPartStat)participationStatus;
- (BOOL)isEqualToPerson:(iCalPerson *)_other;
- (BOOL)hasSameEmailAddress:(iCalPerson *)_other;
@end
#endif /* __NGCards_iCalPerson_H__ */
| gpl-2.0 |
gregorynicholas/houdini-ocean-toolkit | src/3rdparty/src/blitz-0.9/doc/blitz_3.html | 71964 | <HTML>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- Created on October, 14 2005 by texi2html 1.64 -->
<!--
Written by: Lionel Cons <[email protected]> (original author)
Karl Berry <[email protected]>
Olaf Bachmann <[email protected]>
and many others.
Maintained by: Olaf Bachmann <[email protected]>
Send bugs and suggestions to <[email protected]>
-->
<HEAD>
<TITLE>Blitz++: Array Expressions</TITLE>
<META NAME="description" CONTENT="Blitz++: Array Expressions">
<META NAME="keywords" CONTENT="Blitz++: Array Expressions">
<META NAME="resource-type" CONTENT="document">
<META NAME="distribution" CONTENT="global">
<META NAME="Generator" CONTENT="texi2html 1.64">
</HEAD>
<BODY LANG="" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#0000FF" VLINK="#800080" ALINK="#FF0000">
<A NAME="SEC80"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_2.html#SEC79"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC81"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H1> 3. Array Expressions </H1>
<!--docid::SEC80::-->
<BLOCKQUOTE><TABLE BORDER=0 CELLSPACING=0>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC81">3.1 Expression evaluation order</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">Creating expressions with Array's</TD></TR>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC88">3.6 Index placeholders</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">Array indices functionality</TD></TR>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC92">3.8 Single-argument math functions</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">Single-argument math functions on Array's</TD></TR>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC95">3.9 Two-argument math functions</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">Two-argument math functions on Array's</TD></TR>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC98">3.10 Declaring your own math functions on arrays</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">Creating your math functions on Array's</TD></TR>
<TR><TD ALIGN="left" VALIGN="TOP"><A HREF="blitz_3.html#SEC103">3.15 where statements</A></TD><TD> </TD><TD ALIGN="left" VALIGN="TOP">The where statement</TD></TR>
</TABLE></BLOCKQUOTE>
<P>
<A NAME="IDX163"></A>
<A NAME="IDX164"></A>
<A NAME="IDX165"></A>
<A NAME="IDX166"></A>
<A NAME="IDX167"></A>
</P><P>
Array expressions in Blitz++ are implemented using the <EM>expression
templates</EM> technique. Unless otherwise noted, expression evaluation will
never generate temporaries or multiple loops; an expression such as
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,1> A, B, C, D; // ...
A = B + C + D;
</pre></td></tr></table></P><P>
will result in code similar to
</P><P>
<TABLE><tr><td> </td><td class=example><pre>for (int i=A.lbound(firstDim); i <= A.ubound(firstDim); ++i)
A[i] = B[i] + C[i] + D[i];
</pre></td></tr></table></P><P>
<A NAME="Array expressions"></A>
<HR SIZE="6">
<A NAME="SEC81"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.1 Expression evaluation order </H2>
<!--docid::SEC81::-->
<P>
A commonly asked question about Blitz++ is what order it uses to evaluate
array expressions. For example, in code such as
</P><P>
<TABLE><tr><td> </td><td class=example><pre>A(Range(2,10)) = A(Range(1,9))
</pre></td></tr></table></P><P>
does the expression get evaluated at indices 1, 2, ..., 9 or at 9, 8, ...,
1? This makes a big difference to the result: in one case, the array will
be shifted to the right by one element; in the other case, most of the array
elements will be set to the value in <CODE>A(1)</CODE>.
</P><P>
Blitz always selects the traversal order it thinks will be fastest. For 1D
arrays, this means it will go from beginning to the end of the array in
memory (see notes below). For multidimensional arrays, it will do one of
two things:
</P><P>
<UL>
<LI>try to go through the destination array in the order it is laid out
in memory (i.e. row-major for row-major arrays, column-major for
column-major arrays).
<P>
<LI>if the expression is a stencil, Blitz will do tiling to improve cache
use. Under some circumstances blitz will even use a traversal based on a
hilbert curve (a fractal) for 3D arrays.
<P>
</UL>
<P>
Because the traversal order is not always predictable, it is safest to put
the result in a new array if you are doing a stencil-style expression.
Blitz guarantees this will always work correctly. If you try to put the
result in one of the operands, you have to guess correctly which traversal
order blitz will choose. This is easy for the 1D case, but hard for the
multidimensional case.
</P><P>
Some special notes about 1D array traversals:
</P><P>
<UL>
<LI>if your array is stored in reverse order, i.e. because of a
A.reverse(firstDim) or funny storage order, blitz will go through the array
from end to beginning in array coordinates, but from beginning to end in
memory locations.
<P>
<LI>many compilers/architecture combinations are equally fast at reverse
order. But blitz has a specialized version for stride = +1, and it would be
wasteful to also specialize for the case stride = -1. So 1D arrays are
traversed from beginning to end (in memory storage order).
<P>
</UL>
<P>
<HR SIZE="6">
<A NAME="SEC82"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC81"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC83"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC83"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.2 Expression operands </H2>
<!--docid::SEC82::-->
<P>
An expression can contain any mix of these operands:
</P><P>
<UL>
<LI>An array of any type, so long as it is of the same rank.
Expressions which contain a mixture of array types are handled through the
type promotion mechanism described below.
<P>
<LI>Scalars of type <CODE>int</CODE>, <CODE>float</CODE>, <CODE>double</CODE>,
<CODE>long double</CODE>, or <CODE>complex<T></CODE>
<P>
<LI>Index placeholders, described below
<P>
<LI>Other expressions (e.g. <CODE>A+(B+C)</CODE>)
</UL>
<P>
<HR SIZE="6">
<A NAME="SEC83"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC84"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC86"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC86"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.3 Array operands </H2>
<!--docid::SEC83::-->
<P>
<HR SIZE="6">
<A NAME="SEC84"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC83"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC85"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> Using subarrays in an expression </H3>
<!--docid::SEC84::-->
<P>
<A NAME="IDX168"></A>
</P><P>
Subarrays may be used in an expression. For example, this code example
performs a 5-point average on a two-dimensional array:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A(64,64), B(64,64); // ...
Range I(1,62), J(1,62);
A(I,J) = (B(I,J) + B(I+1,J) + B(I-1,J)
+ B(I,J+1) + B(I,J-1)) / 5;
</pre></td></tr></table></P><P>
<HR SIZE="6">
<A NAME="SEC85"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC84"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC86"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> Mixing arrays with different storage formats </H3>
<!--docid::SEC85::-->
<P>
<A NAME="IDX169"></A>
</P><P>
Arrays with different storage formats (for example, C-style and
Fortran-style) can be mixed in the same expression. Blitz++ will handle the
different storage formats automatically. However:
</P><P>
<UL>
<LI>Evaluation may be slower, since a different traversal order may be
used.
<P>
<LI>If you are using index placeholders (see below) or reductions in
the expression, you may <STRONG>not</STRONG> mix array objects with different
starting bases.
<P>
</UL>
<P>
<HR SIZE="6">
<A NAME="SEC86"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC85"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC87"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC87"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.4 Expression operators </H2>
<!--docid::SEC86::-->
<P>
These binary operators are supported:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>+ - * / % > < >= <= == != && || ^ & |
</pre></td></tr></table></P><P>
Note: operator <CODE><<</CODE> and <CODE>>></CODE> are reserved for use in input/output.
If you need a bit-shift operation on arrays, you may define one yourself;
see <A HREF="blitz_3.html#SEC98">3.10 Declaring your own math functions on arrays</A>.
</P><P>
These unary operators are supported:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>- ~ !
</pre></td></tr></table></P><P>
The operators <CODE>> < >= <= == != && || !</CODE> result in a bool-valued
expression.
</P><P>
<A NAME="IDX170"></A>
All operators are applied <EM>elementwise</EM>.
</P><P>
<A NAME="IDX171"></A>
You can only use operators which are well-defined for the number type stored
in the arrays. For example, bitwise XOR (<CODE>^</CODE>) is meaningful for
integers, so this code is all right:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,3> A, B, C; // ...
A = B ^ C;
</pre></td></tr></table></P><P>
Bitwise XOR is <EM>not</EM> meaningful on floating point types, so this code
will generate a compiler error:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,1> A, B, C; // ...
C = B ^ C;
</pre></td></tr></table></P><P>
Here's the compiler error generated by KAI C++ for the above code:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>"../../blitz/ops.h", line 85: error: expression must have integral or enum type
BZ_DEFINE_OP(BitwiseXor,^);
^
detected during:
instantiation of "blitz::BitwiseXor<float, float>::T_numtype
blitz::BitwiseXor<float, float>::apply(float, float)" at
line 210 of "../../blitz/arrayexpr.h"
instantiation of ...
.
.
</pre></td></tr></table></P><P>
<A NAME="IDX172"></A>
If you are creating arrays using a type you have created yourself, you will
need to overload whatever operators you want to use on arrays. For example,
if I create a class <CODE>Polynomial</CODE>, and want to write code such as:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<Polynomial,2> A, B, C; // ...
C = A * B;
</pre></td></tr></table></P><P>
I would have to provide <CODE>operator*</CODE> for <CODE>Polynomial</CODE> by
implementing
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Polynomial Polynomial::operator*(Polynomial);)
</pre></td></tr></table></P><P>
or
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Polynomial operator*(Polynomial, Polynomial);)
</pre></td></tr></table></P><P>
<HR SIZE="6">
<A NAME="SEC87"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC86"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC88"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC88"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.5 Assignment operators </H2>
<!--docid::SEC87::-->
<P>
<A NAME="IDX173"></A>
These assignment operators are supported:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>= += -= *= /= %= ^= &= |= >>= <<=
</pre></td></tr></table></P><P>
An array object should appear on the left side of the operator. The right
side can be:
</P><P>
<UL>
<LI>A constant (or literal) of type <CODE>T_numtype</CODE>
<P>
<LI>An array of appropriate rank, possibly of a different numeric type
<P>
<LI>An array expression, with appropriate rank and shape
<P>
</UL>
<P>
<A NAME="Index placeholders"></A>
<HR SIZE="6">
<A NAME="SEC88"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC87"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC89"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC89"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.6 Index placeholders </H2>
<!--docid::SEC88::-->
<P>
Blitz++ provides objects called <EM>index placeholders</EM> which represent
array indices. They can be used directly in expressions.
</P><P>
There is a distinct index placeholder type associated with each dimension of
an array. The types are called <CODE>firstIndex</CODE>, <CODE>secondIndex</CODE>,
<CODE>thirdIndex</CODE>, ..., <CODE>tenthIndex</CODE>, <CODE>eleventhIndex</CODE>.
<A NAME="IDX174"></A>
<A NAME="IDX175"></A>
<A NAME="IDX176"></A>
<A NAME="IDX177"></A>
Here's an example of using an index placeholder:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,1> A(10);
firstIndex i;
A = i;
</pre></td></tr></table></P><P>
This generates code which is similar to:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>for (int i=0; i < A.length(); ++i)
A(i) = i;
</pre></td></tr></table></P><P>
Here's an example which fills an array with a sampled sine wave:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,1> A(16);
firstIndex i;
A = sin(2 * M_PI * i / 16.);
</pre></td></tr></table></P><P>
If your destination array has rank greater than 1, you may use
multiple index placeholders:
</P><P>
<A NAME="IDX178"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>// Fill a two-dimensional array with a radially
// symmetric, decaying sinusoid
// Create the array
int N = 64;
Array<float,2> F(N,N);
// Some parameters
float midpoint = (N-1)/2.;
int cycles = 3;
float omega = 2.0 * M_PI * cycles / double(N);
float tau = - 10.0 / N;
// Index placeholders
firstIndex i;
secondIndex j;
// Fill the array
F = cos(omega * sqrt(pow2(i-midpoint) + pow2(j-midpoint)))
* exp(tau * sqrt(pow2(i-midpoint) + pow2(j-midpoint)));
</pre></td></tr></table></P><P>
Here's a plot of the resulting array:
</P><P>
<center>
<CENTER><IMG SRC="sinsoid.gif" ALT="sinsoid"></CENTER>
</center>
<center>
Array filled using an index placeholder expression.
</center>
</P><P>
You can use index placeholder expressions in up to 11 dimensions.
Here's a three dimensional example:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>// Fill a three-dimensional array with a Gaussian function
Array<float,3> A(16,16,16);
firstIndex i;
secondIndex j;
thirdIndex k;
float midpoint = 15/2.;
float c = - 1/3.0;
A = exp(c * (sqr(i-midpoint) + sqr(j-midpoint)
+ sqr(k-midpoint)));
</pre></td></tr></table></P><P>
You can mix array operands and index placeholders:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,1> A(5), B(5);
firstIndex i;
A = 0, 1, 1, 0, 2;
B = i * A; // Results in [ 0, 1, 2, 0, 8 ]
</pre></td></tr></table></P><P>
For your convenience, there is a namespace within blitz
called <CODE>tensor</CODE> which declares all the index placeholders:
</P><P>
<A NAME="IDX179"></A>
<A NAME="IDX180"></A>
<A NAME="IDX181"></A>
<A NAME="IDX182"></A>
<A NAME="IDX183"></A>
<A NAME="IDX184"></A>
<A NAME="IDX185"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>namespace blitz {
namespace tensor {
firstIndex i;
secondIndex j;
thirdIndex k;
...
eleventhIndex t;
}
}
</pre></td></tr></table></P><P>
So instead of declaring your own index placeholder objects,
you can just say
</P><P>
<A NAME="IDX186"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>namespace blitz::tensor;
</pre></td></tr></table>
when you would like to use them. Alternately, you can just preface all the
index placeholders with <CODE>tensor::</CODE>, for example:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>A = sin(2 * M_PI * tensor::i / 16.);
</pre></td></tr></table></P><P>
This will make your code more readable, since it is immediately clear that
<CODE>i</CODE> is an index placeholder, rather than a scalar value.
</P><P>
<HR SIZE="6">
<A NAME="SEC89"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC88"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC90"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC92"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC92"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.7 Type promotion </H2>
<!--docid::SEC89::-->
<P>
When operands of different numeric types are used in an expression, the
result gets promoted according to the usual C-style type promotion. For
example, the result of adding an <CODE>Array<int></CODE> to an
<CODE>Arrray<float></CODE> will be promoted to <CODE>float</CODE>. Generally, the
result is promoted to whichever type has greater precision.
</P><P>
<HR SIZE="6">
<A NAME="SEC90"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC89"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC91"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> Type promotion for user-defined types </H3>
<!--docid::SEC90::-->
<P>
<A NAME="IDX187"></A>
<A NAME="IDX188"></A>
</P><P>
The rules for type promotion of user-defined types (or types from another
library) are a bit complicated. Here's how a pair of operand types are
promoted:
</P><P>
<UL>
<LI>If both types are intrinsic (e.g. bool, int, float) then type
promotion follows the standard C rules. This generally means that the
result will be promoted to whichever type has greater precision. In
Blitz++, these rules have been extended to incorporate
<CODE>complex<float></CODE>, <CODE>complex<double></CODE>, and <CODE>complex<long
double></CODE>.
<P>
<LI>If one of the types is intrinsic (or complex), and the other is a
user-defined type, then the result is promoted to the user-defined type.
<P>
<LI>If both types are user-defined, then the result is promoted to
whichever type requires more storage space (as determined by
<CODE>sizeof()</CODE>). The rationale is that more storage space probably
indicates more precision.
<P>
</UL>
<P>
If you wish to alter the default type promotion rules above, you have two
choices:
</P><P>
<UL>
<A NAME="IDX189"></A>
<LI>If the type promotion behaviour isn't dependent on the type of
operation performed, then you can provide appropriate specializations for
the class <CODE>promote_trait<A,B></CODE> which is declared in
<CODE><blitz/promote.h></CODE>.
<P>
<LI>If type promotion does depend on the type of operation, then you
will need to specialize the appropriate function objects in
<CODE><blitz/ops.h></CODE>.
<P>
</UL>
<P>
Note that you can do these specializations in your own header files (you
don't have to edit <TT>`promote.h'</TT> or <TT>`ops.h'</TT>).
</P><P>
<HR SIZE="6">
<A NAME="SEC91"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC90"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC92"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> Manual casts </H3>
<!--docid::SEC91::-->
<P>
<A NAME="IDX190"></A>
<A NAME="IDX191"></A>
</P><P>
There are some inconvenient aspects of C-style type promotion. For example,
when you divide two integers in C, the result gets truncated. The same
problem occurs when dividing two integer arrays in Blitz++:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,1> A(4), B(4);
Array<float,1> C(4);
A = 1, 2, 3, 5;
B = 2, 2, 2, 7;
C = A / B; // Result: [ 0 1 1 0 ]
</pre></td></tr></table></P><P>
The usual solution to this problem is to cast one of the operands to a
floating type. For this purpose, Blitz++ provides a function
<CODE>cast(expr,type)</CODE> which will cast the result of <EM>expr</EM> as
<EM>type</EM>:
</P><P>
<A NAME="IDX192"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>C = A / cast(B, float()); // Result: [ 0.5 1 1.5 0.714 ]
</pre></td></tr></table></P><P>
The first argument to <CODE>cast()</CODE> is an array or expression. The second
argument is a dummy object of the type to which you want to cast. Once
compilers support templates more thoroughly, it will be possible to use this
cast syntax:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>C = A / cast<float>(B);
</pre></td></tr></table></P><P>
But this is not yet supported.
</P><P>
<A NAME="Math functions 1"></A>
<HR SIZE="6">
<A NAME="SEC92"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC91"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC93"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC95"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC95"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.8 Single-argument math functions </H2>
<!--docid::SEC92::-->
<P>
All of the functions described in this section are <EM>element-wise</EM>. For
example, this code--
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A, B; //
A = sin(B);
</pre></td></tr></table></P><P>
results in <CODE>A(i,j) = sin(B(i,j))</CODE> for all (i,j).
</P><P>
<HR SIZE="6">
<A NAME="SEC93"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC92"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC94"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> ANSI C++ math functions </H3>
<!--docid::SEC93::-->
<P>
These math functions are available on all platforms:
</P><P>
<A NAME="IDX193"></A>
<A NAME="IDX194"></A>
</P><P>
<DL COMPACT>
<DT><CODE>abs()</CODE>
<DD><A NAME="IDX195"></A>
Absolute value
<P>
<DT><CODE>acos()</CODE>
<DD><A NAME="IDX196"></A>
Inverse cosine. For real arguments, the return value is in the range
<EM>[0, \pi]</EM>.
<P>
<DT><CODE>arg()</CODE>
<DD><A NAME="IDX197"></A>
Argument of a complex number (<CODE>atan2(Im,Re)</CODE>).
<P>
<DT><CODE>asin()</CODE>
<DD><A NAME="IDX198"></A>
Inverse sine. For real arguments, the return value is in the range
<EM>[-\pi/2, \pi/2]</EM>.
<P>
<DT><CODE>atan()</CODE>
<DD><A NAME="IDX199"></A>
Inverse tangent. For real arguments, the return value is in the range
<EM>[-\pi/2, \pi/2]</EM>. See also <CODE>atan2()</CODE> in section
<A HREF="blitz_3.html#SEC95">3.9 Two-argument math functions</A>.
<P>
<DT><CODE>ceil()</CODE>
<DD><A NAME="IDX200"></A>
Ceiling function: smallest floating-point integer value not less than the
argument.
<P>
<DT><CODE>cexp()</CODE>
<DD><A NAME="IDX201"></A>
Complex exponential; same as <CODE>exp()</CODE>.
<P>
<DT><CODE>conj()</CODE>
<DD><A NAME="IDX202"></A>
Conjugate of a complex number.
<P>
<DT><CODE>cos()</CODE>
<DD><A NAME="IDX203"></A>
Cosine. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>cosh()</CODE>
<DD><A NAME="IDX204"></A>
Hyperbolic cosine. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>csqrt()</CODE>
<DD><A NAME="IDX205"></A>
Complex square root; same as <CODE>sqrt()</CODE>.
<P>
<DT><CODE>exp()</CODE>
<DD><A NAME="IDX206"></A>
Exponential. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>fabs()</CODE>
<DD><A NAME="IDX207"></A>
Same as <CODE>abs()</CODE>.
<P>
<DT><CODE>floor()</CODE>
<DD><A NAME="IDX208"></A>
Floor function: largest floating-point integer value not greater than the
argument.
<P>
<DT><CODE>log()</CODE>
<DD><A NAME="IDX209"></A>
Natural logarithm. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>log10()</CODE>
<DD><A NAME="IDX210"></A>
Base 10 logarithm. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>pow2(), pow3(), pow4(), pow5(), pow6(), pow7(), pow8()</CODE>
<DD><A NAME="IDX211"></A>
<A NAME="IDX212"></A>
<A NAME="IDX213"></A>
These functions compute an integer power. They expand to a series of
multiplications, so they can be used on any type for which multiplication is
well-defined.
<P>
<DT><CODE>sin()</CODE>
<DD><A NAME="IDX214"></A>
Sine. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>sinh()</CODE>
<DD><A NAME="IDX215"></A>
Hyperbolic sine. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>sqr()</CODE>
<DD><A NAME="IDX216"></A>
Same as <CODE>pow2()</CODE>. Computes <CODE>x*x</CODE>. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>sqrt()</CODE>
<DD><A NAME="IDX217"></A>
Square root. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>tan()</CODE>
<DD><A NAME="IDX218"></A>
Tangent. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>tanh()</CODE>
<DD><A NAME="IDX219"></A>
Hyperbolic tangent. Works for <CODE>complex<T></CODE>.
</DL>
<P>
<HR SIZE="6">
<A NAME="SEC94"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC93"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC95"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> IEEE/System V math functions </H3>
<!--docid::SEC94::-->
<P>
<A NAME="IDX220"></A>
<A NAME="IDX221"></A>
<A NAME="IDX222"></A>
<A NAME="IDX223"></A>
</P><P>
These functions are only available on platforms which provide the IEEE Math
library (libm.a) and/or System V Math Library (libmsaa.a). Apparently not
all platforms provide all of these functions, so what you can use on your
platform may be a subset of these. If you choose to use one of these
functions, be aware that you may be limiting the portability of your code.
</P><P>
<A NAME="IDX224"></A>
<A NAME="IDX225"></A>
</P><P>
On some platforms, the preprocessor symbols <CODE>_XOPEN_SOURCE</CODE> and/or
<CODE>_XOPEN_SOURCE_EXTENDED</CODE> need to be defined to use these functions.
These symbols can be enabled by compiling with
<CODE>-DBZ_ENABLE_XOPEN_SOURCE</CODE>. (In previous version of Blitz++,
<CODE>_XOPEN_SOURCE</CODE> and <CODE>_XOPEN_SOURCE_EXTENDED</CODE> were declared by
default. This was found to cause too many problems, so users must manually
enable them with <CODE>-DBZ_ENABLE_XOPEN_SOURCE</CODE>.).
</P><P>
In the current version, Blitz++ divides these functions into two groups:
IEEE and System V. This distinction is probably artificial. If one of the
functions in a group is missing, Blitz++ won't allow you to use any of them.
You can see the division of these functions in the files
<TT>`Blitz++/compiler/ieeemath.cpp'</TT> and
<TT>`Blitz++/compiler/sysvmath.cpp'</TT>. This arrangement is unsatisfactory
and will probably change in a future version.
</P><P>
You may have to link with <CODE>-lm</CODE> and/or <CODE>-lmsaa</CODE> to use these
functions.
</P><P>
None of these functions are available for <CODE>complex<T></CODE>.
</P><P>
<DL COMPACT>
<DT><CODE>acosh()</CODE>
<DD><A NAME="IDX226"></A>
Inverse hyperbolic cosine
<P>
<DT><CODE>asinh()</CODE>
<DD><A NAME="IDX227"></A>
Inverse hyperbolic sine
<P>
<DT><CODE>atanh()</CODE>
<DD><A NAME="IDX228"></A>
Inverse hyperbolic tangent
<P>
<DT><CODE>_class()</CODE>
<DD><A NAME="IDX229"></A>
Classification of floating point values. The return type is integer and
will be one of:
<P>
<DL COMPACT>
<DT><CODE>FP_PLUS_NORM</CODE>
<DD><A NAME="IDX230"></A>
Positive normalized, nonzero
<P>
<DT><CODE>FP_MINUS_NORM</CODE>
<DD><A NAME="IDX231"></A>
Negative normalized, nonzero
<P>
<DT><CODE>FP_PLUS_DENORM</CODE>
<DD><A NAME="IDX232"></A>
Positive denormalized, nonzero
<P>
<DT><CODE>FP_MINUS_DENORM</CODE>
<DD><A NAME="IDX233"></A>
Negative denormalized, nonzero
<P>
<DT><CODE>FP_PLUS_ZERO</CODE>
<DD><A NAME="IDX234"></A>
+0.0
<P>
<DT><CODE>FP_MINUS_ZERO</CODE>
<DD><A NAME="IDX235"></A>
-0.0
<P>
<DT><CODE>FP_PLUS_INF</CODE>
<DD><A NAME="IDX236"></A>
Positive infinity
<P>
<DT><CODE>FP_MINUS_INF</CODE>
<DD><A NAME="IDX237"></A>
Negative infinity
<P>
<DT><CODE>FP_NANS</CODE>
<DD><A NAME="IDX238"></A>
Signalling Not a Number (NaNS)
<P>
<DT><CODE>FP_NANQ</CODE>
<DD><A NAME="IDX239"></A>
Quiet Not a Number (NaNQ)
</DL>
<P>
<DT><CODE>cbrt()</CODE>
<DD><A NAME="IDX240"></A>
Cubic root
<P>
<DT><CODE>expm1()</CODE>
<DD><A NAME="IDX241"></A>
Computes exp(x)-1
<P>
<DT><CODE>erf()</CODE>
<DD><A NAME="IDX242"></A>
Computes the error function:
@erf(x) = 2/sqrt(Pi) * integral(exp(-t^2), t=0..x)
<P>
Note that for large values of the parameter, calculating can result in
extreme loss of accuracy. Instead, use <CODE>erfc()</CODE>.
</P><P>
<DT><CODE>erfc()</CODE>
<DD><A NAME="IDX243"></A>
Computes the complementary error function <EM>erfc(x) = 1 - erf(x)</EM>.
<P>
<DT><CODE>finite()</CODE>
<DD><A NAME="IDX244"></A>
Returns a nonzero integer if the parameter is a finite number (i.e. not
+INF, -INF, NaNQ or NaNS).
<P>
<DT><CODE>ilogb()</CODE>
<DD><A NAME="IDX245"></A>
Returns an integer which is equal to the unbiased exponent of
the parameter.
<P>
<DT><CODE>blitz_isnan()</CODE>
<DD><A NAME="IDX246"></A>
<A NAME="IDX247"></A>
Returns a nonzero integer if the parameter is NaNQ or
NaNS (quiet or signalling Not a Number).
<P>
<DT><CODE>itrunc()</CODE>
<DD><A NAME="IDX248"></A>
Round a floating-point number to a signed integer. Returns
the nearest signed integer to the parameter in the direction of 0.
<P>
<DT><CODE>j0()</CODE>
<DD><A NAME="IDX249"></A>
<A NAME="IDX250"></A>
Bessel function of the first kind, order 0.
<P>
<DT><CODE>j1()</CODE>
<DD><A NAME="IDX251"></A>
Bessel function of the first kind, order 1.
<P>
<DT><CODE>lgamma()</CODE>
<DD><A NAME="IDX252"></A>
<A NAME="IDX253"></A>
Natural logarithm of the gamma function. The gamma function
is defined as:
Gamma(x) = integral(e^(-t) * t^(x-1), t=0..infinity))
<DT><CODE>logb()</CODE>
<DD><A NAME="IDX254"></A>
Returns a floating-point double that is equal to the unbiased
exponent of the parameter.
<P>
<DT><CODE>log1p()</CODE>
<DD><A NAME="IDX255"></A>
Calculates log(1+x), where x is the parameter.
<P>
<DT><CODE>nearest()</CODE>
<DD><A NAME="IDX256"></A>
Returns the nearest floating-point integer value to the
parameter. If the parameter is exactly halfway between two integer values,
an even value is returned.
<P>
<DT><CODE>rint()</CODE>
<DD><A NAME="IDX257"></A>
<A NAME="IDX258"></A>
Rounds the parameter and returns a floating-point integer value. Whether
<CODE>rint()</CODE> rounds up or down or to the nearest integer depends on the
current floating-point rounding mode. If you haven't altered the rounding
mode, <CODE>rint()</CODE> should be equivalent to <CODE>nearest()</CODE>. If rounding
mode is set to round towards +INF, <CODE>rint()</CODE> is equivalent to
<CODE>ceil()</CODE>. If the mode is round toward -INF, <CODE>rint()</CODE> is
equivalent to <CODE>floor()</CODE>. If the mode is round toward zero,
<CODE>rint()</CODE> is equivalent to <CODE>trunc()</CODE>.
<P>
<DT><CODE>rsqrt()</CODE>
<DD><A NAME="IDX259"></A>
Reciprocal square root.
<P>
<DT><CODE>uitrunc()</CODE>
<DD><A NAME="IDX260"></A>
Returns the nearest unsigned integer to the parameter in the
direction of zero.
<P>
<DT><CODE>y0()</CODE>
<DD><A NAME="IDX261"></A>
Bessel function of the second kind, order 0.
<P>
<DT><CODE>y1()</CODE>
<DD><A NAME="IDX262"></A>
Bessel function of the second kind, order 1.
</DL>
<P>
There may be better descriptions of these functions in your
system man pages.
</P><P>
<A NAME="Math functions 2"></A>
<HR SIZE="6">
<A NAME="SEC95"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC94"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC93"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC98"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.9 Two-argument math functions </H2>
<!--docid::SEC95::-->
<P>
The math functions described in this section take two arguments.
Most combinations of these types may be used as arguments:
</P><P>
<UL>
<LI>An Array object
<LI>An Array expression
<LI>An index placeholder
<LI>A scalar of type <CODE>float</CODE>, <CODE>double</CODE>, <CODE>long double</CODE>,
or <CODE>complex<T></CODE>
</UL>
<P>
<HR SIZE="6">
<A NAME="SEC93"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC95"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC94"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> ANSI C++ math functions </H3>
<!--docid::SEC96::-->
<P>
These math functions are available on all platforms, and work for
complex numbers.
</P><P>
<A NAME="IDX263"></A>
<A NAME="IDX264"></A>
</P><P>
<DL COMPACT>
<DT><CODE>atan2(x,y)</CODE>
<DD><A NAME="IDX265"></A>
Inverse tangent of (y/x). The signs of both parameters
are used to determine the quadrant of the return value, which is in the
range <EM>[-\pi, \pi]</EM>. Works for <CODE>complex<T></CODE>.
<P>
<DT><CODE>blitz::polar(r,t)</CODE>
<DD><A NAME="IDX266"></A>
Computes ; i.e. converts polar-form to
Cartesian form complex numbers. The <CODE>blitz::</CODE> scope qualifier is
needed to disambiguate the ANSI C++ function template <CODE>polar(T,T)</CODE>.
This qualifier will hopefully disappear in a future version.
<P>
<DT><CODE>pow(x,y)</CODE>
<DD><A NAME="IDX267"></A>
Computes x to the exponent y. Works for <CODE>complex<T></CODE>.
</DL>
<P>
<HR SIZE="6">
<A NAME="SEC94"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC93"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC98"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[ << ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[ >> ]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H3> IEEE/System V math functions </H3>
<!--docid::SEC97::-->
<P>
See the notes about IEEE/System V math functions in the previous section.
None of these functions work for complex numbers. They will all cast their
arguments to double precision.
</P><P>
<DL COMPACT>
<DT><CODE>copysign(x,y)</CODE>
<DD><A NAME="IDX268"></A>
Returns the x parameter with the same sign as the y parameter.
<P>
<DT><CODE>drem(x,y)</CODE>
<DD><A NAME="IDX269"></A>
<A NAME="IDX270"></A>
Computes a floating point remainder. The return value r is equal to r = x -
n * y, where n is equal to <CODE>nearest(x/y)</CODE> (the nearest integer to x/y).
The return value will lie in the range [ -y/2, +y/2 ]. If y is zero or x is
+INF or -INF, NaNQ is returned.
<P>
<DT><CODE>fmod(x,y)</CODE>
<DD><A NAME="IDX271"></A>
<A NAME="IDX272"></A>
Computes a floating point modulo remainder. The return value r is equal to
r = x - n * y, where n is selected so that r has the same sign as x and
magnitude less than abs(y). In order words, if x > 0, r is in the range [0,
|y|], and if x < 0, r is in the range [-|y|, 0].
<P>
<DT><CODE>hypot(x,y)</CODE>
<DD><A NAME="IDX273"></A>
Computes so that underflow does not occur and overflow occurs only if the
final result warrants it.
<P>
<DT><CODE>nextafter(x,y)</CODE>
<DD><A NAME="IDX274"></A>
Returns the next representable number after x in the direction of y.
<P>
<DT><CODE>remainder(x,y)</CODE>
<DD><A NAME="IDX275"></A>
Equivalent to drem(x,y).
<P>
<DT><CODE>scalb(x,y)</CODE>
<DD><A NAME="IDX276"></A>
Calculates.
<P>
<DT><CODE>unordered(x,y)</CODE>
<DD><A NAME="IDX277"></A>
Returns a nonzero value if a floating-point comparison between x and y would
be unordered. Otherwise, it returns zero.
</DL>
<P>
<A NAME="User et"></A>
<HR SIZE="6">
<A NAME="SEC98"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC94"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC99"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.10 Declaring your own math functions on arrays </H2>
<!--docid::SEC98::-->
<P>
<A NAME="IDX278"></A>
<A NAME="IDX279"></A>
</P><P>
There are four macros which make it easy to turn your own scalar functions
into functions defined on arrays. They are:
</P><P>
<A NAME="IDX280"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>BZ_DECLARE_FUNCTION(f) // 1
BZ_DECLARE_FUNCTION_RET(f,return_type) // 2
BZ_DECLARE_FUNCTION2(f) // 3
BZ_DECLARE_FUNCTION2_RET(f,return_type) // 4
</pre></td></tr></table></P><P>
Use version 1 when you have a function which takes one argument and returns
a result of the same type. For example:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>#include <blitz/array.h>
using namespace blitz;
double myFunction(double x)
{
return 1.0 / (1 + x);
}
BZ_DECLARE_FUNCTION(myFunction)
int main()
{
Array<double,2> A(4,4), B(4,4); // ...
B = myFunction(A);
}
</pre></td></tr></table></P><P>
Use version 2 when you have a one argument function whose return type is
different than the argument type, such as
</P><P>
<TABLE><tr><td> </td><td class=example><pre>int g(double x);
</pre></td></tr></table></P><P>
Use version 3 for a function which takes two arguments and returns a result
of the same type, such as:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>double g(double x, double y);
</pre></td></tr></table></P><P>
Use version 4 for a function of two arguments which returns a different
type, such as:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>int g(double x, double y);
</pre></td></tr></table></P><P>
<HR SIZE="6">
<A NAME="SEC99"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC98"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC100"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.11 Tensor notation </H2>
<!--docid::SEC99::-->
<P>
<A NAME="IDX281"></A>
<A NAME="IDX282"></A>
</P><P>
Blitz++ arrays support a tensor-like notation. Here's an example of
real-world tensor notation:
<pre>
ijk ij k
A = B C
</pre>
</P><P>
<EM>A</EM> is a rank 3 tensor (a three dimensional array), <EM>B</EM> is a rank
2 tensor (a two dimensional array), and <EM>C</EM> is a rank 1 tensor (a one
dimensional array). The above expression sets
<CODE>A(i,j,k) = B(i,j) * C(k)</CODE>.
</P><P>
To implement this product using Blitz++, we'll need the arrays and some
index placeholders:
</P><P>
<A NAME="IDX283"></A>
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,3> A(4,4,4);
Array<float,2> B(4,4);
Array<float,1> C(4);
firstIndex i; // Alternately, could just say
secondIndex j; // using namespace blitz::tensor;
thirdIndex k;
</pre></td></tr></table></P><P>
Here's the Blitz++ code which is equivalent to the tensor expression:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>A = B(i,j) * C(k);
</pre></td></tr></table></P><P>
The index placeholder arguments tell an array how to map its dimensions onto
the dimensions of the destination array. For example, here's some
real-world tensor notation:
<pre>
ijk ij k jk i
C = A x - A y
</pre>
</P><P>
In Blitz++, this would be coded as:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>using namespace blitz::tensor;
C = A(i,j) * x(k) - A(j,k) * y(i);
</pre></td></tr></table></P><P>
This tensor expression can be visualized in the following way:
</P><P>
<center>
<CENTER><IMG SRC="tensor1.gif" ALT="tensor1"></CENTER>
</center>
<center>
Examples of array indexing, subarrays, and slicing.
</center>
</P><P>
Here's an example which computes an outer product of two one-dimensional
arrays:
<A NAME="IDX284"></A>
<A NAME="IDX285"></A>
<A NAME="IDX286"></A>
</P><P>
<TABLE><tr><td> </td><td class=smallexample><FONT SIZE=-1><pre>#include <blitz/array.h>
using namespace blitz;
int main()
{
Array<float,1> x(4), y(4);
Array<float,2> A(4,4);
x = 1, 2, 3, 4;
y = 1, 0, 0, 1;
firstIndex i;
secondIndex j;
A = x(i) * y(j);
cout << A << endl;
return 0;
}
</FONT></pre></td></tr></table></P><P>
And the output:
</P><P>
<TABLE><tr><td> </td><td class=smallexample><FONT SIZE=-1><pre>4 x 4
[ 1 0 0 1
2 0 0 2
3 0 0 3
4 0 0 4 ]
</FONT></pre></td></tr></table></P><P>
Index placeholders can <EM>not</EM> be used on the left-hand side of an
expression. If you need to reorder the indices, you must do this on the
right-hand side.
</P><P>
In real-world tensor notation, repeated indices imply a contraction (or
summation). For example, this tensor expression computes a matrix-matrix
product:
<pre>
ij ik kj
C = A B
</pre>
</P><P>
The repeated k index is interpreted as meaning
<pre>
c = sum of {a * b } over k
ij ik kj
</pre>
</P><P>
<A NAME="IDX287"></A>
<A NAME="IDX288"></A>
</P><P>
In Blitz++, repeated indices do <EM>not</EM> imply contraction. If you want
to contract (sum along) an index, you must use the <CODE>sum()</CODE> function:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A, B, C; // ...
firstIndex i;
secondIndex j;
thirdIndex k;
C = sum(A(i,k) * B(k,j), k);
</pre></td></tr></table></P><P>
The <CODE>sum()</CODE> function is an example of an <EM>array reduction</EM>,
described in the next section.
</P><P>
Index placeholders can be used in any order in an expression. This example
computes a kronecker product of a pair of two-dimensional arrays, and
permutes the indices along the way:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A, B; // ...
Array<float,4> C; // ...
fourthIndex l;
C = A(l,j) * B(k,i);
</pre></td></tr></table></P><P>
This is equivalent to the tensor notation
<pre>
ijkl lj ki
C = A B
</pre>
</P><P>
Tensor-like notation can be mixed with other array notations:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A, B; // ...
Array<double,4> C; // ...
C = cos(A(l,j)) * sin(B(k,i)) + 1./(i+j+k+l);
</pre></td></tr></table></P><P>
<A NAME="IDX289"></A>
An important efficiency note about tensor-like notation: the right-hand side
of an expression is <EM>completely evaluated</EM> for <EM>every</EM> element in
the destination array. For example, in this code:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,1> x(4), y(4);
Array<float,2> A(4,4):
A = cos(x(i)) * sin(y(j));
</pre></td></tr></table></P><P>
The resulting implementation will look something like this:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>for (int n=0; n < 4; ++n)
for (int m=0; m < 4; ++m)
A(n,m) = cos(x(n)) * sin(y(m));
</pre></td></tr></table></P><P>
The functions <CODE>cos</CODE> and <CODE>sin</CODE> will be invoked sixteen times each.
It's possible that a good optimizing compiler could hoist the <CODE>cos</CODE>
evaluation out of the inner loop, but don't hold your breath -- there's a
lot of complicated machinery behind the scenes to handle tensor notation,
and most optimizing compilers are easily confused. In a situation like the
above, you are probably best off manually creating temporaries for
<CODE>cos(x)</CODE> and <CODE>sin(y)</CODE> first.
</P><P>
<HR SIZE="6">
<A NAME="SEC100"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC99"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC101"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.12 Array reductions </H2>
<!--docid::SEC100::-->
<P>
Currently, Blitz++ arrays support two forms of reduction:
</P><P>
<UL>
<LI>Reductions which transform an array into a scalar (for example,
summing the elements). These are referred to as <STRONG>complete
reductions</STRONG>.
<P>
<LI>Reducing an N dimensional array (or array expression) to an N-1
dimensional array expression. These are called <STRONG>partial reductions</STRONG>.
<P>
</UL>
<P>
<A NAME="IDX290"></A>
<A NAME="IDX291"></A>
<A NAME="IDX292"></A>
</P><P>
<HR SIZE="6">
<A NAME="SEC101"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC100"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC102"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.13 Complete reductions </H2>
<!--docid::SEC101::-->
<P>
Complete reductions transform an array (or array expression) into
a scalar. Here are some examples:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A(3,3);
A = 0, 1, 2,
3, 4, 5,
6, 7, 8;
cout << sum(A) << endl // 36
<< min(A) << endl // 0
<< count(A >= 4) << endl; // 5
</pre></td></tr></table></P><P>
Here are the available complete reductions:
</P><P>
<DL COMPACT>
<DT><CODE>sum()</CODE>
<DD><A NAME="IDX293"></A>
Summation (may be promoted to a higher-precision type)
<P>
<DT><CODE>product()</CODE>
<DD><A NAME="IDX294"></A>
Product
<P>
<DT><CODE>mean()</CODE>
<DD><A NAME="IDX295"></A>
Arithmetic mean (promoted to floating-point type if necessary)
<P>
<DT><CODE>min()</CODE>
<DD><A NAME="IDX296"></A>
Minimum value
<P>
<DT><CODE>max()</CODE>
<DD><A NAME="IDX297"></A>
Maximum value
<P>
<DT><CODE>minIndex()</CODE>
<DD><A NAME="IDX298"></A>
Index of the minimum value (<CODE>TinyVector<int,N_rank></CODE>)
<P>
<DT><CODE>maxIndex()</CODE>
<DD><A NAME="IDX299"></A>
Index of the maximum value (<CODE>TinyVector<int,N_rank></CODE>)
<P>
<DT><CODE>count()</CODE>
<DD><A NAME="IDX300"></A>
Counts the number of times the expression is logical true (<CODE>int</CODE>)
<P>
<DT><CODE>any()</CODE>
<DD><A NAME="IDX301"></A>
True if the expression is true anywhere (<CODE>bool</CODE>)
<P>
<DT><CODE>all()</CODE>
<DD><A NAME="IDX302"></A>
True if the expression is true everywhere (<CODE>bool</CODE>)
</DL>
<P>
<STRONG>Note:</STRONG> <CODE>minIndex()</CODE> and <CODE>maxIndex()</CODE> return TinyVectors,
even when the rank of the array (or array expression) is 1.
</P><P>
Reductions can be combined with <CODE>where</CODE> expressions (<A HREF="blitz_3.html#SEC103">3.15 where statements</A>)
to reduce over some part of an array. For example, <CODE>sum(where(A > 0,
A, 0))</CODE> sums only the positive elements in an array.
</P><P>
<HR SIZE="6">
<A NAME="SEC102"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC101"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC103"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.14 Partial Reductions </H2>
<!--docid::SEC102::-->
<P>
<A NAME="IDX303"></A>
<A NAME="IDX304"></A>
<A NAME="IDX305"></A>
</P><P>
Here's an example which computes the sum of each row of a two-dimensional
array:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,2> A; // ...
Array<float,1> rs; // ...
firstIndex i;
secondIndex j;
rs = sum(A, j);
</pre></td></tr></table></P><P>
The reduction <CODE>sum()</CODE> takes two arguments:
</P><P>
<UL>
<LI>The first argument is an array or array expression.
<P>
<LI>The second argument is an index placeholder indicating the
dimension over which the reduction is to occur.
<P>
</UL>
<P>
Reductions have an <STRONG>important restriction</STRONG>: It is currently only
possible to reduce over the <EM>last</EM> dimension of an array or array
expression. Reducing a dimension other than the last would require Blitz++
to reorder the dimensions to fill the hole left behind. For example, in
order for this reduction to work:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<float,3> A; // ...
Array<float,2> B; // ...
secondIndex j;
// Reduce over dimension 2 of a 3-D array?
B = sum(A, j);
</pre></td></tr></table></P><P>
Blitz++ would have to remap the dimensions so that the third dimension
became the second. It's not currently smart enough to do this.
</P><P>
However, there is a simple workaround which solves some of the problems
created by this limitation: you can do the reordering manually, prior to the
reduction:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>B = sum(A(i,k,j), k);
</pre></td></tr></table></P><P>
Writing <CODE>A(i,k,j)</CODE> interchanges the second and third dimensions,
permitting you to reduce over the second dimension. Here's a list of the
reduction operations currently supported:
</P><P>
<DL COMPACT>
<DT><CODE>sum()</CODE>
<DD>Summation
<P>
<DT><CODE>product()</CODE>
<DD>Product
<P>
<DT><CODE>mean()</CODE>
<DD>Arithmetic mean (promoted to floating-point type if necessary)
<P>
<DT><CODE>min()</CODE>
<DD>Minimum value
<P>
<DT><CODE>max()</CODE>
<DD>Maximum value
<P>
<DT><CODE>minIndex()</CODE>
<DD>Index of the minimum value (int)
<P>
<DT><CODE>maxIndex()</CODE>
<DD>Index of the maximum value (int)
<P>
<DT><CODE>count()</CODE>
<DD>Counts the number of times the expression is logical true (int)
<P>
<DT><CODE>any()</CODE>
<DD>True if the expression is true anywhere (bool)
<P>
<DT><CODE>all()</CODE>
<DD>True if the expression is true everywhere (bool)
<P>
<DT><CODE>first()</CODE>
<DD>First index at which the expression is logical true (int); if the expression
is logical true nowhere, then <CODE>tiny(int())</CODE> (INT_MIN) is returned.
<P>
<DT><CODE>last()</CODE>
<DD>Last index at which the expression is logical true (int); if the expression
is logical true nowhere, then <CODE>huge(int())</CODE> (INT_MAX) is returned.
</DL>
<P>
The reductions <CODE>any()</CODE>, <CODE>all()</CODE>, and <CODE>first()</CODE> have
short-circuit semantics: the reduction will halt as soon as the answer is
known. For example, if you use <CODE>any()</CODE>, scanning of the expression
will stop as soon as the first true value is encountered.
</P><P>
To illustrate, here's an example:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int, 2> A(4,4);
A = 3, 8, 0, 1,
1, -1, 9, 3,
2, -5, -1, 1,
4, 3, 4, 2;
Array<float, 1> z;
firstIndex i;
secondIndex j;
z = sum(A(j,i), j);
</pre></td></tr></table></P><P>
The array <CODE>z</CODE> now contains the sum of <CODE>A</CODE> along each column:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>[ 10 5 12 7 ]
</pre></td></tr></table></P><P>
This table shows what the result stored in <CODE>z</CODE> would be if
<CODE>sum()</CODE> were replaced with other reductions:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>sum [ 10 5 12 7 ]
mean [ 2.5 1.25 3 1.75 ]
min [ 1 -5 -1 1 ]
minIndex [ 1 2 2 0 ]
max [ 4 8 9 3 ]
maxIndex [ 3 0 1 1 ]
first((A < 0), j) [ -2147483648 1 2 -2147483648 ]
product [ 24 120 0 6 ]
count((A(j,i) > 0), j) [ 4 2 2 4 ]
any(abs(A(j,i)) > 4, j) [ 0 1 1 0 ]
all(A(j,i) > 0, j) [ 1 0 0 1 ]
</pre></td></tr></table></P><P>
Note: the odd numbers for first() are <CODE>tiny(int())</CODE> i.e. the smallest
number representable by an int. The exact value is machine-dependent.
</P><P>
<A NAME="IDX306"></A>
<A NAME="IDX307"></A>
<A NAME="IDX308"></A>
</P><P>
The result of a reduction is an array expression, so reductions
can be used as operands in an array expression:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,3> A;
Array<int,2> B;
Array<int,1> C; // ...
secondIndex j;
thirdIndex k;
B = sqrt(sum(sqr(A), k));
// Do two reductions in a row
C = sum(sum(A, k), j);
</pre></td></tr></table></P><P>
Note that this is not allowed:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>Array<int,2> A;
firstIndex i;
secondIndex j;
// Completely sum the array?
int result = sum(sum(A, j), i);
</pre></td></tr></table></P><P>
You cannot reduce an array to zero dimensions! Instead, use one of the
global functions described in the previous section.
</P><P>
<A NAME="Where expr"></A>
<HR SIZE="6">
<A NAME="SEC103"></A>
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC102"> < </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> > </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC80"> Up </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<H2> 3.15 where statements </H2>
<!--docid::SEC103::-->
<P>
Blitz++ provides the <CODE>where</CODE> function as an array expression version of the
<CODE>( ? : )</CODE> operator. The syntax is:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>where(array-expr1, array-expr2, array-expr3)
</pre></td></tr></table></P><P>
Wherever <CODE>array-expr1</CODE> is true, <CODE>array-expr2</CODE> is returned. Where
<CODE>array-expr1</CODE> is false, <CODE>array-expr3</CODE> is returned. For example,
suppose we wanted to sum the squares of only the positive elements of an
array. This can be implemented using a where function:
</P><P>
<TABLE><tr><td> </td><td class=example><pre>double posSquareSum = sum(where(A > 0, pow2(A), 0));
</pre></td></tr></table></P><P>
<A NAME="Stencils"></A>
<HR SIZE="6">
<TABLE CELLPADDING=1 CELLSPACING=1 BORDER=0>
<TR><TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_3.html#SEC82"> << </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_4.html#SEC104"> >> </A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT"> <TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz.html#SEC_Top">Top</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_toc.html#SEC_Contents">Contents</A>]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[Index]</TD>
<TD VALIGN="MIDDLE" ALIGN="LEFT">[<A HREF="blitz_abt.html#SEC_About"> ? </A>]</TD>
</TR></TABLE>
<BR>
<FONT SIZE="-1">
This document was generated
by <I>Julian Cummings</I> on <I>October, 14 2005</I>
using <A HREF="http://www.mathematik.uni-kl.de/~obachman/Texi2html
"><I>texi2html</I></A>
</BODY>
</HTML>
| gpl-2.0 |
xavierm02/lyx-mathpartir | src/mathed/InsetMathFontOld.cpp | 2314 | /**
* \file InsetMathFontOld.cpp
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* \author André Pönitz
*
* Full author contact details are available in file CREDITS.
*/
#include <config.h>
#include "InsetMathFontOld.h"
#include "MathData.h"
#include "MathParser.h"
#include "MathStream.h"
#include "MathSupport.h"
#include "MetricsInfo.h"
#include "support/gettext.h"
#include "support/lstrings.h"
#include <ostream>
using namespace lyx::support;
namespace lyx {
InsetMathFontOld::InsetMathFontOld(Buffer * buf, latexkeys const * key)
: InsetMathNest(buf, 1), key_(key), current_mode_(TEXT_MODE)
{
//lock(true);
}
Inset * InsetMathFontOld::clone() const
{
return new InsetMathFontOld(*this);
}
void InsetMathFontOld::metrics(MetricsInfo & mi, Dimension & dim) const
{
current_mode_ = isTextFont(from_ascii(mi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(mi.base, font, really_change_font);
cell(0).metrics(mi, dim);
metricsMarkers(dim);
}
void InsetMathFontOld::draw(PainterInfo & pi, int x, int y) const
{
current_mode_ = isTextFont(from_ascii(pi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(pi.base, font, really_change_font);
cell(0).draw(pi, x + 1, y);
drawMarkers(pi, x, y);
}
void InsetMathFontOld::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
{
cell(0).metricsT(mi, dim);
}
void InsetMathFontOld::drawT(TextPainter & pain, int x, int y) const
{
cell(0).drawT(pain, x, y);
}
void InsetMathFontOld::write(WriteStream & os) const
{
os << "{\\" << key_->name << ' ' << cell(0) << '}';
}
void InsetMathFontOld::normalize(NormalStream & os) const
{
os << "[font " << key_->name << ' ' << cell(0) << ']';
}
void InsetMathFontOld::infoize(odocstream & os) const
{
os << bformat(_("Font: %1$s"), key_->name);
}
} // namespace lyx
| gpl-2.0 |
djwong/linux-xfs-dev | sound/usb/quirks.c | 42173 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/usb/audio.h>
#include <linux/usb/midi.h>
#include <sound/control.h>
#include <sound/core.h>
#include <sound/info.h>
#include <sound/pcm.h>
#include "usbaudio.h"
#include "card.h"
#include "mixer.h"
#include "mixer_quirks.h"
#include "midi.h"
#include "quirks.h"
#include "helper.h"
#include "endpoint.h"
#include "pcm.h"
#include "clock.h"
#include "stream.h"
/*
* handle the quirks for the contained interfaces
*/
static int create_composite_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk_comp)
{
int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber;
const struct snd_usb_audio_quirk *quirk;
int err;
for (quirk = quirk_comp->data; quirk->ifnum >= 0; ++quirk) {
iface = usb_ifnum_to_if(chip->dev, quirk->ifnum);
if (!iface)
continue;
if (quirk->ifnum != probed_ifnum &&
usb_interface_claimed(iface))
continue;
err = snd_usb_create_quirk(chip, iface, driver, quirk);
if (err < 0)
return err;
}
for (quirk = quirk_comp->data; quirk->ifnum >= 0; ++quirk) {
iface = usb_ifnum_to_if(chip->dev, quirk->ifnum);
if (!iface)
continue;
if (quirk->ifnum != probed_ifnum &&
!usb_interface_claimed(iface))
usb_driver_claim_interface(driver, iface, (void *)-1L);
}
return 0;
}
static int ignore_interface_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
return 0;
}
/*
* Allow alignment on audio sub-slot (channel samples) rather than
* on audio slots (audio frames)
*/
static int create_align_transfer_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
chip->txfr_quirk = 1;
return 1; /* Continue with creating streams and mixer */
}
static int create_any_midi_quirk(struct snd_usb_audio *chip,
struct usb_interface *intf,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
return snd_usbmidi_create(chip->card, intf, &chip->midi_list, quirk);
}
/*
* create a stream for an interface with proper descriptors
*/
static int create_standard_audio_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
int err;
if (chip->usb_id == USB_ID(0x1686, 0x00dd)) /* Zoom R16/24 */
chip->tx_length_quirk = 1;
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
err = snd_usb_parse_audio_interface(chip, altsd->bInterfaceNumber);
if (err < 0) {
usb_audio_err(chip, "cannot setup if %d: error %d\n",
altsd->bInterfaceNumber, err);
return err;
}
/* reset the current interface */
usb_set_interface(chip->dev, altsd->bInterfaceNumber, 0);
return 0;
}
/*
* create a stream for an endpoint/altsetting without proper descriptors
*/
static int create_fixed_stream_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
struct audioformat *fp;
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
int stream, err;
unsigned *rate_table = NULL;
fp = kmemdup(quirk->data, sizeof(*fp), GFP_KERNEL);
if (!fp)
return -ENOMEM;
INIT_LIST_HEAD(&fp->list);
if (fp->nr_rates > MAX_NR_RATES) {
kfree(fp);
return -EINVAL;
}
if (fp->nr_rates > 0) {
rate_table = kmemdup(fp->rate_table,
sizeof(int) * fp->nr_rates, GFP_KERNEL);
if (!rate_table) {
kfree(fp);
return -ENOMEM;
}
fp->rate_table = rate_table;
}
stream = (fp->endpoint & USB_DIR_IN)
? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
err = snd_usb_add_audio_stream(chip, stream, fp);
if (err < 0)
goto error;
if (fp->iface != get_iface_desc(&iface->altsetting[0])->bInterfaceNumber ||
fp->altset_idx >= iface->num_altsetting) {
err = -EINVAL;
goto error;
}
alts = &iface->altsetting[fp->altset_idx];
altsd = get_iface_desc(alts);
if (altsd->bNumEndpoints < 1) {
err = -EINVAL;
goto error;
}
fp->protocol = altsd->bInterfaceProtocol;
if (fp->datainterval == 0)
fp->datainterval = snd_usb_parse_datainterval(chip, alts);
if (fp->maxpacksize == 0)
fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
usb_set_interface(chip->dev, fp->iface, 0);
snd_usb_init_pitch(chip, fp->iface, alts, fp);
snd_usb_init_sample_rate(chip, fp->iface, alts, fp, fp->rate_max);
return 0;
error:
list_del(&fp->list); /* unlink for avoiding double-free */
kfree(fp);
kfree(rate_table);
return err;
}
static int create_auto_pcm_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver)
{
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
struct usb_endpoint_descriptor *epd;
struct uac1_as_header_descriptor *ashd;
struct uac_format_type_i_discrete_descriptor *fmtd;
/*
* Most Roland/Yamaha audio streaming interfaces have more or less
* standard descriptors, but older devices might lack descriptors, and
* future ones might change, so ensure that we fail silently if the
* interface doesn't look exactly right.
*/
/* must have a non-zero altsetting for streaming */
if (iface->num_altsetting < 2)
return -ENODEV;
alts = &iface->altsetting[1];
altsd = get_iface_desc(alts);
/* must have an isochronous endpoint for streaming */
if (altsd->bNumEndpoints < 1)
return -ENODEV;
epd = get_endpoint(alts, 0);
if (!usb_endpoint_xfer_isoc(epd))
return -ENODEV;
/* must have format descriptors */
ashd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
UAC_AS_GENERAL);
fmtd = snd_usb_find_csint_desc(alts->extra, alts->extralen, NULL,
UAC_FORMAT_TYPE);
if (!ashd || ashd->bLength < 7 ||
!fmtd || fmtd->bLength < 8)
return -ENODEV;
return create_standard_audio_quirk(chip, iface, driver, NULL);
}
static int create_yamaha_midi_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
struct usb_host_interface *alts)
{
static const struct snd_usb_audio_quirk yamaha_midi_quirk = {
.type = QUIRK_MIDI_YAMAHA
};
struct usb_midi_in_jack_descriptor *injd;
struct usb_midi_out_jack_descriptor *outjd;
/* must have some valid jack descriptors */
injd = snd_usb_find_csint_desc(alts->extra, alts->extralen,
NULL, USB_MS_MIDI_IN_JACK);
outjd = snd_usb_find_csint_desc(alts->extra, alts->extralen,
NULL, USB_MS_MIDI_OUT_JACK);
if (!injd && !outjd)
return -ENODEV;
if (injd && (injd->bLength < 5 ||
(injd->bJackType != USB_MS_EMBEDDED &&
injd->bJackType != USB_MS_EXTERNAL)))
return -ENODEV;
if (outjd && (outjd->bLength < 6 ||
(outjd->bJackType != USB_MS_EMBEDDED &&
outjd->bJackType != USB_MS_EXTERNAL)))
return -ENODEV;
return create_any_midi_quirk(chip, iface, driver, &yamaha_midi_quirk);
}
static int create_roland_midi_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
struct usb_host_interface *alts)
{
static const struct snd_usb_audio_quirk roland_midi_quirk = {
.type = QUIRK_MIDI_ROLAND
};
u8 *roland_desc = NULL;
/* might have a vendor-specific descriptor <06 24 F1 02 ...> */
for (;;) {
roland_desc = snd_usb_find_csint_desc(alts->extra,
alts->extralen,
roland_desc, 0xf1);
if (!roland_desc)
return -ENODEV;
if (roland_desc[0] < 6 || roland_desc[3] != 2)
continue;
return create_any_midi_quirk(chip, iface, driver,
&roland_midi_quirk);
}
}
static int create_std_midi_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
struct usb_host_interface *alts)
{
struct usb_ms_header_descriptor *mshd;
struct usb_ms_endpoint_descriptor *msepd;
/* must have the MIDIStreaming interface header descriptor*/
mshd = (struct usb_ms_header_descriptor *)alts->extra;
if (alts->extralen < 7 ||
mshd->bLength < 7 ||
mshd->bDescriptorType != USB_DT_CS_INTERFACE ||
mshd->bDescriptorSubtype != USB_MS_HEADER)
return -ENODEV;
/* must have the MIDIStreaming endpoint descriptor*/
msepd = (struct usb_ms_endpoint_descriptor *)alts->endpoint[0].extra;
if (alts->endpoint[0].extralen < 4 ||
msepd->bLength < 4 ||
msepd->bDescriptorType != USB_DT_CS_ENDPOINT ||
msepd->bDescriptorSubtype != UAC_MS_GENERAL ||
msepd->bNumEmbMIDIJack < 1 ||
msepd->bNumEmbMIDIJack > 16)
return -ENODEV;
return create_any_midi_quirk(chip, iface, driver, NULL);
}
static int create_auto_midi_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver)
{
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
struct usb_endpoint_descriptor *epd;
int err;
alts = &iface->altsetting[0];
altsd = get_iface_desc(alts);
/* must have at least one bulk/interrupt endpoint for streaming */
if (altsd->bNumEndpoints < 1)
return -ENODEV;
epd = get_endpoint(alts, 0);
if (!usb_endpoint_xfer_bulk(epd) &&
!usb_endpoint_xfer_int(epd))
return -ENODEV;
switch (USB_ID_VENDOR(chip->usb_id)) {
case 0x0499: /* Yamaha */
err = create_yamaha_midi_quirk(chip, iface, driver, alts);
if (err != -ENODEV)
return err;
break;
case 0x0582: /* Roland */
err = create_roland_midi_quirk(chip, iface, driver, alts);
if (err != -ENODEV)
return err;
break;
}
return create_std_midi_quirk(chip, iface, driver, alts);
}
static int create_autodetect_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver)
{
int err;
err = create_auto_pcm_quirk(chip, iface, driver);
if (err == -ENODEV)
err = create_auto_midi_quirk(chip, iface, driver);
return err;
}
static int create_autodetect_quirks(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
int probed_ifnum = get_iface_desc(iface->altsetting)->bInterfaceNumber;
int ifcount, ifnum, err;
err = create_autodetect_quirk(chip, iface, driver);
if (err < 0)
return err;
/*
* ALSA PCM playback/capture devices cannot be registered in two steps,
* so we have to claim the other corresponding interface here.
*/
ifcount = chip->dev->actconfig->desc.bNumInterfaces;
for (ifnum = 0; ifnum < ifcount; ifnum++) {
if (ifnum == probed_ifnum || quirk->ifnum >= 0)
continue;
iface = usb_ifnum_to_if(chip->dev, ifnum);
if (!iface ||
usb_interface_claimed(iface) ||
get_iface_desc(iface->altsetting)->bInterfaceClass !=
USB_CLASS_VENDOR_SPEC)
continue;
err = create_autodetect_quirk(chip, iface, driver);
if (err >= 0)
usb_driver_claim_interface(driver, iface, (void *)-1L);
}
return 0;
}
/*
* Create a stream for an Edirol UA-700/UA-25/UA-4FX interface.
* The only way to detect the sample rate is by looking at wMaxPacketSize.
*/
static int create_uaxx_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
static const struct audioformat ua_format = {
.formats = SNDRV_PCM_FMTBIT_S24_3LE,
.channels = 2,
.fmt_type = UAC_FORMAT_TYPE_I,
.altsetting = 1,
.altset_idx = 1,
.rates = SNDRV_PCM_RATE_CONTINUOUS,
};
struct usb_host_interface *alts;
struct usb_interface_descriptor *altsd;
struct audioformat *fp;
int stream, err;
/* both PCM and MIDI interfaces have 2 or more altsettings */
if (iface->num_altsetting < 2)
return -ENXIO;
alts = &iface->altsetting[1];
altsd = get_iface_desc(alts);
if (altsd->bNumEndpoints == 2) {
static const struct snd_usb_midi_endpoint_info ua700_ep = {
.out_cables = 0x0003,
.in_cables = 0x0003
};
static const struct snd_usb_audio_quirk ua700_quirk = {
.type = QUIRK_MIDI_FIXED_ENDPOINT,
.data = &ua700_ep
};
static const struct snd_usb_midi_endpoint_info uaxx_ep = {
.out_cables = 0x0001,
.in_cables = 0x0001
};
static const struct snd_usb_audio_quirk uaxx_quirk = {
.type = QUIRK_MIDI_FIXED_ENDPOINT,
.data = &uaxx_ep
};
const struct snd_usb_audio_quirk *quirk =
chip->usb_id == USB_ID(0x0582, 0x002b)
? &ua700_quirk : &uaxx_quirk;
return __snd_usbmidi_create(chip->card, iface,
&chip->midi_list, quirk,
chip->usb_id);
}
if (altsd->bNumEndpoints != 1)
return -ENXIO;
fp = kmemdup(&ua_format, sizeof(*fp), GFP_KERNEL);
if (!fp)
return -ENOMEM;
fp->iface = altsd->bInterfaceNumber;
fp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;
fp->ep_attr = get_endpoint(alts, 0)->bmAttributes;
fp->datainterval = 0;
fp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);
INIT_LIST_HEAD(&fp->list);
switch (fp->maxpacksize) {
case 0x120:
fp->rate_max = fp->rate_min = 44100;
break;
case 0x138:
case 0x140:
fp->rate_max = fp->rate_min = 48000;
break;
case 0x258:
case 0x260:
fp->rate_max = fp->rate_min = 96000;
break;
default:
usb_audio_err(chip, "unknown sample rate\n");
kfree(fp);
return -ENXIO;
}
stream = (fp->endpoint & USB_DIR_IN)
? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;
err = snd_usb_add_audio_stream(chip, stream, fp);
if (err < 0) {
list_del(&fp->list); /* unlink for avoiding double-free */
kfree(fp);
return err;
}
usb_set_interface(chip->dev, fp->iface, 0);
return 0;
}
/*
* Create a standard mixer for the specified interface.
*/
static int create_standard_mixer_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
if (quirk->ifnum < 0)
return 0;
return snd_usb_create_mixer(chip, quirk->ifnum, 0);
}
/*
* audio-interface quirks
*
* returns zero if no standard audio/MIDI parsing is needed.
* returns a positive value if standard audio/midi interfaces are parsed
* after this.
* returns a negative value at error.
*/
int snd_usb_create_quirk(struct snd_usb_audio *chip,
struct usb_interface *iface,
struct usb_driver *driver,
const struct snd_usb_audio_quirk *quirk)
{
typedef int (*quirk_func_t)(struct snd_usb_audio *,
struct usb_interface *,
struct usb_driver *,
const struct snd_usb_audio_quirk *);
static const quirk_func_t quirk_funcs[] = {
[QUIRK_IGNORE_INTERFACE] = ignore_interface_quirk,
[QUIRK_COMPOSITE] = create_composite_quirk,
[QUIRK_AUTODETECT] = create_autodetect_quirks,
[QUIRK_MIDI_STANDARD_INTERFACE] = create_any_midi_quirk,
[QUIRK_MIDI_FIXED_ENDPOINT] = create_any_midi_quirk,
[QUIRK_MIDI_YAMAHA] = create_any_midi_quirk,
[QUIRK_MIDI_ROLAND] = create_any_midi_quirk,
[QUIRK_MIDI_MIDIMAN] = create_any_midi_quirk,
[QUIRK_MIDI_NOVATION] = create_any_midi_quirk,
[QUIRK_MIDI_RAW_BYTES] = create_any_midi_quirk,
[QUIRK_MIDI_EMAGIC] = create_any_midi_quirk,
[QUIRK_MIDI_CME] = create_any_midi_quirk,
[QUIRK_MIDI_AKAI] = create_any_midi_quirk,
[QUIRK_MIDI_FTDI] = create_any_midi_quirk,
[QUIRK_MIDI_CH345] = create_any_midi_quirk,
[QUIRK_AUDIO_STANDARD_INTERFACE] = create_standard_audio_quirk,
[QUIRK_AUDIO_FIXED_ENDPOINT] = create_fixed_stream_quirk,
[QUIRK_AUDIO_EDIROL_UAXX] = create_uaxx_quirk,
[QUIRK_AUDIO_ALIGN_TRANSFER] = create_align_transfer_quirk,
[QUIRK_AUDIO_STANDARD_MIXER] = create_standard_mixer_quirk,
};
if (quirk->type < QUIRK_TYPE_COUNT) {
return quirk_funcs[quirk->type](chip, iface, driver, quirk);
} else {
usb_audio_err(chip, "invalid quirk type %d\n", quirk->type);
return -ENXIO;
}
}
/*
* boot quirks
*/
#define EXTIGY_FIRMWARE_SIZE_OLD 794
#define EXTIGY_FIRMWARE_SIZE_NEW 483
static int snd_usb_extigy_boot_quirk(struct usb_device *dev, struct usb_interface *intf)
{
struct usb_host_config *config = dev->actconfig;
int err;
if (le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_OLD ||
le16_to_cpu(get_cfg_desc(config)->wTotalLength) == EXTIGY_FIRMWARE_SIZE_NEW) {
dev_dbg(&dev->dev, "sending Extigy boot sequence...\n");
/* Send message to force it to reconnect with full interface. */
err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev,0),
0x10, 0x43, 0x0001, 0x000a, NULL, 0);
if (err < 0)
dev_dbg(&dev->dev, "error sending boot message: %d\n", err);
err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
&dev->descriptor, sizeof(dev->descriptor));
config = dev->actconfig;
if (err < 0)
dev_dbg(&dev->dev, "error usb_get_descriptor: %d\n", err);
err = usb_reset_configuration(dev);
if (err < 0)
dev_dbg(&dev->dev, "error usb_reset_configuration: %d\n", err);
dev_dbg(&dev->dev, "extigy_boot: new boot length = %d\n",
le16_to_cpu(get_cfg_desc(config)->wTotalLength));
return -ENODEV; /* quit this anyway */
}
return 0;
}
static int snd_usb_audigy2nx_boot_quirk(struct usb_device *dev)
{
u8 buf = 1;
snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0), 0x2a,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_OTHER,
0, 0, &buf, 1);
if (buf == 0) {
snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0x29,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_OTHER,
1, 2000, NULL, 0);
return -ENODEV;
}
return 0;
}
static int snd_usb_fasttrackpro_boot_quirk(struct usb_device *dev)
{
int err;
if (dev->actconfig->desc.bConfigurationValue == 1) {
dev_info(&dev->dev,
"Fast Track Pro switching to config #2\n");
/* This function has to be available by the usb core module.
* if it is not avialable the boot quirk has to be left out
* and the configuration has to be set by udev or hotplug
* rules
*/
err = usb_driver_set_configuration(dev, 2);
if (err < 0)
dev_dbg(&dev->dev,
"error usb_driver_set_configuration: %d\n",
err);
/* Always return an error, so that we stop creating a device
that will just be destroyed and recreated with a new
configuration */
return -ENODEV;
} else
dev_info(&dev->dev, "Fast Track Pro config OK\n");
return 0;
}
/*
* C-Media CM106/CM106+ have four 16-bit internal registers that are nicely
* documented in the device's data sheet.
*/
static int snd_usb_cm106_write_int_reg(struct usb_device *dev, int reg, u16 value)
{
u8 buf[4];
buf[0] = 0x20;
buf[1] = value & 0xff;
buf[2] = (value >> 8) & 0xff;
buf[3] = reg;
return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), USB_REQ_SET_CONFIGURATION,
USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT,
0, 0, &buf, 4);
}
static int snd_usb_cm106_boot_quirk(struct usb_device *dev)
{
/*
* Enable line-out driver mode, set headphone source to front
* channels, enable stereo mic.
*/
return snd_usb_cm106_write_int_reg(dev, 2, 0x8004);
}
/*
* C-Media CM6206 is based on CM106 with two additional
* registers that are not documented in the data sheet.
* Values here are chosen based on sniffing USB traffic
* under Windows.
*/
static int snd_usb_cm6206_boot_quirk(struct usb_device *dev)
{
int err = 0, reg;
int val[] = {0x2004, 0x3000, 0xf800, 0x143f, 0x0000, 0x3000};
for (reg = 0; reg < ARRAY_SIZE(val); reg++) {
err = snd_usb_cm106_write_int_reg(dev, reg, val[reg]);
if (err < 0)
return err;
}
return err;
}
/* quirk for Plantronics GameCom 780 with CM6302 chip */
static int snd_usb_gamecon780_boot_quirk(struct usb_device *dev)
{
/* set the initial volume and don't change; other values are either
* too loud or silent due to firmware bug (bko#65251)
*/
u8 buf[2] = { 0x74, 0xe3 };
return snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), UAC_SET_CUR,
USB_RECIP_INTERFACE | USB_TYPE_CLASS | USB_DIR_OUT,
UAC_FU_VOLUME << 8, 9 << 8, buf, 2);
}
/*
* Novation Twitch DJ controller
* Focusrite Novation Saffire 6 USB audio card
*/
static int snd_usb_novation_boot_quirk(struct usb_device *dev)
{
/* preemptively set up the device because otherwise the
* raw MIDI endpoints are not active */
usb_set_interface(dev, 0, 1);
return 0;
}
/*
* This call will put the synth in "USB send" mode, i.e it will send MIDI
* messages through USB (this is disabled at startup). The synth will
* acknowledge by sending a sysex on endpoint 0x85 and by displaying a USB
* sign on its LCD. Values here are chosen based on sniffing USB traffic
* under Windows.
*/
static int snd_usb_accessmusic_boot_quirk(struct usb_device *dev)
{
int err, actual_length;
/* "midi send" enable */
static const u8 seq[] = { 0x4e, 0x73, 0x52, 0x01 };
void *buf = kmemdup(seq, ARRAY_SIZE(seq), GFP_KERNEL);
if (!buf)
return -ENOMEM;
err = usb_interrupt_msg(dev, usb_sndintpipe(dev, 0x05), buf,
ARRAY_SIZE(seq), &actual_length, 1000);
kfree(buf);
if (err < 0)
return err;
return 0;
}
/*
* Some sound cards from Native Instruments are in fact compliant to the USB
* audio standard of version 2 and other approved USB standards, even though
* they come up as vendor-specific device when first connected.
*
* However, they can be told to come up with a new set of descriptors
* upon their next enumeration, and the interfaces announced by the new
* descriptors will then be handled by the kernel's class drivers. As the
* product ID will also change, no further checks are required.
*/
static int snd_usb_nativeinstruments_boot_quirk(struct usb_device *dev)
{
int ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
0xaf, USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1, 0, NULL, 0, 1000);
if (ret < 0)
return ret;
usb_reset_device(dev);
/* return -EAGAIN, so the creation of an audio interface for this
* temporary device is aborted. The device will reconnect with a
* new product ID */
return -EAGAIN;
}
static void mbox2_setup_48_24_magic(struct usb_device *dev)
{
u8 srate[3];
u8 temp[12];
/* Choose 48000Hz permanently */
srate[0] = 0x80;
srate[1] = 0xbb;
srate[2] = 0x00;
/* Send the magic! */
snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
0x01, 0x22, 0x0100, 0x0085, &temp, 0x0003);
snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0),
0x81, 0xa2, 0x0100, 0x0085, &srate, 0x0003);
snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0),
0x81, 0xa2, 0x0100, 0x0086, &srate, 0x0003);
snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0),
0x81, 0xa2, 0x0100, 0x0003, &srate, 0x0003);
return;
}
/* Digidesign Mbox 2 needs to load firmware onboard
* and driver must wait a few seconds for initialisation.
*/
#define MBOX2_FIRMWARE_SIZE 646
#define MBOX2_BOOT_LOADING 0x01 /* Hard coded into the device */
#define MBOX2_BOOT_READY 0x02 /* Hard coded into the device */
static int snd_usb_mbox2_boot_quirk(struct usb_device *dev)
{
struct usb_host_config *config = dev->actconfig;
int err;
u8 bootresponse[0x12];
int fwsize;
int count;
fwsize = le16_to_cpu(get_cfg_desc(config)->wTotalLength);
if (fwsize != MBOX2_FIRMWARE_SIZE) {
dev_err(&dev->dev, "Invalid firmware size=%d.\n", fwsize);
return -ENODEV;
}
dev_dbg(&dev->dev, "Sending Digidesign Mbox 2 boot sequence...\n");
count = 0;
bootresponse[0] = MBOX2_BOOT_LOADING;
while ((bootresponse[0] == MBOX2_BOOT_LOADING) && (count < 10)) {
msleep(500); /* 0.5 second delay */
snd_usb_ctl_msg(dev, usb_rcvctrlpipe(dev, 0),
/* Control magic - load onboard firmware */
0x85, 0xc0, 0x0001, 0x0000, &bootresponse, 0x0012);
if (bootresponse[0] == MBOX2_BOOT_READY)
break;
dev_dbg(&dev->dev, "device not ready, resending boot sequence...\n");
count++;
}
if (bootresponse[0] != MBOX2_BOOT_READY) {
dev_err(&dev->dev, "Unknown bootresponse=%d, or timed out, ignoring device.\n", bootresponse[0]);
return -ENODEV;
}
dev_dbg(&dev->dev, "device initialised!\n");
err = usb_get_descriptor(dev, USB_DT_DEVICE, 0,
&dev->descriptor, sizeof(dev->descriptor));
config = dev->actconfig;
if (err < 0)
dev_dbg(&dev->dev, "error usb_get_descriptor: %d\n", err);
err = usb_reset_configuration(dev);
if (err < 0)
dev_dbg(&dev->dev, "error usb_reset_configuration: %d\n", err);
dev_dbg(&dev->dev, "mbox2_boot: new boot length = %d\n",
le16_to_cpu(get_cfg_desc(config)->wTotalLength));
mbox2_setup_48_24_magic(dev);
dev_info(&dev->dev, "Digidesign Mbox 2: 24bit 48kHz");
return 0; /* Successful boot */
}
/*
* Setup quirks
*/
#define MAUDIO_SET 0x01 /* parse device_setup */
#define MAUDIO_SET_COMPATIBLE 0x80 /* use only "win-compatible" interfaces */
#define MAUDIO_SET_DTS 0x02 /* enable DTS Digital Output */
#define MAUDIO_SET_96K 0x04 /* 48-96KHz rate if set, 8-48KHz otherwise */
#define MAUDIO_SET_24B 0x08 /* 24bits sample if set, 16bits otherwise */
#define MAUDIO_SET_DI 0x10 /* enable Digital Input */
#define MAUDIO_SET_MASK 0x1f /* bit mask for setup value */
#define MAUDIO_SET_24B_48K_DI 0x19 /* 24bits+48KHz+Digital Input */
#define MAUDIO_SET_24B_48K_NOTDI 0x09 /* 24bits+48KHz+No Digital Input */
#define MAUDIO_SET_16B_48K_DI 0x11 /* 16bits+48KHz+Digital Input */
#define MAUDIO_SET_16B_48K_NOTDI 0x01 /* 16bits+48KHz+No Digital Input */
static int quattro_skip_setting_quirk(struct snd_usb_audio *chip,
int iface, int altno)
{
/* Reset ALL ifaces to 0 altsetting.
* Call it for every possible altsetting of every interface.
*/
usb_set_interface(chip->dev, iface, 0);
if (chip->setup & MAUDIO_SET) {
if (chip->setup & MAUDIO_SET_COMPATIBLE) {
if (iface != 1 && iface != 2)
return 1; /* skip all interfaces but 1 and 2 */
} else {
unsigned int mask;
if (iface == 1 || iface == 2)
return 1; /* skip interfaces 1 and 2 */
if ((chip->setup & MAUDIO_SET_96K) && altno != 1)
return 1; /* skip this altsetting */
mask = chip->setup & MAUDIO_SET_MASK;
if (mask == MAUDIO_SET_24B_48K_DI && altno != 2)
return 1; /* skip this altsetting */
if (mask == MAUDIO_SET_24B_48K_NOTDI && altno != 3)
return 1; /* skip this altsetting */
if (mask == MAUDIO_SET_16B_48K_NOTDI && altno != 4)
return 1; /* skip this altsetting */
}
}
usb_audio_dbg(chip,
"using altsetting %d for interface %d config %d\n",
altno, iface, chip->setup);
return 0; /* keep this altsetting */
}
static int audiophile_skip_setting_quirk(struct snd_usb_audio *chip,
int iface,
int altno)
{
/* Reset ALL ifaces to 0 altsetting.
* Call it for every possible altsetting of every interface.
*/
usb_set_interface(chip->dev, iface, 0);
if (chip->setup & MAUDIO_SET) {
unsigned int mask;
if ((chip->setup & MAUDIO_SET_DTS) && altno != 6)
return 1; /* skip this altsetting */
if ((chip->setup & MAUDIO_SET_96K) && altno != 1)
return 1; /* skip this altsetting */
mask = chip->setup & MAUDIO_SET_MASK;
if (mask == MAUDIO_SET_24B_48K_DI && altno != 2)
return 1; /* skip this altsetting */
if (mask == MAUDIO_SET_24B_48K_NOTDI && altno != 3)
return 1; /* skip this altsetting */
if (mask == MAUDIO_SET_16B_48K_DI && altno != 4)
return 1; /* skip this altsetting */
if (mask == MAUDIO_SET_16B_48K_NOTDI && altno != 5)
return 1; /* skip this altsetting */
}
return 0; /* keep this altsetting */
}
static int fasttrackpro_skip_setting_quirk(struct snd_usb_audio *chip,
int iface, int altno)
{
/* Reset ALL ifaces to 0 altsetting.
* Call it for every possible altsetting of every interface.
*/
usb_set_interface(chip->dev, iface, 0);
/* possible configuration where both inputs and only one output is
*used is not supported by the current setup
*/
if (chip->setup & (MAUDIO_SET | MAUDIO_SET_24B)) {
if (chip->setup & MAUDIO_SET_96K) {
if (altno != 3 && altno != 6)
return 1;
} else if (chip->setup & MAUDIO_SET_DI) {
if (iface == 4)
return 1; /* no analog input */
if (altno != 2 && altno != 5)
return 1; /* enable only altsets 2 and 5 */
} else {
if (iface == 5)
return 1; /* disable digialt input */
if (altno != 2 && altno != 5)
return 1; /* enalbe only altsets 2 and 5 */
}
} else {
/* keep only 16-Bit mode */
if (altno != 1)
return 1;
}
usb_audio_dbg(chip,
"using altsetting %d for interface %d config %d\n",
altno, iface, chip->setup);
return 0; /* keep this altsetting */
}
int snd_usb_apply_interface_quirk(struct snd_usb_audio *chip,
int iface,
int altno)
{
/* audiophile usb: skip altsets incompatible with device_setup */
if (chip->usb_id == USB_ID(0x0763, 0x2003))
return audiophile_skip_setting_quirk(chip, iface, altno);
/* quattro usb: skip altsets incompatible with device_setup */
if (chip->usb_id == USB_ID(0x0763, 0x2001))
return quattro_skip_setting_quirk(chip, iface, altno);
/* fasttrackpro usb: skip altsets incompatible with device_setup */
if (chip->usb_id == USB_ID(0x0763, 0x2012))
return fasttrackpro_skip_setting_quirk(chip, iface, altno);
return 0;
}
int snd_usb_apply_boot_quirk(struct usb_device *dev,
struct usb_interface *intf,
const struct snd_usb_audio_quirk *quirk,
unsigned int id)
{
switch (id) {
case USB_ID(0x041e, 0x3000):
/* SB Extigy needs special boot-up sequence */
/* if more models come, this will go to the quirk list. */
return snd_usb_extigy_boot_quirk(dev, intf);
case USB_ID(0x041e, 0x3020):
/* SB Audigy 2 NX needs its own boot-up magic, too */
return snd_usb_audigy2nx_boot_quirk(dev);
case USB_ID(0x10f5, 0x0200):
/* C-Media CM106 / Turtle Beach Audio Advantage Roadie */
return snd_usb_cm106_boot_quirk(dev);
case USB_ID(0x0d8c, 0x0102):
/* C-Media CM6206 / CM106-Like Sound Device */
case USB_ID(0x0ccd, 0x00b1): /* Terratec Aureon 7.1 USB */
return snd_usb_cm6206_boot_quirk(dev);
case USB_ID(0x0dba, 0x3000):
/* Digidesign Mbox 2 */
return snd_usb_mbox2_boot_quirk(dev);
case USB_ID(0x1235, 0x0010): /* Focusrite Novation Saffire 6 USB */
case USB_ID(0x1235, 0x0018): /* Focusrite Novation Twitch */
return snd_usb_novation_boot_quirk(dev);
case USB_ID(0x133e, 0x0815):
/* Access Music VirusTI Desktop */
return snd_usb_accessmusic_boot_quirk(dev);
case USB_ID(0x17cc, 0x1000): /* Komplete Audio 6 */
case USB_ID(0x17cc, 0x1010): /* Traktor Audio 6 */
case USB_ID(0x17cc, 0x1020): /* Traktor Audio 10 */
return snd_usb_nativeinstruments_boot_quirk(dev);
case USB_ID(0x0763, 0x2012): /* M-Audio Fast Track Pro USB */
return snd_usb_fasttrackpro_boot_quirk(dev);
case USB_ID(0x047f, 0xc010): /* Plantronics Gamecom 780 */
return snd_usb_gamecon780_boot_quirk(dev);
}
return 0;
}
/*
* check if the device uses big-endian samples
*/
int snd_usb_is_big_endian_format(struct snd_usb_audio *chip, struct audioformat *fp)
{
/* it depends on altsetting whether the device is big-endian or not */
switch (chip->usb_id) {
case USB_ID(0x0763, 0x2001): /* M-Audio Quattro: captured data only */
if (fp->altsetting == 2 || fp->altsetting == 3 ||
fp->altsetting == 5 || fp->altsetting == 6)
return 1;
break;
case USB_ID(0x0763, 0x2003): /* M-Audio Audiophile USB */
if (chip->setup == 0x00 ||
fp->altsetting == 1 || fp->altsetting == 2 ||
fp->altsetting == 3)
return 1;
break;
case USB_ID(0x0763, 0x2012): /* M-Audio Fast Track Pro */
if (fp->altsetting == 2 || fp->altsetting == 3 ||
fp->altsetting == 5 || fp->altsetting == 6)
return 1;
break;
}
return 0;
}
/*
* For E-Mu 0404USB/0202USB/TrackerPre/0204 sample rate should be set for device,
* not for interface.
*/
enum {
EMU_QUIRK_SR_44100HZ = 0,
EMU_QUIRK_SR_48000HZ,
EMU_QUIRK_SR_88200HZ,
EMU_QUIRK_SR_96000HZ,
EMU_QUIRK_SR_176400HZ,
EMU_QUIRK_SR_192000HZ
};
static void set_format_emu_quirk(struct snd_usb_substream *subs,
struct audioformat *fmt)
{
unsigned char emu_samplerate_id = 0;
/* When capture is active
* sample rate shouldn't be changed
* by playback substream
*/
if (subs->direction == SNDRV_PCM_STREAM_PLAYBACK) {
if (subs->stream->substream[SNDRV_PCM_STREAM_CAPTURE].interface != -1)
return;
}
switch (fmt->rate_min) {
case 48000:
emu_samplerate_id = EMU_QUIRK_SR_48000HZ;
break;
case 88200:
emu_samplerate_id = EMU_QUIRK_SR_88200HZ;
break;
case 96000:
emu_samplerate_id = EMU_QUIRK_SR_96000HZ;
break;
case 176400:
emu_samplerate_id = EMU_QUIRK_SR_176400HZ;
break;
case 192000:
emu_samplerate_id = EMU_QUIRK_SR_192000HZ;
break;
default:
emu_samplerate_id = EMU_QUIRK_SR_44100HZ;
break;
}
snd_emuusb_set_samplerate(subs->stream->chip, emu_samplerate_id);
subs->pkt_offset_adj = (emu_samplerate_id >= EMU_QUIRK_SR_176400HZ) ? 4 : 0;
}
void snd_usb_set_format_quirk(struct snd_usb_substream *subs,
struct audioformat *fmt)
{
switch (subs->stream->chip->usb_id) {
case USB_ID(0x041e, 0x3f02): /* E-Mu 0202 USB */
case USB_ID(0x041e, 0x3f04): /* E-Mu 0404 USB */
case USB_ID(0x041e, 0x3f0a): /* E-Mu Tracker Pre */
case USB_ID(0x041e, 0x3f19): /* E-Mu 0204 USB */
set_format_emu_quirk(subs, fmt);
break;
}
}
bool snd_usb_get_sample_rate_quirk(struct snd_usb_audio *chip)
{
/* devices which do not support reading the sample rate. */
switch (chip->usb_id) {
case USB_ID(0x041E, 0x4080): /* Creative Live Cam VF0610 */
case USB_ID(0x04D8, 0xFEEA): /* Benchmark DAC1 Pre */
case USB_ID(0x0556, 0x0014): /* Phoenix Audio TMX320VC */
case USB_ID(0x05A3, 0x9420): /* ELP HD USB Camera */
case USB_ID(0x074D, 0x3553): /* Outlaw RR2150 (Micronas UAC3553B) */
case USB_ID(0x1395, 0x740a): /* Sennheiser DECT */
case USB_ID(0x1901, 0x0191): /* GE B850V3 CP2114 audio interface */
case USB_ID(0x21B4, 0x0081): /* AudioQuest DragonFly */
return true;
}
/* devices of these vendors don't support reading rate, either */
switch (USB_ID_VENDOR(chip->usb_id)) {
case 0x045E: /* MS Lifecam */
case 0x047F: /* Plantronics */
case 0x1de7: /* Phoenix Audio */
return true;
}
return false;
}
/* Marantz/Denon USB DACs need a vendor cmd to switch
* between PCM and native DSD mode
*/
static bool is_marantz_denon_dac(unsigned int id)
{
switch (id) {
case USB_ID(0x154e, 0x1003): /* Denon DA-300USB */
case USB_ID(0x154e, 0x3005): /* Marantz HD-DAC1 */
case USB_ID(0x154e, 0x3006): /* Marantz SA-14S1 */
return true;
}
return false;
}
/* TEAC UD-501/UD-503/NT-503 USB DACs need a vendor cmd to switch
* between PCM/DOP and native DSD mode
*/
static bool is_teac_dsd_dac(unsigned int id)
{
switch (id) {
case USB_ID(0x0644, 0x8043): /* TEAC UD-501/UD-503/NT-503 */
case USB_ID(0x0644, 0x8044): /* Esoteric D-05X */
case USB_ID(0x0644, 0x804a): /* TEAC UD-301 */
return true;
}
return false;
}
int snd_usb_select_mode_quirk(struct snd_usb_substream *subs,
struct audioformat *fmt)
{
struct usb_device *dev = subs->dev;
int err;
if (is_marantz_denon_dac(subs->stream->chip->usb_id)) {
/* First switch to alt set 0, otherwise the mode switch cmd
* will not be accepted by the DAC
*/
err = usb_set_interface(dev, fmt->iface, 0);
if (err < 0)
return err;
mdelay(20); /* Delay needed after setting the interface */
switch (fmt->altsetting) {
case 2: /* DSD mode requested */
case 1: /* PCM mode requested */
err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0,
USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
fmt->altsetting - 1, 1, NULL, 0);
if (err < 0)
return err;
break;
}
mdelay(20);
} else if (is_teac_dsd_dac(subs->stream->chip->usb_id)) {
/* Vendor mode switch cmd is required. */
switch (fmt->altsetting) {
case 3: /* DSD mode (DSD_U32) requested */
err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0,
USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
1, 1, NULL, 0);
if (err < 0)
return err;
break;
case 2: /* PCM or DOP mode (S32) requested */
case 1: /* PCM mode (S16) requested */
err = snd_usb_ctl_msg(dev, usb_sndctrlpipe(dev, 0), 0,
USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE,
0, 1, NULL, 0);
if (err < 0)
return err;
break;
}
}
return 0;
}
void snd_usb_endpoint_start_quirk(struct snd_usb_endpoint *ep)
{
/*
* "Playback Design" products send bogus feedback data at the start
* of the stream. Ignore them.
*/
if (USB_ID_VENDOR(ep->chip->usb_id) == 0x23ba &&
ep->type == SND_USB_ENDPOINT_TYPE_SYNC)
ep->skip_packets = 4;
/*
* M-Audio Fast Track C400/C600 - when packets are not skipped, real
* world latency varies by approx. +/- 50 frames (at 96KHz) each time
* the stream is (re)started. When skipping packets 16 at endpoint
* start up, the real world latency is stable within +/- 1 frame (also
* across power cycles).
*/
if ((ep->chip->usb_id == USB_ID(0x0763, 0x2030) ||
ep->chip->usb_id == USB_ID(0x0763, 0x2031)) &&
ep->type == SND_USB_ENDPOINT_TYPE_DATA)
ep->skip_packets = 16;
/* Work around devices that report unreasonable feedback data */
if ((ep->chip->usb_id == USB_ID(0x0644, 0x8038) || /* TEAC UD-H01 */
ep->chip->usb_id == USB_ID(0x1852, 0x5034)) && /* T+A Dac8 */
ep->syncmaxsize == 4)
ep->tenor_fb_quirk = 1;
}
void snd_usb_set_interface_quirk(struct usb_device *dev)
{
struct snd_usb_audio *chip = dev_get_drvdata(&dev->dev);
if (!chip)
return;
/*
* "Playback Design" products need a 50ms delay after setting the
* USB interface.
*/
switch (USB_ID_VENDOR(chip->usb_id)) {
case 0x23ba: /* Playback Design */
case 0x0644: /* TEAC Corp. */
mdelay(50);
break;
}
}
/* quirk applied after snd_usb_ctl_msg(); not applied during boot quirks */
void snd_usb_ctl_msg_quirk(struct usb_device *dev, unsigned int pipe,
__u8 request, __u8 requesttype, __u16 value,
__u16 index, void *data, __u16 size)
{
struct snd_usb_audio *chip = dev_get_drvdata(&dev->dev);
if (!chip)
return;
/*
* "Playback Design" products need a 20ms delay after each
* class compliant request
*/
if (USB_ID_VENDOR(chip->usb_id) == 0x23ba &&
(requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS)
mdelay(20);
/*
* "TEAC Corp." products need a 20ms delay after each
* class compliant request
*/
if (USB_ID_VENDOR(chip->usb_id) == 0x0644 &&
(requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS)
mdelay(20);
/* Marantz/Denon devices with USB DAC functionality need a delay
* after each class compliant request
*/
if (is_marantz_denon_dac(chip->usb_id)
&& (requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS)
mdelay(20);
/* Zoom R16/24, Logitech H650e, Jabra 550a needs a tiny delay here,
* otherwise requests like get/set frequency return as failed despite
* actually succeeding.
*/
if ((chip->usb_id == USB_ID(0x1686, 0x00dd) ||
chip->usb_id == USB_ID(0x046d, 0x0a46) ||
chip->usb_id == USB_ID(0x0b0e, 0x0349)) &&
(requesttype & USB_TYPE_MASK) == USB_TYPE_CLASS)
mdelay(1);
}
/*
* snd_usb_interface_dsd_format_quirks() is called from format.c to
* augment the PCM format bit-field for DSD types. The UAC standards
* don't have a designated bit field to denote DSD-capable interfaces,
* hence all hardware that is known to support this format has to be
* listed here.
*/
u64 snd_usb_interface_dsd_format_quirks(struct snd_usb_audio *chip,
struct audioformat *fp,
unsigned int sample_bytes)
{
/* Playback Designs */
if (USB_ID_VENDOR(chip->usb_id) == 0x23ba) {
switch (fp->altsetting) {
case 1:
fp->dsd_dop = true;
return SNDRV_PCM_FMTBIT_DSD_U16_LE;
case 2:
fp->dsd_bitrev = true;
return SNDRV_PCM_FMTBIT_DSD_U8;
case 3:
fp->dsd_bitrev = true;
return SNDRV_PCM_FMTBIT_DSD_U16_LE;
}
}
/* XMOS based USB DACs */
switch (chip->usb_id) {
case USB_ID(0x20b1, 0x3008): /* iFi Audio micro/nano iDSD */
case USB_ID(0x20b1, 0x2008): /* Matrix Audio X-Sabre */
case USB_ID(0x20b1, 0x300a): /* Matrix Audio Mini-i Pro */
case USB_ID(0x22d9, 0x0416): /* OPPO HA-1 */
case USB_ID(0x2772, 0x0230): /* Pro-Ject Pre Box S2 Digital */
if (fp->altsetting == 2)
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
break;
case USB_ID(0x20b1, 0x000a): /* Gustard DAC-X20U */
case USB_ID(0x20b1, 0x2009): /* DIYINHK DSD DXD 384kHz USB to I2S/DSD */
case USB_ID(0x20b1, 0x2023): /* JLsounds I2SoverUSB */
case USB_ID(0x20b1, 0x3023): /* Aune X1S 32BIT/384 DSD DAC */
case USB_ID(0x2616, 0x0106): /* PS Audio NuWave DAC */
if (fp->altsetting == 3)
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
break;
/* Amanero Combo384 USB based DACs with native DSD support */
case USB_ID(0x16d0, 0x071a): /* Amanero - Combo384 */
case USB_ID(0x2ab6, 0x0004): /* T+A DAC8DSD-V2.0, MP1000E-V2.0, MP2000R-V2.0, MP2500R-V2.0, MP3100HV-V2.0 */
case USB_ID(0x2ab6, 0x0005): /* T+A USB HD Audio 1 */
case USB_ID(0x2ab6, 0x0006): /* T+A USB HD Audio 2 */
if (fp->altsetting == 2) {
switch (le16_to_cpu(chip->dev->descriptor.bcdDevice)) {
case 0x199:
return SNDRV_PCM_FMTBIT_DSD_U32_LE;
case 0x19b:
case 0x203:
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
default:
break;
}
}
break;
case USB_ID(0x16d0, 0x0a23):
if (fp->altsetting == 2)
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
break;
default:
break;
}
/* Denon/Marantz devices with USB DAC functionality */
if (is_marantz_denon_dac(chip->usb_id)) {
if (fp->altsetting == 2)
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
}
/* TEAC devices with USB DAC functionality */
if (is_teac_dsd_dac(chip->usb_id)) {
if (fp->altsetting == 3)
return SNDRV_PCM_FMTBIT_DSD_U32_BE;
}
return 0;
}
| gpl-2.0 |
tstephen/srp-digital | wp-content/plugins/jetpack/_inc/build/shortcodes/js/recipes.min.asset.php | 95 | <?php return array('dependencies' => array(), 'version' => 'a8dca9f7d5fd098db5af94613d2a8ec0'); | gpl-2.0 |
RGray1959/MyParish | CmsWeb/Areas/Search/Models/SavedQuery/SavedQueryModel.cs | 4459 | using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using CmsData;
using CmsWeb.Models;
using UtilityExtensions;
using Query = CmsData.Query;
namespace CmsWeb.Areas.Search.Models
{
public class SavedQueryModel : PagedTableModel<Query, SavedQueryInfo>
{
public bool admin { get; set; }
public bool OnlyMine { get; set; }
public bool PublicOnly { get; set; }
public string SearchQuery { get; set; }
public bool ScratchPadsOnly { get; set; }
public bool StatusFlagsOnly { get; set; }
public SavedQueryModel() : base("Last Run", "desc", true)
{
admin = Roles.IsUserInRole("Admin");
}
public override IQueryable<Query> DefineModelList()
{
var q = from c in DbUtil.Db.Queries
where !PublicOnly || c.Ispublic
where c.Name.Contains(SearchQuery) || c.Owner == SearchQuery || !SearchQuery.HasValue()
select c;
if (ScratchPadsOnly)
q = from c in q
where c.Name == Util.ScratchPad2
select c;
else
q = from c in q
where c.Name != Util.ScratchPad2
select c;
if (StatusFlagsOnly)
q = from c in q
where StatusFlagsOnly == false || SqlMethods.Like(c.Name, "F[0-9][0-9]%")
select c;
DbUtil.Db.SetUserPreference("SavedQueryOnlyMine", OnlyMine);
if (OnlyMine)
q = from c in q
where c.Owner == Util.UserName
select c;
else if (!admin)
q = from c in q
where c.Owner == Util.UserName || c.Ispublic
select c;
return q;
}
public override IQueryable<Query> DefineModelSort(IQueryable<Query> q)
{
switch (SortExpression)
{
case "Public":
return from c in q
orderby c.Ispublic, c.Owner, c.Name
select c;
case "Description":
return from c in q
orderby c.Name
select c;
case "Last Run":
return from c in q
orderby c.LastRun ?? c.Created
select c;
case "Owner":
return from c in q
orderby c.Owner, c.Name
select c;
case "Count":
return from c in q
orderby c.RunCount, c.Name
select c;
case "Public desc":
return from c in q
orderby c.Ispublic descending, c.Owner, c.Name
select c;
case "Description desc":
return from c in q
orderby c.Name descending
select c;
case "Last Run desc":
return from c in q
let dt = c.LastRun ?? c.Created
orderby dt descending
select c;
case "Owner desc":
return from c in q
orderby c.Owner descending, c.Name
select c;
case "Count desc":
return from c in q
orderby c.RunCount descending, c.Name
select c;
}
return q;
}
public override IEnumerable<SavedQueryInfo> DefineViewList(IQueryable<Query> q)
{
var user = Util.UserName;
return from c in q
select new SavedQueryInfo
{
QueryId = c.QueryId,
Name = c.Name,
Ispublic = c.Ispublic,
LastRun = c.LastRun ?? c.Created,
Owner = c.Owner,
CanDelete = admin || c.Owner == user,
RunCount = c.RunCount,
};
}
}
} | gpl-2.0 |
sevenbot/antispamsevenn | bot/seedbot.lua | 10194 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin"
},
sudo_users = {95822747},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Admins
@iwals [Founder]
@imandaneshi [Developer]
@Rondoozle [Developer]
@seyedan25 [Manager]
Special thanks to
awkward_potato
Siyanew
topkecleon
Vamptacus
Our channels
@teleseedch [English]
@iranseed [persian]
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Grt a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
**U can use both "/" and "!"
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
tianya3796/linux2.6.9 | sound/parisc/harmony.c | 34487 | /*
* Harmony chipset driver
*
* This is a sound driver for ASP's and Lasi's Harmony sound chip
* and is unlikely to be used for anything other than on a HP PA-RISC.
*
* Harmony is found in HP 712s, 715/new and many other GSC based machines.
* On older 715 machines you'll find the technically identical chip
* called 'Vivace'. Both Harmony and Vivace are supported by this driver.
*
* this ALSA driver is based on OSS driver by:
* Copyright 2000 (c) Linuxcare Canada, Alex deVries <[email protected]>
* Copyright 2000-2002 (c) Helge Deller <[email protected]>
* Copyright 2001 (c) Matthieu Delahaye <[email protected]>
*
* TODO:
* - use generic DMA interface and ioremap()/iounmap()
* - capture is still untested (and probaby non-working)
* - spin locks
* - implement non-consistent DMA pages
* - implement gain meter
* - module parameters
* - correct cleaning sequence
* - better error checking
* - try to have a better quality.
*
*/
/*
* Harmony chipset 'modus operandi'.
* - This chipset is found in some HP 32bit workstations, like 712, or B132 class.
* most of controls are done through registers. Register are found at a fixed offset
* from the hard physical adress, given in struct dev by register_parisc_driver.
*
* Playback and recording use 4kb pages (dma or not, depending on the machine).
*
* Most of PCM playback & capture is done through interrupt. When harmony needs
* a new buffer to put recorded data or read played PCM, it sends an interrupt.
* Bits 2 and 10 of DSTATUS register are '1' when harmony needs respectively
* a new page for recording and playing.
* Interrupt are disabled/enabled by writing to bit 32 of DSTATUS.
* Adresses of next page to be played is put in PNXTADD register, next page
* to be recorded is put in RNXTADD. There is 2 read-only registers, PCURADD and
* RCURADD that provides adress of current page.
*
* Harmony has no way to control full duplex or half duplex mode. It means
* that we always need to provide adresses of playback and capture data, even
* when this is not needed. That's why we statically alloc one graveyard
* buffer (to put recorded data in play-only mode) and a silence buffer.
*
* Bitrate, number of channels and data format are controlled with
* the CNTL register.
*
* Mixer work is done through one register (GAINCTL). Only input gain,
* output attenuation and general attenuation control is provided. There is
* also controls for enabling/disabling internal speaker and line
* input.
*
* Buffers used by this driver are all DMA consistent.
*/
#include <linux/delay.h>
#include <sound/driver.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/pcm.h>
#include <sound/rawmidi.h>
#include <sound/initval.h>
#include <sound/info.h>
#include <asm/hardware.h>
#include <asm/io.h>
#include <asm/parisc-device.h>
MODULE_AUTHOR("Laurent Canet <[email protected]>");
MODULE_DESCRIPTION("ALSA Harmony sound driver");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{ALSA,Harmony soundcard}}");
#undef DEBUG
#ifdef DEBUG
# define DPRINTK printk
#else
# define DPRINTK(x,...)
#endif
#define PFX "harmony: "
#define MAX_PCM_DEVICES 1
#define MAX_PCM_SUBSTREAMS 4
#define MAX_MIDI_DEVICES 0
#define HARMONY_BUF_SIZE 4096
#define MAX_BUFS 10
#define MAX_BUFFER_SIZE (MAX_BUFS * HARMONY_BUF_SIZE)
/* number of silence & graveyard buffers */
#define GRAVEYARD_BUFS 3
#define SILENCE_BUFS 3
#define HARMONY_CNTL_C 0x80000000
#define HARMONY_DSTATUS_PN 0x00000200
#define HARMONY_DSTATUS_RN 0x00000002
#define HARMONY_DSTATUS_IE 0x80000000
#define HARMONY_DF_16BIT_LINEAR 0x00000000
#define HARMONY_DF_8BIT_ULAW 0x00000001
#define HARMONY_DF_8BIT_ALAW 0x00000002
#define HARMONY_SS_MONO 0x00000000
#define HARMONY_SS_STEREO 0x00000001
/*
* Channels Mask in mixer register
* try some "reasonable" default gain values
*/
#define HARMONY_GAIN_TOTAL_SILENCE 0x00F00FFF
/* the following should be enough (mixer is
* very sensible on harmony)
*/
#define HARMONY_GAIN_DEFAULT 0x0F2FF082
/* useless since only one card is supported ATM */
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE;
static int boot_devs;
module_param_array(index, int, boot_devs, 0444);
MODULE_PARM_DESC(index, "Index value for Sun CS4231 soundcard.");
module_param_array(id, charp, boot_devs, 0444);
MODULE_PARM_DESC(id, "ID string for Sun CS4231 soundcard.");
module_param_array(enable, bool, boot_devs, 0444);
MODULE_PARM_DESC(enable, "Enable Sun CS4231 soundcard.");
/* Register offset (from base hpa) */
#define REG_ID 0x00
#define REG_RESET 0x04
#define REG_CNTL 0x08
#define REG_GAINCTL 0x0C
#define REG_PNXTADD 0x10
#define REG_PCURADD 0x14
#define REG_RNXTADD 0x18
#define REG_RCURADD 0x1C
#define REG_DSTATUS 0x20
#define REG_OV 0x24
#define REG_PIO 0x28
#define REG_DIAG 0x3C
/*
* main harmony structure
*/
typedef struct snd_card_harmony {
/* spinlocks (To be done) */
spinlock_t mixer_lock;
spinlock_t control_lock;
/* parameters */
int irq;
unsigned long hpa;
int id;
int rev;
u32 current_gain;
int data_format; /* HARMONY_DF_xx_BIT_xxx */
int sample_rate; /* HARMONY_SR_xx_KHZ */
int stereo_select; /* HARMONY_SS_MONO or HARMONY_SS_STEREO */
int format_initialized;
unsigned long ply_buffer;
int ply_buf;
int ply_count;
int ply_size;
int ply_stopped;
int ply_total;
unsigned long cap_buffer;
int cap_buf;
int cap_count;
int cap_size;
int cap_stopped;
int cap_total;
struct parisc_device *pa_dev;
struct snd_dma_device dma_dev;
/* the graveyard buffer is used as recording buffer when playback,
* because harmony always want a buffer to put recorded data */
struct snd_dma_buffer graveyard_dma;
int graveyard_count;
/* same thing for silence buffer */
struct snd_dma_buffer silence_dma;
int silence_count;
/* alsa stuff */
snd_card_t *card;
snd_pcm_t *pcm;
snd_pcm_substream_t *playback_substream;
snd_pcm_substream_t *capture_substream;
snd_info_entry_t *proc_entry;
} snd_card_harmony_t;
static snd_card_t *snd_harmony_cards[SNDRV_CARDS] = SNDRV_DEFAULT_PTR;
/* wait to be out of control mode */
static inline void snd_harmony_wait_cntl(snd_card_harmony_t *harmony)
{
int timeout = 5000;
while ( (gsc_readl(harmony->hpa+REG_CNTL) & HARMONY_CNTL_C) && --timeout)
{
/* Wait */ ;
}
if (timeout == 0) DPRINTK(KERN_DEBUG PFX "Error: wait cntl timeouted\n");
}
/*
* sample rate routines
*/
static unsigned int snd_card_harmony_rates[] = {
5125, 6615, 8000, 9600,
11025, 16000, 18900, 22050,
27428, 32000, 33075, 37800,
44100, 48000
};
static snd_pcm_hw_constraint_list_t hw_constraint_rates = {
.count = ARRAY_SIZE(snd_card_harmony_rates),
.list = snd_card_harmony_rates,
.mask = 0,
};
#define HARMONY_SR_8KHZ 0x08
#define HARMONY_SR_16KHZ 0x09
#define HARMONY_SR_27KHZ 0x0A
#define HARMONY_SR_32KHZ 0x0B
#define HARMONY_SR_48KHZ 0x0E
#define HARMONY_SR_9KHZ 0x0F
#define HARMONY_SR_5KHZ 0x10
#define HARMONY_SR_11KHZ 0x11
#define HARMONY_SR_18KHZ 0x12
#define HARMONY_SR_22KHZ 0x13
#define HARMONY_SR_37KHZ 0x14
#define HARMONY_SR_44KHZ 0x15
#define HARMONY_SR_33KHZ 0x16
#define HARMONY_SR_6KHZ 0x17
/* bits corresponding to the entries of snd_card_harmony_rates */
static unsigned int rate_bits[14] = {
HARMONY_SR_5KHZ, HARMONY_SR_6KHZ, HARMONY_SR_8KHZ,
HARMONY_SR_9KHZ, HARMONY_SR_11KHZ, HARMONY_SR_16KHZ,
HARMONY_SR_18KHZ, HARMONY_SR_22KHZ, HARMONY_SR_27KHZ,
HARMONY_SR_32KHZ, HARMONY_SR_33KHZ, HARMONY_SR_37KHZ,
HARMONY_SR_44KHZ, HARMONY_SR_48KHZ
};
/* snd_card_harmony_rate_bits
* @rate: index of current data rate in list
* returns: harmony hex code for registers
*/
static unsigned int snd_card_harmony_rate_bits(int rate)
{
unsigned int idx;
for (idx = 0; idx <= ARRAY_SIZE(snd_card_harmony_rates); idx++)
if (snd_card_harmony_rates[idx] == rate)
return rate_bits[idx];
return HARMONY_SR_44KHZ; /* fallback */
}
/*
* update controls (data format, sample rate, number of channels)
* according to value supplied in data structure
*/
void snd_harmony_update_control(snd_card_harmony_t *harmony)
{
u32 default_cntl;
/* Set CNTL */
default_cntl = (HARMONY_CNTL_C | /* The C bit */
(harmony->data_format << 6) | /* Set the data format */
(harmony->stereo_select << 5) | /* Stereo select */
(harmony->sample_rate)); /* Set sample rate */
/* initialize CNTL */
snd_harmony_wait_cntl(harmony);
gsc_writel(default_cntl, harmony->hpa+REG_CNTL);
}
/*
* interruption controls routines
*/
static void snd_harmony_disable_interrupts(snd_card_harmony_t *chip)
{
snd_harmony_wait_cntl(chip);
gsc_writel(0, chip->hpa+REG_DSTATUS);
}
static void snd_harmony_enable_interrupts(snd_card_harmony_t *chip)
{
snd_harmony_wait_cntl(chip);
gsc_writel(HARMONY_DSTATUS_IE, chip->hpa+REG_DSTATUS);
}
/*
* interruption routine:
* The interrupt routine must provide adresse of next physical pages
* used by harmony
*/
static int snd_card_harmony_interrupt(int irq, void *dev, struct pt_regs *regs)
{
snd_card_harmony_t *harmony = (snd_card_harmony_t *)dev;
u32 dstatus = 0;
unsigned long hpa = harmony->hpa;
/* Turn off interrupts */
snd_harmony_disable_interrupts(harmony);
/* wait for control to free */
snd_harmony_wait_cntl(harmony);
/* Read dstatus and pcuradd (the current address) */
dstatus = gsc_readl(hpa+REG_DSTATUS);
/* Check if this is a request to get the next play buffer */
if (dstatus & HARMONY_DSTATUS_PN) {
if (harmony->playback_substream) {
harmony->ply_buf += harmony->ply_count;
harmony->ply_buf %= harmony->ply_size;
gsc_writel(harmony->ply_buffer + harmony->ply_buf,
hpa+REG_PNXTADD);
snd_pcm_period_elapsed(harmony->playback_substream);
harmony->ply_total++;
} else {
gsc_writel(harmony->silence_dma.addr +
(HARMONY_BUF_SIZE*harmony->silence_count),
hpa+REG_PNXTADD);
harmony->silence_count++;
harmony->silence_count %= SILENCE_BUFS;
}
}
/* Check if we're being asked to fill in a recording buffer */
if (dstatus & HARMONY_DSTATUS_RN) {
if (harmony->capture_substream) {
harmony->cap_buf += harmony->cap_count;
harmony->cap_buf %= harmony->cap_size;
gsc_writel(harmony->cap_buffer + harmony->cap_buf,
hpa+REG_RNXTADD);
snd_pcm_period_elapsed(harmony->capture_substream);
harmony->cap_total++;
} else {
/* graveyard buffer */
gsc_writel(harmony->graveyard_dma.addr +
(HARMONY_BUF_SIZE*harmony->graveyard_count),
hpa+REG_RNXTADD);
harmony->graveyard_count++;
harmony->graveyard_count %= GRAVEYARD_BUFS;
}
}
snd_harmony_enable_interrupts(harmony);
return IRQ_HANDLED;
}
/*
* proc entry
* this proc file will give some debugging info
*/
static void snd_harmony_proc_read(snd_info_entry_t *entry, snd_info_buffer_t *buffer)
{
snd_card_harmony_t *harmony = (snd_card_harmony_t *)entry->private_data;
snd_iprintf(buffer, "LASI Harmony driver\nLaurent Canet <[email protected]>\n\n");
snd_iprintf(buffer, "IRQ %d, hpa %lx, id %d rev %d\n",
harmony->irq, harmony->hpa,
harmony->id, harmony->rev);
snd_iprintf(buffer, "Current gain %lx\n", (unsigned long) harmony->current_gain);
snd_iprintf(buffer, "\tsample rate=%d\n", harmony->sample_rate);
snd_iprintf(buffer, "\tstereo select=%d\n", harmony->stereo_select);
snd_iprintf(buffer, "\tbitperchan=%d\n\n", harmony->data_format);
snd_iprintf(buffer, "Play status:\n");
snd_iprintf(buffer, "\tstopped %d\n", harmony->ply_stopped);
snd_iprintf(buffer, "\tbuffer %lx, count %d\n", harmony->ply_buffer, harmony->ply_count);
snd_iprintf(buffer, "\tbuf %d size %d\n\n", harmony->ply_buf, harmony->ply_size);
snd_iprintf(buffer, "Capture status:\n");
snd_iprintf(buffer, "\tstopped %d\n", harmony->cap_stopped);
snd_iprintf(buffer, "\tbuffer %lx, count %d\n", harmony->cap_buffer, harmony->cap_count);
snd_iprintf(buffer, "\tbuf %d, size %d\n\n", harmony->cap_buf, harmony->cap_size);
snd_iprintf(buffer, "Funny stats: total played=%d, recorded=%d\n\n", harmony->ply_total, harmony->cap_total);
snd_iprintf(buffer, "Register:\n");
snd_iprintf(buffer, "\tgainctl: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_GAINCTL));
snd_iprintf(buffer, "\tcntl: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_CNTL));
snd_iprintf(buffer, "\tid: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_ID));
snd_iprintf(buffer, "\tpcuradd: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_PCURADD));
snd_iprintf(buffer, "\trcuradd: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_RCURADD));
snd_iprintf(buffer, "\tpnxtadd: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_PNXTADD));
snd_iprintf(buffer, "\trnxtadd: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_RNXTADD));
snd_iprintf(buffer, "\tdstatus: %lx\n", (unsigned long) gsc_readl(harmony->hpa+REG_DSTATUS));
snd_iprintf(buffer, "\tov: %lx\n\n", (unsigned long) gsc_readl(harmony->hpa+REG_OV));
}
static void __devinit snd_harmony_proc_init(snd_card_harmony_t *harmony)
{
snd_info_entry_t *entry;
if (! snd_card_proc_new(harmony->card, "harmony", &entry))
snd_info_set_text_ops(entry, harmony, 2048, snd_harmony_proc_read);
}
/*
* PCM Stuff
*/
static int snd_card_harmony_playback_ioctl(snd_pcm_substream_t * substream,
unsigned int cmd,
void *arg)
{
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int snd_card_harmony_capture_ioctl(snd_pcm_substream_t * substream,
unsigned int cmd,
void *arg)
{
return snd_pcm_lib_ioctl(substream, cmd, arg);
}
static int snd_card_harmony_playback_trigger(snd_pcm_substream_t * substream,
int cmd)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_STOP:
if (harmony->ply_stopped)
return -EBUSY;
harmony->ply_stopped = 1;
snd_harmony_disable_interrupts(harmony);
break;
case SNDRV_PCM_TRIGGER_START:
if (!harmony->ply_stopped)
return -EBUSY;
harmony->ply_stopped = 0;
/* write the location of the first buffer to play */
gsc_writel(harmony->ply_buffer, harmony->hpa+REG_PNXTADD);
snd_harmony_enable_interrupts(harmony);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
DPRINTK(KERN_INFO PFX "received unimplemented trigger: %d\n", cmd);
default:
return -EINVAL;
}
return 0;
}
static int snd_card_harmony_capture_trigger(snd_pcm_substream_t * substream,
int cmd)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
switch (cmd) {
case SNDRV_PCM_TRIGGER_STOP:
if (harmony->cap_stopped)
return -EBUSY;
harmony->cap_stopped = 1;
snd_harmony_disable_interrupts(harmony);
break;
case SNDRV_PCM_TRIGGER_START:
if (!harmony->cap_stopped)
return -EBUSY;
harmony->cap_stopped = 0;
snd_harmony_enable_interrupts(harmony);
break;
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_SUSPEND:
DPRINTK(KERN_INFO PFX "Received unimplemented trigger: %d\n", cmd);
default:
return -EINVAL;
}
return 0;
}
/* set data format */
static int snd_harmony_set_data_format(snd_card_harmony_t *harmony, int pcm_format)
{
int old_format = harmony->data_format;
int new_format = old_format;
switch (pcm_format) {
case SNDRV_PCM_FORMAT_S16_BE:
new_format = HARMONY_DF_16BIT_LINEAR;
break;
case SNDRV_PCM_FORMAT_A_LAW:
new_format = HARMONY_DF_8BIT_ALAW;
break;
case SNDRV_PCM_FORMAT_MU_LAW:
new_format = HARMONY_DF_8BIT_ULAW;
break;
}
/* re-initialize silence buffer if needed */
if (old_format != new_format)
snd_pcm_format_set_silence(pcm_format, harmony->silence_dma.area,
(HARMONY_BUF_SIZE * SILENCE_BUFS * 8) / snd_pcm_format_width(pcm_format));
return new_format;
}
static int snd_card_harmony_playback_prepare(snd_pcm_substream_t * substream)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
snd_pcm_runtime_t *runtime = substream->runtime;
harmony->ply_size = snd_pcm_lib_buffer_bytes(substream);
harmony->ply_count = snd_pcm_lib_period_bytes(substream);
harmony->ply_buf = 0;
harmony->ply_stopped = 1;
/* initialize given sample rate */
harmony->sample_rate = snd_card_harmony_rate_bits(runtime->rate);
/* data format */
harmony->data_format = snd_harmony_set_data_format(harmony, runtime->format);
/* number of channels */
if (runtime->channels == 2)
harmony->stereo_select = HARMONY_SS_STEREO;
else
harmony->stereo_select = HARMONY_SS_MONO;
DPRINTK(KERN_INFO PFX "Playback_prepare, sr=%d(%x), df=%x, ss=%x hpa=%lx\n", runtime->rate,
harmony->sample_rate, harmony->data_format, harmony->stereo_select, harmony->hpa);
snd_harmony_update_control(harmony);
harmony->format_initialized = 1;
harmony->ply_buffer = runtime->dma_addr;
return 0;
}
static int snd_card_harmony_capture_prepare(snd_pcm_substream_t * substream)
{
snd_pcm_runtime_t *runtime = substream->runtime;
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
harmony->cap_size = snd_pcm_lib_buffer_bytes(substream);
harmony->cap_count = snd_pcm_lib_period_bytes(substream);
harmony->cap_count = 0;
harmony->cap_stopped = 1;
/* initialize given sample rate */
harmony->sample_rate = snd_card_harmony_rate_bits(runtime->rate);
/* data format */
harmony->data_format = snd_harmony_set_data_format(harmony, runtime->format);
/* number of channels */
if (runtime->channels == 1)
harmony->stereo_select = HARMONY_SS_MONO;
else if (runtime->channels == 2)
harmony->stereo_select = HARMONY_SS_STEREO;
snd_harmony_update_control(harmony);
harmony->format_initialized = 1;
harmony->cap_buffer = runtime->dma_addr;
return 0;
}
static snd_pcm_uframes_t snd_card_harmony_capture_pointer(snd_pcm_substream_t * substream)
{
snd_pcm_runtime_t *runtime = substream->runtime;
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
unsigned long rcuradd;
int recorded;
if (harmony->cap_stopped) return 0;
if (harmony->capture_substream == NULL) return 0;
rcuradd = gsc_readl(harmony->hpa+REG_RCURADD);
recorded = (rcuradd - harmony->cap_buffer);
recorded %= harmony->cap_size;
return bytes_to_frames(runtime, recorded);
}
/*
*/
static snd_pcm_uframes_t snd_card_harmony_playback_pointer(snd_pcm_substream_t * substream)
{
snd_pcm_runtime_t *runtime = substream->runtime;
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
int played;
long int pcuradd = gsc_readl(harmony->hpa+REG_PCURADD);
if ((harmony->ply_stopped) || (harmony->playback_substream == NULL)) return 0;
if ((harmony->ply_buffer == 0) || (harmony->ply_size == 0)) return 0;
played = (pcuradd - harmony->ply_buffer);
printk(KERN_DEBUG PFX "Pointer is %lx-%lx = %d\n", pcuradd, harmony->ply_buffer, played);
if (pcuradd > harmony->ply_buffer + harmony->ply_size) return 0;
return bytes_to_frames(runtime, played);
}
static snd_pcm_hardware_t snd_card_harmony_playback =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_A_LAW | SNDRV_PCM_FMTBIT_MU_LAW),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5500,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUFFER_SIZE,
.period_bytes_min = HARMONY_BUF_SIZE,
.period_bytes_max = HARMONY_BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static snd_pcm_hardware_t snd_card_harmony_capture =
{
.info = (SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_JOINT_DUPLEX |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_BLOCK_TRANSFER),
.formats = (SNDRV_PCM_FMTBIT_U8 | SNDRV_PCM_FMTBIT_S16_BE |
SNDRV_PCM_FMTBIT_A_LAW | SNDRV_PCM_FMTBIT_MU_LAW),
.rates = SNDRV_PCM_RATE_CONTINUOUS | SNDRV_PCM_RATE_8000_48000,
.rate_min = 5500,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 2,
.buffer_bytes_max = MAX_BUFFER_SIZE,
.period_bytes_min = HARMONY_BUF_SIZE,
.period_bytes_max = HARMONY_BUF_SIZE,
.periods_min = 1,
.periods_max = MAX_BUFS,
.fifo_size = 0,
};
static int snd_card_harmony_playback_open(snd_pcm_substream_t * substream)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
snd_pcm_runtime_t *runtime = substream->runtime;
int err;
harmony->playback_substream = substream;
runtime->hw = snd_card_harmony_playback;
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &hw_constraint_rates);
if ((err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS)) < 0)
return err;
return 0;
}
static int snd_card_harmony_capture_open(snd_pcm_substream_t * substream)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
snd_pcm_runtime_t *runtime = substream->runtime;
int err;
harmony->capture_substream = substream;
runtime->hw = snd_card_harmony_capture;
snd_pcm_hw_constraint_list(runtime, 0, SNDRV_PCM_HW_PARAM_RATE, &hw_constraint_rates);
if ((err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS)) < 0)
return err;
return 0;
}
static int snd_card_harmony_playback_close(snd_pcm_substream_t * substream)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
harmony->playback_substream = NULL;
harmony->ply_size = 0;
harmony->ply_buf = 0;
harmony->ply_buffer = 0;
harmony->ply_count = 0;
harmony->ply_stopped = 1;
harmony->format_initialized = 0;
return 0;
}
static int snd_card_harmony_capture_close(snd_pcm_substream_t * substream)
{
snd_card_harmony_t *harmony = snd_pcm_substream_chip(substream);
harmony->capture_substream = NULL;
harmony->cap_size = 0;
harmony->cap_buf = 0;
harmony->cap_buffer = 0;
harmony->cap_count = 0;
harmony->cap_stopped = 1;
harmony->format_initialized = 0;
return 0;
}
static int snd_card_harmony_hw_params(snd_pcm_substream_t *substream,
snd_pcm_hw_params_t * hw_params)
{
int err;
err = snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
if (err > 0 && substream->dma_device.type == SNDRV_DMA_TYPE_CONTINUOUS)
substream->runtime->dma_addr = __pa(substream->runtime->dma_area);
DPRINTK(KERN_INFO PFX "HW Params returned %d, dma_addr %lx\n", err,
(unsigned long)substream->runtime->dma_addr);
return err;
}
static int snd_card_harmony_hw_free(snd_pcm_substream_t *substream)
{
snd_pcm_lib_free_pages(substream);
return 0;
}
static snd_pcm_ops_t snd_card_harmony_playback_ops = {
.open = snd_card_harmony_playback_open,
.close = snd_card_harmony_playback_close,
.ioctl = snd_card_harmony_playback_ioctl,
.hw_params = snd_card_harmony_hw_params,
.hw_free = snd_card_harmony_hw_free,
.prepare = snd_card_harmony_playback_prepare,
.trigger = snd_card_harmony_playback_trigger,
.pointer = snd_card_harmony_playback_pointer,
};
static snd_pcm_ops_t snd_card_harmony_capture_ops = {
.open = snd_card_harmony_capture_open,
.close = snd_card_harmony_capture_close,
.ioctl = snd_card_harmony_capture_ioctl,
.hw_params = snd_card_harmony_hw_params,
.hw_free = snd_card_harmony_hw_free,
.prepare = snd_card_harmony_capture_prepare,
.trigger = snd_card_harmony_capture_trigger,
.pointer = snd_card_harmony_capture_pointer,
};
static int snd_card_harmony_pcm_init(snd_card_harmony_t *harmony)
{
snd_pcm_t *pcm;
int err;
/* Request that IRQ */
if (request_irq(harmony->irq, snd_card_harmony_interrupt, 0 ,"harmony", harmony)) {
printk(KERN_ERR PFX "Error requesting irq %d.\n", harmony->irq);
return -EFAULT;
}
snd_harmony_disable_interrupts(harmony);
if ((err = snd_pcm_new(harmony->card, "Harmony", 0, 1, 1, &pcm)) < 0)
return err;
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &snd_card_harmony_playback_ops);
snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &snd_card_harmony_capture_ops);
pcm->private_data = harmony;
pcm->info_flags = 0;
strcpy(pcm->name, "Harmony");
harmony->pcm = pcm;
/* initialize graveyard buffer */
harmony->dma_dev.type = SNDRV_DMA_TYPE_DEV;
harmony->dma_dev.dev = &harmony->pa_dev->dev;
err = snd_dma_alloc_pages(harmony->dma_dev.type,
harmony->dma_dev.dev,
HARMONY_BUF_SIZE*GRAVEYARD_BUFS,
&harmony->graveyard_dma);
if (err == -ENOMEM) {
/* use continuous buffers */
harmony->dma_dev.type = SNDRV_DMA_TYPE_CONTINUOUS;
harmony->dma_dev.dev = snd_dma_continuous_data(GFP_KERNEL);
err = snd_dma_alloc_pages(harmony->dma_dev.type,
harmony->dma_dev.dev,
HARMONY_BUF_SIZE*GRAVEYARD_BUFS,
&harmony->graveyard_dma);
}
if (err < 0) {
printk(KERN_ERR PFX "can't allocate graveyard buffer\n");
return err;
}
harmony->graveyard_count = 0;
/* initialize silence buffers */
err = snd_dma_alloc_pages(harmony->dma_dev.type,
harmony->dma_dev.dev,
HARMONY_BUF_SIZE*SILENCE_BUFS,
&harmony->silence_dma);
if (err < 0) {
printk(KERN_ERR PFX "can't allocate silence buffer\n");
return err;
}
harmony->silence_count = 0;
if (harmony->dma_dev.type == SNDRV_DMA_TYPE_CONTINUOUS) {
harmony->graveyard_dma.addr = __pa(harmony->graveyard_dma.area);
harmony->silence_dma.addr = __pa(harmony->silence_dma.area);
}
harmony->ply_stopped = harmony->cap_stopped = 1;
harmony->playback_substream = NULL;
harmony->capture_substream = NULL;
harmony->graveyard_count = 0;
err = snd_pcm_lib_preallocate_pages_for_all(pcm, harmony->dma_dev.type,
harmony->dma_dev.dev,
MAX_BUFFER_SIZE, MAX_BUFFER_SIZE);
if (err < 0) {
printk(KERN_ERR PFX "buffer allocation error %d\n", err);
// return err;
}
return 0;
}
/*
* mixer routines
*/
static void snd_harmony_set_new_gain(snd_card_harmony_t *harmony)
{
DPRINTK(KERN_INFO PFX "Setting new gain %x at %lx\n", harmony->current_gain, harmony->hpa+REG_GAINCTL);
/* Wait until we're out of control mode */
snd_harmony_wait_cntl(harmony);
gsc_writel(harmony->current_gain, harmony->hpa+REG_GAINCTL);
}
#define HARMONY_VOLUME(xname, left_shift, right_shift, mask, invert) \
{ .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = xname, \
.info = snd_harmony_mixercontrol_info, \
.get = snd_harmony_volume_get, .put = snd_harmony_volume_put, \
.private_value = ((left_shift) | ((right_shift) << 8) | ((mask) << 16) | ((invert) << 24)) }
static int snd_harmony_mixercontrol_info(snd_kcontrol_t * kcontrol, snd_ctl_elem_info_t * uinfo)
{
int mask = (kcontrol->private_value >> 16) & 0xff;
int left_shift = (kcontrol->private_value) & 0xff;
int right_shift = (kcontrol->private_value >> 8) & 0xff;
uinfo->type = (mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER);
uinfo->count = (left_shift == right_shift) ? 1 : 2;
uinfo->value.integer.min = 0;
uinfo->value.integer.max = mask;
return 0;
}
static int snd_harmony_volume_get(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
{
snd_card_harmony_t *harmony = snd_kcontrol_chip(kcontrol);
int shift_left = (kcontrol->private_value) & 0xff;
int shift_right = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
unsigned long flags;
int left, right;
spin_lock_irqsave(&harmony->mixer_lock, flags);
left = (harmony->current_gain >> shift_left) & mask;
right = (harmony->current_gain >> shift_right) & mask;
if (invert) {
left = mask - left;
right = mask - right;
}
ucontrol->value.integer.value[0] = left;
ucontrol->value.integer.value[1] = right;
spin_unlock_irqrestore(&harmony->mixer_lock, flags);
return 0;
}
static int snd_harmony_volume_put(snd_kcontrol_t * kcontrol, snd_ctl_elem_value_t * ucontrol)
{
snd_card_harmony_t *harmony = snd_kcontrol_chip(kcontrol);
int shift_left = (kcontrol->private_value) & 0xff;
int shift_right = (kcontrol->private_value >> 8) & 0xff;
int mask = (kcontrol->private_value >> 16) & 0xff;
int invert = (kcontrol->private_value >> 24) & 0xff;
unsigned long flags;
int left, right;
int old_gain = harmony->current_gain;
left = ucontrol->value.integer.value[0] & mask;
right = ucontrol->value.integer.value[1] & mask;
if (invert) {
left = mask - left;
right = mask - right;
}
spin_lock_irqsave(&harmony->mixer_lock, flags);
harmony->current_gain = harmony->current_gain & ~( (mask << shift_right) | (mask << shift_left));
harmony->current_gain = harmony->current_gain | ((left << shift_left) | (right << shift_right) );
snd_harmony_set_new_gain(harmony);
spin_unlock_irqrestore(&harmony->mixer_lock, flags);
return (old_gain - harmony->current_gain);
}
#define HARMONY_CONTROLS (sizeof(snd_harmony_controls)/sizeof(snd_kcontrol_new_t))
static snd_kcontrol_new_t snd_harmony_controls[] = {
HARMONY_VOLUME("PCM Capture Volume", 12, 16, 0x0f, 0),
HARMONY_VOLUME("Master Volume", 20, 20, 0x0f, 1),
HARMONY_VOLUME("PCM Playback Volume", 6, 0, 0x3f, 1),
};
static void __init snd_harmony_reset_codec(snd_card_harmony_t *harmony)
{
snd_harmony_wait_cntl(harmony);
gsc_writel(1, harmony->hpa+REG_RESET);
mdelay(50); /* wait 50 ms */
gsc_writel(0, harmony->hpa+REG_RESET);
}
/*
* Mute all the output and reset Harmony.
*/
static void __init snd_harmony_mixer_reset(snd_card_harmony_t *harmony)
{
harmony->current_gain = HARMONY_GAIN_TOTAL_SILENCE;
snd_harmony_set_new_gain(harmony);
snd_harmony_reset_codec(harmony);
harmony->current_gain = HARMONY_GAIN_DEFAULT;
snd_harmony_set_new_gain(harmony);
}
static int __init snd_card_harmony_mixer_init(snd_card_harmony_t *harmony)
{
snd_card_t *card = harmony->card;
int idx, err;
snd_assert(harmony != NULL, return -EINVAL);
strcpy(card->mixername, "Harmony Gain control interface");
for (idx = 0; idx < HARMONY_CONTROLS; idx++) {
if ((err = snd_ctl_add(card, snd_ctl_new1(&snd_harmony_controls[idx], harmony))) < 0)
return err;
}
snd_harmony_mixer_reset(harmony);
return 0;
}
static int snd_card_harmony_create(snd_card_t *card, struct parisc_device *pa_dev, snd_card_harmony_t *harmony)
{
u32 cntl;
harmony->card = card;
harmony->pa_dev = pa_dev;
/* Set the HPA of harmony */
harmony->hpa = pa_dev->hpa;
harmony->irq = pa_dev->irq;
if (!harmony->irq) {
printk(KERN_ERR PFX "no irq found\n");
return -ENODEV;
}
/* Grab the ID and revision from the device */
harmony->id = (gsc_readl(harmony->hpa+REG_ID)&0x00ff0000) >> 16;
if ((harmony->id | 1) != 0x15) {
printk(KERN_WARNING PFX "wrong harmony id 0x%02x\n", harmony->id);
return -EBUSY;
}
cntl = gsc_readl(harmony->hpa+REG_CNTL);
harmony->rev = (cntl>>20) & 0xff;
printk(KERN_INFO "Lasi Harmony Audio driver h/w id %i, rev. %i at 0x%lx, IRQ %i\n", harmony->id, harmony->rev, pa_dev->hpa, harmony->irq);
/* Make sure the control bit isn't set, although I don't think it
ever is. */
if (cntl & HARMONY_CNTL_C) {
printk(KERN_WARNING PFX "CNTL busy\n");
harmony->hpa = 0;
return -EBUSY;
}
return 0;
}
static int __init snd_card_harmony_probe(struct parisc_device *pa_dev)
{
static int dev;
snd_card_harmony_t *chip;
snd_card_t *card;
int err;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
snd_harmony_cards[dev] = snd_card_new(index[dev], id[dev], THIS_MODULE,
sizeof(snd_card_harmony_t));
card = snd_harmony_cards[dev];
if (card == NULL)
return -ENOMEM;
chip = (struct snd_card_harmony *)card->private_data;
spin_lock_init(&chip->control_lock);
spin_lock_init(&chip->mixer_lock);
if ((err = snd_card_harmony_create(card, pa_dev, chip)) < 0) {
printk(KERN_ERR PFX "Creation failed\n");
snd_card_free(card);
return err;
}
if ((err = snd_card_harmony_pcm_init(chip)) < 0) {
printk(KERN_ERR PFX "PCM Init failed\n");
snd_card_free(card);
return err;
}
if ((err = snd_card_harmony_mixer_init(chip)) < 0) {
printk(KERN_ERR PFX "Mixer init failed\n");
snd_card_free(card);
return err;
}
snd_harmony_proc_init(chip);
strcpy(card->driver, "Harmony");
strcpy(card->shortname, "ALSA driver for LASI Harmony");
sprintf(card->longname, "%s at h/w, id %i, rev. %i hpa 0x%lx, IRQ %i\n",card->shortname, chip->id, chip->rev, pa_dev->hpa, chip->irq);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
printk(KERN_DEBUG PFX "Successfully registered harmony pcm backend & mixer %d\n", dev);
dev++;
return 0;
}
static struct parisc_device_id snd_card_harmony_devicetbl[] = {
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007A }, /* Bushmaster/Flounder */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007B }, /* 712/715 Audio */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007E }, /* Pace Audio */
{ HPHW_FIO, HVERSION_REV_ANY_ID, HVERSION_ANY_ID, 0x0007F }, /* Outfield / Coral II */
{ 0, }
};
MODULE_DEVICE_TABLE(parisc, snd_card_harmony_devicetbl);
/*
* bloc device parisc. c'est une structure qui definit un device
* que l'on trouve sur parisc.
* On y trouve les differents numeros HVERSION correspondant au device
* en question (ce qui permet a l'inventory de l'identifier) et la fonction
* d'initialisation du chose
*/
static struct parisc_driver snd_card_harmony_driver = {
.name = "Lasi ALSA Harmony",
.id_table = snd_card_harmony_devicetbl,
.probe = snd_card_harmony_probe,
};
static int __init alsa_card_harmony_init(void)
{
int err;
if ((err = register_parisc_driver(&snd_card_harmony_driver)) < 0) {
printk(KERN_ERR "Harmony soundcard not found or device busy\n");
return err;
}
return 0;
}
static void __exit alsa_card_harmony_exit(void)
{
int idx;
snd_card_harmony_t *harmony;
for (idx = 0; idx < SNDRV_CARDS; idx++)
{
if (snd_harmony_cards[idx] != NULL)
{
DPRINTK(KERN_INFO PFX "Freeing card %d\n", idx);
harmony = snd_harmony_cards[idx]->private_data;
free_irq(harmony->irq, snd_card_harmony_interrupt);
printk(KERN_INFO PFX "Card unloaded %d, irq=%d\n", idx, harmony->irq);
snd_card_free(snd_harmony_cards[idx]);
}
}
}
module_init(alsa_card_harmony_init)
module_exit(alsa_card_harmony_exit)
| gpl-2.0 |
norov/glibc | sysdeps/unix/sysv/linux/ipc_priv.h | 1459 | /* Old SysV permission definition for Linux. Default version.
Copyright (C) 1995-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <sys/ipc.h> /* For __key_t */
#define __IPC_64 0x100
struct __old_ipc_perm
{
__key_t __key; /* Key. */
unsigned short int uid; /* Owner's user ID. */
unsigned short int gid; /* Owner's group ID. */
unsigned short int cuid; /* Creator's user ID. */
unsigned short int cgid; /* Creator's group ID. */
unsigned short int mode; /* Read/write permission. */
unsigned short int __seq; /* Sequence number. */
};
#define SEMCTL_ARG_ADDRESS(__arg) &__arg.array
#define MSGRCV_ARGS(__msgp, __msgtyp) \
((long int []){ (long int) __msgp, __msgtyp })
#include <ipc_ops.h>
| gpl-2.0 |
slowfranklin/wireshark | epan/dissectors/packet-dcerpc-wkssvc.h | 14030 | /* autogenerated by pidl */
/* DO NOT EDIT
This filter was automatically generated
from wkssvc.idl and wkssvc.cnf.
Pidl is a perl based IDL compiler for DCE/RPC idl files.
It is maintained by the Samba team, not the Wireshark team.
Instructions on how to download and install Pidl can be
found at http://wiki.wireshark.org/Pidl
$Id$
*/
#include "packet-dcerpc-srvsvc.h"
#include "packet-dcerpc-lsa.h"
#ifndef __PACKET_DCERPC_WKSSVC_H
#define __PACKET_DCERPC_WKSSVC_H
int wkssvc_dissect_struct_lsa_String(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo100(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo101(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo102(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo502(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1010(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1011(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1012(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1013(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1018(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1023(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1027(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1028(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1032(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1033(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1041(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1042(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1043(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1044(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1045(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1046(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1047(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1048(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1049(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1050(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1051(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1052(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1053(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1054(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1055(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1056(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1057(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1058(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1059(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1060(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1061(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaInfo1062(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrWkstaUserInfo0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaEnumUsersCtr0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrWkstaUserInfo1(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaEnumUsersCtr1(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaEnumUsersInfo(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrWkstaUserInfo1101(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaTransportInfo0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaTransportCtr0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetWkstaTransportInfo(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseInfo3(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseInfo2(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseInfo1(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseInfo0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseEnumCtr2(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseEnumCtr1(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseEnumCtr0(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrUseEnumInfo(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_struct_NetrWorkstationStatistics(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_bitmap_renameflags(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
#define NetSetupUnknown (0)
#define NetSetupMachine (1)
#define NetSetupWorkgroup (2)
#define NetSetupDomain (3)
#define NetSetupNonExistentDomain (4)
#define NetSetupDnsMachine (5)
extern const value_string wkssvc_wkssvc_NetValidateNameType_vals[];
int wkssvc_dissect_enum_NetValidateNameType(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 *param _U_);
#define NetSetupUnknownStatus (0)
#define NetSetupUnjoined (1)
#define NetSetupWorkgroupName (2)
#define NetSetupDomainName (3)
extern const value_string wkssvc_wkssvc_NetJoinStatus_vals[];
int wkssvc_dissect_enum_NetJoinStatus(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 *param _U_);
int wkssvc_dissect_struct_PasswordBuffer(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
int wkssvc_dissect_bitmap_joinflags(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
#define NetPrimaryComputerName (0)
#define NetAlternateComputerNames (1)
#define NetAllComputerNames (2)
#define NetComputerNameTypeMax (3)
extern const value_string wkssvc_wkssvc_ComputerNameType_vals[];
int wkssvc_dissect_enum_ComputerNameType(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 *param _U_);
int wkssvc_dissect_struct_ComputerNamesCtr(tvbuff_t *tvb _U_, int offset _U_, packet_info *pinfo _U_, proto_tree *parent_tree _U_, dcerpc_info* di _U_, guint8 *drep _U_, int hf_index _U_, guint32 param _U_);
#endif /* __PACKET_DCERPC_WKSSVC_H */
| gpl-2.0 |
mohammadhamad/mohammsdGeIPSEC | repos/libports/src/test/lwip/Keynote_rpc_app_4444/vp_msg.h | 1575 | //include <sys/types.h>
//#include <sys/stat.h>
//#include <fcntl.h>
//#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//#include <sys/uio.h>
//#include <unistd.h>
#include <regex.h>
//#include <keynote/keynote.h>
#define APP_DOMAIN "vending app"
#define SRV_PORT 4444
/*
* read in message: each message is of the form Cnnn:mmm
* where C is a one character message indentifier, nnnnn is
* an unsigned integer denoting payload lenght, and mmm
* is the payload.
* Current message indentifiers are:
* H hello: contains initial order
* O offer: the server sends its offer for
* the requested item.
* R request: purchase order, followed by
* at least one credentials
* C(c) credentials: credentials authorising the
* sale. The last credential uses 'C'
* while the one in the middle use 'c'.
* D decision: outcome (essentially yes/no)
*/
#define MSG_CMD_ERROR -1
#define MSG_CMD_HELLO 'H'
#define MSG_CMD_OFFER 'O'
#define MSG_CMD_REQUEST 'R'
#define MSG_CMD_CRED 'c'
#define MSG_CMD_CRED_L 'C'
#define MSG_CMD_DECIS 'D'
int read_message(FILE *fd, char *msg_ids, char **pbuf_p, int *plen_p);
int read_file(char *fname, char **pbuf, int *plen);
// request format
#define ENDOFLIST "__EOF__"
#define NOT_FOUND "-1"
#define QLEN 20
struct vp_offer {
char o_nam[QLEN];
char o_val[QLEN];
};
| gpl-2.0 |
diydrones/alceosd | firmware/bootloader_updater.X/hex2header.py | 1513 | import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print "need input file"
sys.exit(1)
fin = open(sys.argv[1], "r")
lines = fin.readlines()
fin.close()
fout = open("bootloader.h", "w")
fout.write("/* File automatically generated by hex2header.py */\n\n")
fout.write("const unsigned int bootloader_data[] = {");
mem = {}
eAddr = 0
addr = 0
for line in lines:
line = line.strip()
if line[0] != ":":
continue
lType = int(line[7:9], 16)
lAddr = int(line[3:7], 16)
dLen = int(line[1:3], 16)
if lType == 2:
eAddr = int(line[9:13], 16) << 8;
continue
if lType == 4:
eAddr = int(line[9:13], 16) << 16;
continue
if lType == 1:
break
if lType == 0:
idx = 0
data = line[9:-2]
dataLen = len(data)
#print "data = ", data
for idx in range(dataLen / 4):
word = int(data[idx*4:(idx*4)+2], 16)
word |= int(data[(idx*4)+2:(idx*4)+4], 16) << 8;
addr = (lAddr + eAddr + idx*2) >> 1
#print hex(addr), "=", hex(word)
mem[addr] = word
output = []
for addr in range(0x800, 0xfff):
if mem.has_key(addr):
output.append(mem[addr])
else:
output.append(0xffff)
output.reverse()
idx = 0
for word in output:
if word != 0xffff:
break
output = output[1:]
output.reverse()
left = len(output) % 8
if left != 0:
output += [0xffff] * (8-left)
while (idx < len(output)):
fout.write("\n ")
for i in range(8):
fout.write("0x%04x, " % output[idx])
idx += 1
fout.write("\n};\n");
fout.close()
| gpl-2.0 |
liuyanghejerry/qtextended | qtopiacore/qt/src/gui/text/qfontengine_win.cpp | 43049 | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 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 GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
****************************************************************************/
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include <qglobal.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include <qlibrary.h>
#include <qpaintdevice.h>
#include <qpainter.h>
#include <qlibrary.h>
#include <limits.h>
#include <qendian.h>
#include <qmath.h>
#include <qthreadstorage.h>
#include <private/qunicodetables_p.h>
#include <qbitmap.h>
#include <private/qpainter_p.h>
#include <private/qpdf_p.h>
#include "qpaintengine.h"
#include "qvarlengtharray.h"
#include <private/qpaintengine_raster_p.h>
#if defined(Q_OS_WINCE)
#include "qguifunctions_wince.h"
#endif
//### mingw needed define
#ifndef TT_PRIM_CSPLINE
#define TT_PRIM_CSPLINE 3
#endif
#ifdef MAKE_TAG
#undef MAKE_TAG
#endif
// GetFontData expects the tags in little endian ;(
#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
(((quint32)(ch4)) << 24) | \
(((quint32)(ch3)) << 16) | \
(((quint32)(ch2)) << 8) | \
((quint32)(ch1)) \
)
typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
// common DC for all fonts
QT_BEGIN_NAMESPACE
class QtHDC
{
HDC _hdc;
public:
QtHDC()
{
HDC displayDC = GetDC(0);
_hdc = CreateCompatibleDC(displayDC);
ReleaseDC(0, displayDC);
}
~QtHDC()
{
if (_hdc)
DeleteDC(_hdc);
}
HDC hdc() const
{
return _hdc;
}
};
#ifndef QT_NO_THREAD
Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
HDC shared_dc()
{
QtHDC *&hdc = local_shared_dc()->localData();
if (!hdc)
hdc = new QtHDC;
return hdc->hdc();
}
#else
HDC shared_dc()
{
return 0;
}
#endif
static HFONT stock_sysfont = 0;
static PtrGetCharWidthI ptrGetCharWidthI = 0;
static bool resolvedGetCharWidthI = false;
static void resolveGetCharWidthI()
{
if (resolvedGetCharWidthI)
return;
resolvedGetCharWidthI = true;
ptrGetCharWidthI = (PtrGetCharWidthI)QLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI");
}
// Copy a LOGFONTW struct into a LOGFONTA by converting the face name to an 8 bit value.
// This is needed when calling CreateFontIndirect on non-unicode windowses.
inline static void wa_copy_logfont(LOGFONTW *lfw, LOGFONTA *lfa)
{
lfa->lfHeight = lfw->lfHeight;
lfa->lfWidth = lfw->lfWidth;
lfa->lfEscapement = lfw->lfEscapement;
lfa->lfOrientation = lfw->lfOrientation;
lfa->lfWeight = lfw->lfWeight;
lfa->lfItalic = lfw->lfItalic;
lfa->lfUnderline = lfw->lfUnderline;
lfa->lfCharSet = lfw->lfCharSet;
lfa->lfOutPrecision = lfw->lfOutPrecision;
lfa->lfClipPrecision = lfw->lfClipPrecision;
lfa->lfQuality = lfw->lfQuality;
lfa->lfPitchAndFamily = lfw->lfPitchAndFamily;
QString fam = QString::fromUtf16((const ushort*)lfw->lfFaceName);
memcpy(lfa->lfFaceName, fam.toLocal8Bit().constData(), fam.length() + 1);
}
// defined in qtextengine_win.cpp
typedef void *SCRIPT_CACHE;
typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
extern fScriptFreeCache ScriptFreeCache;
static inline quint32 getUInt(unsigned char *p)
{
quint32 val;
val = *p++ << 24;
val |= *p++ << 16;
val |= *p++ << 8;
val |= *p;
return val;
}
static inline quint16 getUShort(unsigned char *p)
{
quint16 val;
val = *p++ << 8;
val |= *p;
return val;
}
static inline HFONT systemFont()
{
if (stock_sysfont == 0)
stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
return stock_sysfont;
}
// general font engine
QFixed QFontEngineWin::lineThickness() const
{
if(lineWidth > 0)
return lineWidth;
return QFontEngine::lineThickness();
}
#if defined(Q_OS_WINCE)
static OUTLINETEXTMETRICW *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsW(hdc, 0, 0);
OUTLINETEXTMETRICW *otm = (OUTLINETEXTMETRICW *)malloc(size);
GetOutlineTextMetricsW(hdc, size, otm);
return otm;
}
#else
static OUTLINETEXTMETRICA *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsA(hdc, 0, 0);
OUTLINETEXTMETRICA *otm = (OUTLINETEXTMETRICA *)malloc(size);
GetOutlineTextMetricsA(hdc, size, otm);
return otm;
}
#endif
void QFontEngineWin::getCMap()
{
QT_WA({
ttf = (bool)(tm.w.tmPitchAndFamily & TMPF_TRUETYPE);
} , {
ttf = (bool)(tm.a.tmPitchAndFamily & TMPF_TRUETYPE);
});
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
bool symb = false;
if (ttf) {
cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
int size = 0;
cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
cmapTable.size(), &symb, &size);
}
if (!cmap) {
ttf = false;
symb = false;
}
symbol = symb;
designToDevice = 1;
_faceId.index = 0;
if(cmap) {
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
unitsPerEm = otm->otmEMSquare;
x_height = (int)otm->otmsXHeight;
loadKerningPairs(designToDevice);
_faceId.filename = (char *)otm + (int)otm->otmpFullName;
lineWidth = otm->otmsUnderscoreSize;
fsType = otm->otmfsType;
free(otm);
} else {
unitsPerEm = tm.w.tmHeight;
}
}
inline unsigned int getChar(const QChar *str, int &i, const int len)
{
unsigned int uc = str[i].unicode();
if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
uint low = str[i+1].unicode();
if (low >= 0xdc00 && low < 0xe000) {
uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
++i;
}
}
return uc;
}
int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
{
QGlyphLayout *g = glyphs;
if (mirrored) {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
if (ucs >= first && ucs <= last)
glyphs->glyph = ucs;
else
glyphs->glyph = 0;
glyphs++;
}
}
} else {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint uc = getChar(str, i, numChars);
if (uc >= first && uc <= last)
glyphs->glyph = uc;
else
glyphs->glyph = 0;
glyphs++;
}
}
}
return glyphs - g;
}
QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
{
//qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
_name = name;
cmap = 0;
hfont = _hfont;
logfont = lf;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
this->stockFont = stockFont;
fontDef.pixelSize = -lf.lfHeight;
lbearing = SHRT_MIN;
rbearing = SHRT_MIN;
synthesized_flags = -1;
lineWidth = -1;
x_height = -1;
BOOL res;
QT_WA({
res = GetTextMetricsW(hdc, &tm.w);
} , {
res = GetTextMetricsA(hdc, &tm.a);
});
fontDef.fixedPitch = !(tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
cache_cost = tm.w.tmHeight * tm.w.tmAveCharWidth * 2000;
getCMap();
useTextOutA = false;
#ifndef Q_OS_WINCE
// TextOutW doesn't work for symbol fonts on Windows 95!
// since we're using glyph indices we don't care for ttfs about this!
if (QSysInfo::WindowsVersion == QSysInfo::WV_95 && !ttf &&
(_name == QLatin1String("Marlett") || _name == QLatin1String("Symbol") ||
_name == QLatin1String("Webdings") || _name == QLatin1String("Wingdings")))
useTextOutA = true;
#endif
widthCache = 0;
widthCacheSize = 0;
designAdvances = 0;
designAdvancesSize = 0;
if (!resolvedGetCharWidthI)
resolveGetCharWidthI();
}
QFontEngineWin::~QFontEngineWin()
{
if (designAdvances)
free(designAdvances);
if (widthCache)
free(widthCache);
// make sure we aren't by accident still selected
SelectObject(shared_dc(), systemFont());
if (!stockFont) {
if (!DeleteObject(hfont))
qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
}
}
HGDIOBJ QFontEngineWin::selectDesignFont(QFixed *overhang) const
{
LOGFONT f = logfont;
f.lfHeight = unitsPerEm;
HFONT designFont;
QT_WA({
designFont = CreateFontIndirectW(&f);
}, {
LOGFONTA fa;
wa_copy_logfont(&f, &fa);
designFont = CreateFontIndirectA(&fa);
});
HGDIOBJ oldFont = SelectObject(shared_dc(), designFont);
if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) {
BOOL res;
QT_WA({
TEXTMETRICW tm;
res = GetTextMetricsW(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
} , {
TEXTMETRICA tm;
res = GetTextMetricsA(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
});
} else {
*overhang = 0;
}
return oldFont;
}
bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
{
if (*nglyphs < len) {
*nglyphs = len;
return false;
}
*nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
if (flags & QTextEngine::GlyphIndicesOnly)
return true;
#if defined(Q_OS_WINCE)
HDC hdc = shared_dc();
if (flags & QTextEngine::DesignMetrics) {
HGDIOBJ oldFont = 0;
QFixed overhang = 0;
int glyph_pos = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size);
designAdvances[glyph] = QFixed((int)size.cx)/designToDevice;
}
glyphs[glyph_pos].advance.x = designAdvances[glyph];
glyphs[glyph_pos].advance.y = 0;
if (surrogate)
++i;
++glyph_pos;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
int glyph_pos = 0;
HGDIOBJ oldFont = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
glyphs[glyph_pos].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[glyph_pos].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[glyph_pos].advance.x == 0) {
SIZE size = {0, 0};
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
GetTextExtentPoint32W(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size);
size.cx -= overhang;
glyphs[glyph_pos].advance.x = size.cx;
// if glyph's within cache range, store it for later
if (size.cx > 0 && size.cx < 0x100)
widthCache[glyph] = size.cx;
}
if (surrogate)
++i;
++glyph_pos;
}
if (oldFont)
SelectObject(hdc, oldFont);
}
#else
recalcAdvances(*nglyphs, glyphs, flags);
#endif
return true;
}
void QFontEngineWin::recalcAdvances(int len, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
{
HGDIOBJ oldFont = 0;
HDC hdc = shared_dc();
if (ttf && (flags & QTextEngine::DesignMetrics)) {
QFixed overhang = 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
if (ptrGetCharWidthI) {
int width = 0;
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
designAdvances[glyph] = QFixed(width) / designToDevice;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
designAdvances[glyph] = QFixed(gm.gmCellIncX) / designToDevice;
}
#endif
}
}
glyphs[i].advance.x = designAdvances[glyph];
glyphs[i].advance.y = 0;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
glyphs[i].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[i].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[i].advance.x == 0) {
int width = 0;
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
if (!ttf) {
QChar ch[2] = { ushort(glyph), 0 };
int chrLen = 1;
if (glyph > 0xffff) {
ch[0] = QChar::highSurrogate(glyph);
ch[1] = QChar::lowSurrogate(glyph);
++chrLen;
}
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)ch, chrLen, &size);
width = size.cx;
} else if (ptrGetCharWidthI) {
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
width -= overhang;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
width = gm.gmCellIncX;
}
#endif
}
glyphs[i].advance.x = width;
// if glyph's within cache range, store it for later
if (width > 0 && width < 0x100)
widthCache[glyph] = width;
}
}
if (oldFont)
SelectObject(hdc, oldFont);
}
}
glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout *glyphs, int numGlyphs)
{
if (numGlyphs == 0)
return glyph_metrics_t();
QFixed w = 0;
const QGlyphLayout *end = glyphs + numGlyphs;
while(end > glyphs) {
--end;
w += end->effectiveAdvance();
}
return glyph_metrics_t(0, -tm.w.tmAscent, w, tm.w.tmHeight, w, 0);
}
#ifndef Q_OS_WINCE
typedef HRESULT (WINAPI *pGetCharABCWidthsFloat)(HDC, UINT, UINT, LPABCFLOAT);
static pGetCharABCWidthsFloat qt_GetCharABCWidthsFloat = 0;
#endif
glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph)
{
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if(!ttf) {
SIZE s = {0, 0};
WCHAR ch = glyph;
int width;
int overhang = 0;
static bool resolved = false;
if (!resolved) {
QLibrary lib(QLatin1String("gdi32"));
qt_GetCharABCWidthsFloat = (pGetCharABCWidthsFloat) lib.resolve("GetCharABCWidthsFloatW");
resolved = true;
}
if (QT_WA_INLINE(true, false) && qt_GetCharABCWidthsFloat) {
ABCFLOAT abc;
qt_GetCharABCWidthsFloat(hdc, ch, ch, &abc);
width = qRound(abc.abcfB);
} else {
GetTextExtentPoint32W(hdc, &ch, 1, &s);
overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
width = s.cx;
}
return glyph_metrics_t(0, -tm.a.tmAscent, width, tm.a.tmHeight, width-overhang, 0);
} else {
DWORD res = 0;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR)
return glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
(int)gm.gmBlackBoxX, (int)gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY);
}
return glyph_metrics_t();
#else
SIZE s = {0, 0};
WCHAR ch = glyph;
HDC hdc = shared_dc();
BOOL res = GetTextExtentPoint32W(hdc, &ch, 1, &s);
Q_UNUSED(res);
return glyph_metrics_t(0, -tm.a.tmAscent, s.cx, tm.a.tmHeight, s.cx, 0);
#endif
}
QFixed QFontEngineWin::ascent() const
{
return tm.w.tmAscent;
}
QFixed QFontEngineWin::descent() const
{
return tm.w.tmDescent;
}
QFixed QFontEngineWin::leading() const
{
return tm.w.tmExternalLeading;
}
QFixed QFontEngineWin::xHeight() const
{
if(x_height >= 0)
return x_height;
return QFontEngine::xHeight();
}
QFixed QFontEngineWin::averageCharWidth() const
{
return tm.w.tmAveCharWidth;
}
qreal QFontEngineWin::maxCharWidth() const
{
return tm.w.tmMaxCharWidth;
}
enum { max_font_count = 256 };
static const ushort char_table[] = {
40,
67,
70,
75,
86,
88,
89,
91,
102,
114,
124,
127,
205,
645,
884,
922,
1070,
12386,
0
};
static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
qreal QFontEngineWin::minLeftBearing() const
{
if (lbearing == SHRT_MIN)
minRightBearing(); // calculates both
return lbearing;
}
qreal QFontEngineWin::minRightBearing() const
{
#ifdef Q_OS_WINCE
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABC[char_table_entries+1];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
ml = 0;
mr = -tm.a.tmOverhang;
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#else
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
QT_WA({
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
}, {
GetCharABCWidthsA(hdc,tm.a.tmFirstChar,tm.a.tmLastChar,abc);
});
} else {
abc = new ABC[char_table_entries+1];
QT_WA({
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
}, {
for(int i = 0; i < char_table_entries; i++) {
QByteArray w = QString(QChar(char_table[i])).toLocal8Bit();
if (w.length() == 1) {
uint ch8 = (uchar)w[0];
GetCharABCWidthsA(hdc, ch8, ch8, abc+i);
}
}
});
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
QT_WA({
ABCFLOAT *abc = 0;
int n = tm.w.tmLastChar - tm.w.tmFirstChar+1;
if (n <= max_font_count) {
abc = new ABCFLOAT[n];
GetCharABCWidthsFloat(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABCFLOAT[char_table_entries];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
float fml = abc[0].abcfA;
float fmr = abc[0].abcfC;
for (int i=1; i<n; i++) {
if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) {
fml = qMin(fml,abc[i].abcfA);
fmr = qMin(fmr,abc[i].abcfC);
}
}
ml = int(fml-0.9999);
mr = int(fmr-0.9999);
delete [] abc;
} , {
ml = 0;
mr = -tm.a.tmOverhang;
});
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#endif
}
const char *QFontEngineWin::name() const
{
return 0;
}
bool QFontEngineWin::canRender(const QChar *string, int len)
{
if (symbol) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
if (uc < 0x100) {
if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
return false;
} else {
return false;
}
}
}
} else if (ttf) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0)
return false;
}
} else {
QT_WA({
while(len--) {
if (tm.w.tmFirstChar > string->unicode() || tm.w.tmLastChar < string->unicode())
return false;
}
}, {
while(len--) {
if (tm.a.tmFirstChar > string->unicode() || tm.a.tmLastChar < string->unicode())
return false;
}
});
}
return true;
}
QFontEngine::Type QFontEngineWin::type() const
{
return QFontEngine::Win;
}
static inline double qt_fixed_to_double(const FIXED &p) {
return ((p.value << 16) + p.fract) / 65536.0;
}
static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
}
#ifndef GGO_UNHINTED
#define GGO_UNHINTED 0x0100
#endif
static void addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
{
#if defined(Q_OS_WINCE)
Q_UNUSED(glyph);
Q_UNUSED(hdc);
#endif
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
uint glyphFormat = GGO_NATIVE;
if (ttf)
glyphFormat |= GGO_GLYPH_INDEX;
GLYPHMETRICS gMetric;
memset(&gMetric, 0, sizeof(GLYPHMETRICS));
int bufferSize = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
bufferSize = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
}, {
bufferSize = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
});
#endif
if ((DWORD)bufferSize == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(1) failed");
return;
}
void *dataBuffer = new char[bufferSize];
DWORD ret = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
ret = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
}, {
ret = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
} );
#endif
if (ret == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(2) failed");
delete [](char *)dataBuffer;
return;
}
if(metric) {
// #### obey scale
*metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
(int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
gMetric.gmCellIncX, gMetric.gmCellIncY);
}
int offset = 0;
int headerOffset = 0;
TTPOLYGONHEADER *ttph = 0;
QPointF oset = position.toPointF();
while (headerOffset < bufferSize) {
ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
path->moveTo(lastPoint + oset);
offset += sizeof(TTPOLYGONHEADER);
TTPOLYCURVE *curve;
while (offset<int(headerOffset + ttph->cb)) {
curve = (TTPOLYCURVE*)((char*)(dataBuffer) + offset);
switch (curve->wType) {
case TT_PRIM_LINE: {
for (int i=0; i<curve->cpfx; ++i) {
QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
path->lineTo(p);
}
break;
}
case TT_PRIM_QSPLINE: {
const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
QPointF prev(elm.x, elm.y);
QPointF endPoint;
for (int i=0; i<curve->cpfx - 1; ++i) {
QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
if (i < curve->cpfx - 2) {
endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
} else {
endPoint = p2;
}
path->quadTo(p1, endPoint);
prev = endPoint;
}
break;
}
case TT_PRIM_CSPLINE: {
for (int i=0; i<curve->cpfx; ) {
QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
path->cubicTo(p2, p3, p4);
}
break;
}
default:
qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
}
offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
}
path->closeSubpath();
headerOffset += ttph->cb;
}
delete [] (char*)dataBuffer;
}
void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
QPainterPath *path, QTextItem::RenderFlags)
{
LOGFONT lf = logfont;
// The sign must be negative here to make sure we match against character height instead of
// hinted cell height. This ensures that we get linear matching, and we need this for
// paths since we later on apply a scaling transform to the glyph outline to get the
// font at the correct pixel size.
lf.lfHeight = -unitsPerEm;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
for(int i = 0; i < nglyphs; ++i)
addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0, qreal(fontDef.pixelSize) / unitsPerEm);
DeleteObject(SelectObject(hdc, oldfont));
}
void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout *glyphs, int numGlyphs,
QPainterPath *path, QTextItem::RenderFlags flags)
{
#if !defined(Q_OS_WINCE)
if(tm.w.tmPitchAndFamily & (TMPF_TRUETYPE)) {
QFontEngine::addOutlineToPath(x, y, glyphs, numGlyphs, path, flags);
return;
}
#endif
QFontEngine::addBitmapFontToPath(x, y, glyphs, numGlyphs, path, flags);
}
QFontEngine::FaceId QFontEngineWin::faceId() const
{
return _faceId;
}
QT_BEGIN_INCLUDE_NAMESPACE
#include <qdebug.h>
QT_END_INCLUDE_NAMESPACE
int QFontEngineWin::synthesized() const
{
if(synthesized_flags == -1) {
synthesized_flags = 0;
if(ttf) {
const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
uchar data[4];
GetFontData(hdc, HEAD, 44, &data, 4);
USHORT macStyle = getUShort(data);
if (tm.w.tmItalic && !(macStyle & 2))
synthesized_flags = SynthesizedItalic;
if (fontDef.stretch != 100 && ttf)
synthesized_flags |= SynthesizedStretch;
if (tm.w.tmWeight >= 500 && !(macStyle & 1))
synthesized_flags |= SynthesizedBold;
//qDebug() << "font is" << _name <<
// "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
}
}
return synthesized_flags;
}
QFixed QFontEngineWin::emSquareSize() const
{
return unitsPerEm;
}
QFontEngine::Properties QFontEngineWin::properties() const
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
Properties p;
p.emSquare = unitsPerEm;
p.italicAngle = otm->otmItalicAngle;
p.postscriptName = (char *)otm + (int)otm->otmpFamilyName;
p.postscriptName += (char *)otm + (int)otm->otmpStyleName;
#ifndef QT_NO_PRINTER
p.postscriptName = QPdf::stripSpecialCharacters(p.postscriptName);
#endif
p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
otm->otmrcFontBox.right - otm->otmrcFontBox.left,
otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
p.ascent = otm->otmAscent;
p.descent = -otm->otmDescent;
p.leading = (int)otm->otmLineGap;
p.capHeight = 0;
p.lineWidth = otm->otmsUnderscoreSize;
free(otm);
DeleteObject(SelectObject(hdc, oldfont));
return p;
}
void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
int flags = synthesized();
if(flags & SynthesizedItalic)
lf.lfItalic = false;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
QFixedPoint p;
p.x = 0;
p.y = 0;
addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
DeleteObject(SelectObject(hdc, oldfont));
}
bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
{
if (!ttf)
return false;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
DWORD t = qbswap<quint32>(tag);
*length = GetFontData(hdc, t, 0, buffer, *length);
return *length != GDI_ERROR;
}
#if !defined(CLEARTYPE_QUALITY)
# define CLEARTYPE_QUALITY 5
#endif
QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph)
{
glyph_metrics_t gm = boundingBox(glyph);
int glyph_x = qFloor(gm.x.toReal());
int glyph_y = qFloor(gm.y.toReal());
int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
if (glyph_width + glyph_x <= 0 || glyph_height <= 0)
return QImage();
QImage im(glyph_width, glyph_height, QImage::Format_ARGB32_Premultiplied);
im.fill(0);
QPainter p(&im);
HFONT oldHFont = hfont;
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
// try hard to disable cleartype rendering
static_cast<QRasterPaintEngine *>(p.paintEngine())->disableClearType();
LOGFONT nonCleartypeFont = logfont;
nonCleartypeFont.lfQuality = ANTIALIASED_QUALITY;
hfont = CreateFontIndirect(&nonCleartypeFont);
}
p.setPen(Qt::black);
p.setBrush(Qt::NoBrush);
QTextItemInt ti;
ti.ascent = ascent();
ti.descent = descent();
ti.width = glyph_width;
ti.fontEngine = this;
ti.num_glyphs = 1;
QGlyphLayout glyphLayout;
ti.glyphs = &glyphLayout;
glyphLayout.glyph = glyph;
memset(&glyphLayout.attributes, 0, sizeof(glyphLayout.attributes));
glyphLayout.advance.x = glyph_width;
p.drawTextItem(QPointF(-glyph_x, -glyph_y), ti);
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
DeleteObject(hfont);
hfont = oldHFont;
}
p.end();
QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
QVector<QRgb> colors(256);
for (int i=0; i<256; ++i)
colors[i] = qRgba(0, 0, 0, i);
indexed.setColorTable(colors);
for (int y=0; y<im.height(); ++y) {
uchar *dst = (uchar *) indexed.scanLine(y);
uint *src = (uint *) im.scanLine(y);
for (int x=0; x<im.width(); ++x)
dst[x] = qAlpha(src[x]);
}
return indexed;
}
// -------------------------------------- Multi font engine
QFontEngineMultiWin::QFontEngineMultiWin(QFontEngineWin *first, const QStringList &fallbacks)
: QFontEngineMulti(fallbacks.size()+1),
fallbacks(fallbacks)
{
engines[0] = first;
first->ref.ref();
fontDef = engines[0]->fontDef;
}
void QFontEngineMultiWin::loadEngine(int at)
{
Q_ASSERT(at < engines.size());
Q_ASSERT(engines.at(at) == 0);
QString fam = fallbacks.at(at-1);
LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
HFONT hfont;
QT_WA({
memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectW(&lf);
} , {
// LOGFONTA and LOGFONTW are binary compatible
QByteArray lname = fam.toLocal8Bit();
memcpy(lf.lfFaceName,lname.data(),
qMin(lname.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectA((LOGFONTA*)&lf);
});
bool stockFont = false;
if (hfont == 0) {
hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
stockFont = true;
}
engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
engines[at]->ref.ref();
engines[at]->fontDef = fontDef;
}
QT_END_NAMESPACE
| gpl-2.0 |
aldencolerain/mc2kernel | drivers/net/ethernet/mvebu_net/pp2/net_dev/mv_pp2_netmap.h | 13567 | /*******************************************************************************
Copyright (C) Marvell International Ltd. and its affiliates
This software file (the "File") is owned and distributed by Marvell
International Ltd. and/or its affiliates ("Marvell") under the following
alternative licensing terms. Once you have made an election to distribute the
File under one of the following license alternatives, please (i) delete this
introductory statement regarding license alternatives, (ii) delete the two
license alternatives that you have not elected to use and (iii) preserve the
Marvell copyright notice above.
********************************************************************************
Marvell GPL License Option
If you received this File from Marvell, you may opt to use, redistribute and/or
modify this File in accordance with the terms and conditions of the General
Public License Version 2, June 1991 (the "GPL License"), a copy of which is
available along with the File in the license.txt file or by writing to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 or
on the worldwide web at http://www.gnu.org/licenses/gpl.txt.
THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE IMPLIED
WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE ARE EXPRESSLY
DISCLAIMED. The GPL License provides additional details about this warranty
disclaimer.
*******************************************************************************/
/* mv_pp2_netmap.h */
#ifndef __MV_PP2_NETMAP_H__
#define __MV_PP2_NETMAP_H__
#include <bsd_glue.h>
#include <netmap.h>
#include <netmap_kern.h>
#define SOFTC_T eth_port
static int pool_buf_num[MV_BM_POOLS];
static struct bm_pool *pool_short[MV_ETH_MAX_PORTS];
/*
* Register/unregister
* adapter is pointer to eth_port
*/
static int mv_pp2_netmap_reg(struct ifnet *ifp, int onoff)
{
struct eth_port *adapter = MV_ETH_PRIV(ifp);
struct netmap_adapter *na = NA(ifp);
int error = 0, txq, rxq;
if (na == NULL)
return -EINVAL;
if (!(ifp->flags & IFF_UP)) {
/* mv_pp2_eth_open has not been called yet, so resources
* are not allocated */
printk(KERN_ERR "Interface is down!");
return -EINVAL;
}
/* stop current interface */
if (mv_pp2_eth_stop(ifp)) {
printk(KERN_ERR "%s: stop interface failed\n", ifp->name);
return -EINVAL;
}
if (onoff) { /* enable netmap mode */
u32 port_map;
mv_pp2_rx_reset(adapter->port);
ifp->if_capenable |= IFCAP_NETMAP;
na->if_transmit = (void *)ifp->netdev_ops;
ifp->netdev_ops = &na->nm_ndo;
/* check that long pool is not shared with other ports */
port_map = mv_pp2_ctrl_pool_port_map_get(adapter->pool_long->pool);
if (port_map != (1 << adapter->port)) {
printk(KERN_ERR "%s: BM pool %d not initialized or shared with other ports.\n",
__func__, adapter->pool_long->pool);
return -EINVAL;
}
/* Keep old number of long pool buffers */
pool_buf_num[adapter->pool_long->pool] = adapter->pool_long->buf_num;
mv_pp2_pool_free(adapter->pool_long->pool, adapter->pool_long->buf_num);
/* set same pool number for short and long packets */
for (rxq = 0; rxq < CONFIG_MV_PP2_RXQ; rxq++)
mvPp2RxqBmShortPoolSet(adapter->port, rxq, adapter->pool_long->pool);
/* update short pool in software */
pool_short[adapter->port] = adapter->pool_short;
adapter->pool_short = adapter->pool_long;
set_bit(MV_ETH_F_IFCAP_NETMAP_BIT, &(adapter->flags));
} else {
unsigned long flags = 0;
u_int pa, i;
ifp->if_capenable &= ~IFCAP_NETMAP;
ifp->netdev_ops = (void *)na->if_transmit;
mv_pp2_rx_reset(adapter->port);
/* TODO: handle SMP - each CPU must call this loop */
/*
for (txq = 0; txq < CONFIG_MV_PP2_TXQ; txq++)
mvPp2TxqSentDescProc(adapter->port, 0, txq);
*/
i = 0;
MV_ETH_LOCK(&adapter->pool_long->lock, flags);
do {
mvBmPoolGet(adapter->pool_long->pool, &pa);
i++;
} while (pa != 0);
MV_ETH_UNLOCK(&adapter->pool_long->lock, flags);
printk(KERN_ERR "NETMAP: free %d buffers from pool %d\n", i, adapter->pool_long->pool);
mv_pp2_pool_add(adapter, adapter->pool_long->pool, pool_buf_num[adapter->pool_long->pool]);
/* set port's short pool for Linux driver */
for (rxq = 0; rxq < CONFIG_MV_PP2_RXQ; rxq++)
mvPp2RxqBmShortPoolSet(adapter->port, rxq, adapter->pool_short->pool);
/* update short pool in software */
adapter->pool_short = pool_short[adapter->port];
clear_bit(MV_ETH_F_IFCAP_NETMAP_BIT, &(adapter->flags));
}
if (mv_pp2_start(ifp)) {
printk(KERN_ERR "%s: start interface failed\n", ifp->name);
return -EINVAL;
}
return error;
}
/*
* Reconcile kernel and user view of the transmit ring.
*/
static int
mv_pp2_netmap_txsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
{
struct SOFTC_T *adapter = MV_ETH_PRIV(ifp);
struct netmap_adapter *na = NA(ifp);
struct netmap_kring *kring = &na->tx_rings[ring_nr];
struct netmap_ring *ring = kring->ring;
u_int j, k, n = 0, lim = kring->nkr_num_slots - 1;
u_int sent_n, cpu = 0;
struct pp2_tx_desc *tx_desc;
struct aggr_tx_queue *aggr_txq_ctrl = NULL;
/* generate an interrupt approximately every half ring */
/*int report_frequency = kring->nkr_num_slots >> 1;*/
/* take a copy of ring->cur now, and never read it again */
k = ring->cur;
if (k > lim)
return netmap_ring_reinit(kring);
aggr_txq_ctrl = &aggr_txqs[cpu];
if (do_lock)
mtx_lock(&kring->q_lock);
rmb();
/*
* Process new packets to send. j is the current index in the
* netmap ring, l is the corresponding index in the NIC ring.
*/
j = kring->nr_hwcur;
if (j != k) { /* we have new packets to send */
for (n = 0; j != k; n++) {
/* slot is the current slot in the netmap ring */
struct netmap_slot *slot = &ring->slot[j];
uint64_t paddr;
void *addr = PNMB(slot, &paddr);
u_int len = slot->len;
if (addr == netmap_buffer_base || len > NETMAP_BUF_SIZE) {
if (do_lock)
mtx_unlock(&kring->q_lock);
return netmap_ring_reinit(kring);
}
slot->flags &= ~NS_REPORT;
/* check aggregated TXQ resource */
if (mv_pp2_aggr_desc_num_check(aggr_txq_ctrl, 1)) {
if (do_lock)
mtx_unlock(&kring->q_lock);
return netmap_ring_reinit(kring);
}
tx_desc = mvPp2AggrTxqNextDescGet(aggr_txq_ctrl->q);
tx_desc->physTxq = MV_PPV2_TXQ_PHYS(adapter->port, 0, ring_nr);
tx_desc->bufPhysAddr = (uint32_t)(paddr);
tx_desc->dataSize = len;
tx_desc->pktOffset = slot->data_offs;
tx_desc->command = PP2_TX_L4_CSUM_NOT | PP2_TX_F_DESC_MASK | PP2_TX_L_DESC_MASK;
mv_pp2_tx_desc_flush(adapter, tx_desc);
aggr_txq_ctrl->txq_count++;
if (slot->flags & NS_BUF_CHANGED)
slot->flags &= ~NS_BUF_CHANGED;
j = (j == lim) ? 0 : j + 1;
}
kring->nr_hwcur = k; /* the saved ring->cur */
kring->nr_hwavail -= n;
wmb(); /* synchronize writes to the NIC ring */
/* Enable transmit */
sent_n = n;
while (sent_n > 0xFF) {
mvPp2AggrTxqPendDescAdd(0xFF);
sent_n -= 0xFF;
}
mvPp2AggrTxqPendDescAdd(sent_n);
}
if (n == 0 || kring->nr_hwavail < 1) {
int delta;
delta = mvPp2TxqSentDescProc(adapter->port, 0, ring_nr);
if (delta)
kring->nr_hwavail += delta;
}
/* update avail to what the kernel knows */
ring->avail = kring->nr_hwavail;
if (do_lock)
mtx_unlock(&kring->q_lock);
return 0;
}
/*
* Reconcile kernel and user view of the receive ring.
*/
static int
mv_pp2_netmap_rxsync(struct ifnet *ifp, u_int ring_nr, int do_lock)
{
struct SOFTC_T *adapter = MV_ETH_PRIV(ifp);
struct netmap_adapter *na = NA(ifp);
MV_PP2_PHYS_RXQ_CTRL *rxr = adapter->rxq_ctrl[ring_nr].q;
struct netmap_kring *kring = &na->rx_rings[ring_nr];
struct netmap_ring *ring = kring->ring;
u_int j, l, n;
int force_update = do_lock || kring->nr_kflags & NKR_PENDINTR;
uint16_t strip_crc = (1) ? 4 : 0; /* TBD :: remove CRC or not */
u_int lim = kring->nkr_num_slots - 1;
u_int k = ring->cur;
u_int resvd = ring->reserved;
u_int rx_done;
if (k > lim)
return netmap_ring_reinit(kring);
if (do_lock)
mtx_lock(&kring->q_lock);
/* hardware memory barrier that prevents any memory read access from being moved */
/* and executed on the other side of the barrier */
rmb();
/*
* Import newly received packets into the netmap ring.
* j is an index in the netmap ring, l in the NIC ring.
*/
l = rxr->queueCtrl.nextToProc;
j = netmap_idx_n2k(kring, l); /* map NIC ring index to netmap ring index */
if (netmap_no_pendintr || force_update) { /* netmap_no_pendintr = 1, see netmap.c */
/* Get number of received packets */
rx_done = mvPp2RxqBusyDescNumGet(adapter->port, ring_nr);
mvOsCacheIoSync();
rx_done = (rx_done >= lim) ? lim - 1 : rx_done;
for (n = 0; n < rx_done; n++) {
PP2_RX_DESC *curr = (PP2_RX_DESC *)MV_PP2_QUEUE_DESC_PTR(&rxr->queueCtrl, l);
#if defined(MV_CPU_BE)
mvPPv2RxqDescSwap(curr);
#endif /* MV_CPU_BE */
/* TBD : check for ERRORs */
ring->slot[j].len = (curr->dataSize) - strip_crc - MV_ETH_MH_SIZE;
ring->slot[j].data_offs = NET_SKB_PAD + MV_ETH_MH_SIZE;
ring->slot[j].buf_idx = curr->bufCookie;
ring->slot[j].flags |= NS_BUF_CHANGED;
j = (j == lim) ? 0 : j + 1;
l = (l == lim) ? 0 : l + 1;
}
if (n) { /* update the state variables */
struct napi_group_ctrl *napi_group;
rxr->queueCtrl.nextToProc = l;
kring->nr_hwavail += n;
mvPp2RxqOccupDescDec(adapter->port, ring_nr, n);
/* enable interrupts */
wmb();
napi_group = adapter->cpu_config[smp_processor_id()]->napi_group;
mvPp2GbeCpuInterruptsEnable(adapter->port, napi_group->cpu_mask);
}
kring->nr_kflags &= ~NKR_PENDINTR;
}
/* skip past packets that userspace has released */
j = kring->nr_hwcur; /* netmap ring index */
if (resvd > 0) {
if (resvd + ring->avail >= lim + 1) {
printk(KERN_ERR "XXX invalid reserve/avail %d %d", resvd, ring->avail);
ring->reserved = resvd = 0;
}
k = (k >= resvd) ? k - resvd : k + lim + 1 - resvd;
}
if (j != k) { /* userspace has released some packets. */
l = netmap_idx_k2n(kring, j); /* NIC ring index */
for (n = 0; j != k; n++) {
struct netmap_slot *slot = &ring->slot[j];
PP2_RX_DESC *curr = (PP2_RX_DESC *)MV_PP2_QUEUE_DESC_PTR(&rxr->queueCtrl, l);
uint64_t paddr;
uint32_t *addr = PNMB(slot, &paddr);
/*
In big endian mode:
we do not need to swap descriptor here, allready swapped before
*/
slot->data_offs = NET_SKB_PAD + MV_ETH_MH_SIZE;
if (addr == (uint32_t *)netmap_buffer_base) { /* bad buf */
if (do_lock)
mtx_unlock(&kring->q_lock);
return netmap_ring_reinit(kring);
}
if (slot->flags & NS_BUF_CHANGED) {
slot->flags &= ~NS_BUF_CHANGED;
mvBmPoolPut(adapter->pool_long->pool, (uint32_t)paddr, curr->bufCookie);
}
curr->status = 0;
j = (j == lim) ? 0 : j + 1;
l = (l == lim) ? 0 : l + 1;
}
kring->nr_hwavail -= n;
kring->nr_hwcur = k;
/* hardware memory barrier that prevents any memory write access from being moved and */
/* executed on the other side of the barrier.*/
wmb();
/*
* IMPORTANT: we must leave one free slot in the ring,
* so move l back by one unit
*/
l = (l == 0) ? lim : l - 1;
mvPp2RxqNonOccupDescAdd(adapter->port, ring_nr, n);
}
/* tell userspace that there are new packets */
ring->avail = kring->nr_hwavail - resvd;
if (do_lock)
mtx_unlock(&kring->q_lock);
return 0;
}
/* diagnostic routine to catch errors */
static void mv_pp2_no_rx_alloc(struct SOFTC_T *a, int n)
{
printk("mv_pp2_skb_alloc should not be called");
}
/*
* Make the rx ring point to the netmap buffers.
*/
static int pp2_netmap_rxq_init_buffers(struct SOFTC_T *adapter, int rxq)
{
struct ifnet *ifp = adapter->dev; /* struct net_devive */
struct netmap_adapter *na = NA(ifp);
struct netmap_slot *slot;
struct rx_queue *rxr;
int i, si;
uint64_t paddr;
uint32_t *vaddr;
if (!(adapter->flags & MV_ETH_F_IFCAP_NETMAP))
return 0;
/* initialize the rx ring */
slot = netmap_reset(na, NR_RX, rxq, 0);
if (!slot) {
printk(KERN_ERR "%s: RX slot is null\n", __func__);
return 1;
}
rxr = &(adapter->rxq_ctrl[rxq]);
for (i = 0; i < rxr->rxq_size; i++) {
si = netmap_idx_n2k(&na->rx_rings[rxq], i);
vaddr = PNMB(slot + si, &paddr);
/* printk(KERN_ERR "paddr = 0x%x, virt = 0x%x\n",
(uint32_t)paddr, (uint32_t)((slot+si)->buf_idx));*/
/* TODO: use mvBmPoolQsetPut in ppv2.1 */
mvBmPoolPut(adapter->pool_long->pool, (uint32_t)paddr, (uint32_t)((slot+si)->buf_idx));
}
rxr->q->queueCtrl.nextToProc = 0;
/* Force memory writes to complete */
wmb();
return 0;
}
/*
* Make the tx ring point to the netmap buffers.
*/
static int pp2_netmap_txq_init_buffers(struct SOFTC_T *adapter, int txp, int txq)
{
struct ifnet *ifp = adapter->dev;
struct netmap_adapter *na = NA(ifp);
struct netmap_slot *slot;
int q;
if (!(adapter->flags & MV_ETH_F_IFCAP_NETMAP))
return 0;
q = txp * CONFIG_MV_PP2_TXQ + txq;
/* initialize the tx ring */
slot = netmap_reset(na, NR_TX, q, 0);
if (!slot) {
printk(KERN_ERR "%s: TX slot is null\n", __func__);
return 1;
}
return 0;
}
static void
mv_pp2_netmap_attach(struct SOFTC_T *adapter)
{
struct netmap_adapter na;
bzero(&na, sizeof(na));
na.ifp = adapter->dev; /* struct net_device */
na.separate_locks = 0;
na.num_tx_desc = 256;
na.num_rx_desc = adapter->rxq_ctrl->rxq_size;
na.nm_register = mv_pp2_netmap_reg;
na.nm_txsync = mv_pp2_netmap_txsync;
na.nm_rxsync = mv_pp2_netmap_rxsync;
na.num_tx_rings = CONFIG_MV_PP2_TXQ;
netmap_attach(&na, CONFIG_MV_PP2_RXQ);
}
/* end of file */
#endif /* __MV_PP2_NETMAP_H__ */
| gpl-2.0 |
Alexpux/GCC | gcc/testsuite/gcc.target/i386/avx512vl-vpmovusqw-2.c | 334 | /* { dg-do run } */
/* { dg-options "-O2 -mavx512vl -DAVX512VL" } */
/* { dg-require-effective-target avx512vl } */
#define AVX512F_LEN 256
#define AVX512F_LEN_HALF 128
#include "avx512f-vpmovusqw-2.c"
#undef AVX512F_LEN
#undef AVX512F_LEN_HALF
#define AVX512F_LEN 128
#define AVX512F_LEN_HALF 128
#include "avx512f-vpmovusqw-2.c"
| gpl-2.0 |
AnduZhang/resource-center | wp-content/plugins/muut/views/widgets/widget-latest-comments.php | 846 | <?php
/**
* The markup for the frontend of the Latest Comments widget
*
* @package Muut
* @copyright 2014 Muut Inc
*/
/**
* This file assumes that we are within the widget() method of the Muut_Widget_Latest_Comments class (which extends WP_Widget).
* Knowing that, `$this` represents that widget instance.
*/
?>
<div id="muut-widget-latest-comments-wrapper" class="muut_widget_wrapper muut_widget_latest_comments_wrapper">
<ul id="muut-recentcomments">
<?php
foreach ( $latest_comments_data as $comment ) {
if ( is_string( $comment['user'] ) ) {
$user_obj->displayname = $comment['user'];
$user_obj->img = '';
$user_obj->path = $comment['user'];
} else {
$user_obj = $comment['user'];
}
echo $this->getRowMarkup( $comment['post_id'], $comment['timestamp'], $comment['user'] );
}
?>
</ul>
</div>
| gpl-2.0 |
Inter-Trust/Aspect_Weaver | documentation/doc/intertrust/modules/aw/package-tree.html | 4807 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Wed Mar 26 16:47:45 CET 2014 -->
<title>intertrust.modules.aw Class Hierarchy</title>
<meta name="date" content="2014-03-26">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="intertrust.modules.aw Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../intertrust/modules/ag/gui/package-tree.html">Prev</a></li>
<li><a href="../../../intertrust/modules/aw/concrete/aspectj/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?intertrust/modules/aw/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package intertrust.modules.aw</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">intertrust.modules.aw.<a href="../../../intertrust/modules/aw/AspectWeaver.html" title="class in intertrust.modules.aw"><span class="strong">AspectWeaver</span></a> (implements intertrust.modules.aw.<a href="../../../intertrust/modules/aw/AspectsAdaptationRequestInt.html" title="interface in intertrust.modules.aw">AspectsAdaptationRequestInt</a>)</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">intertrust.modules.aw.<a href="../../../intertrust/modules/aw/AspectsAdaptationRequestInt.html" title="interface in intertrust.modules.aw"><span class="strong">AspectsAdaptationRequestInt</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../intertrust/modules/ag/gui/package-tree.html">Prev</a></li>
<li><a href="../../../intertrust/modules/aw/concrete/aspectj/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?intertrust/modules/aw/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| gpl-2.0 |
kiennd146/nhazz.com | plugins/system/zend/Zend/Amf/Util/BinaryStream.php | 7414 | <?php defined( '_JEXEC') or die( 'Restricted Access' );
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BinaryStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Utility class to walk through a data stream byte by byte with conventional names
*
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Util_BinaryStream
{
/**
* @var string Byte stream
*/
protected $_stream;
/**
* @var int Length of stream
*/
protected $_streamLength;
/**
* @var bool BigEndian encoding?
*/
protected $_bigEndian;
/**
* @var int Current position in stream
*/
protected $_needle;
/**
* Constructor
*
* Create a reference to a byte stream that is going to be parsed or created
* by the methods in the class. Detect if the class should use big or
* little Endian encoding.
*
* @param string $stream use '' if creating a new stream or pass a string if reading.
* @return void
*/
public function __construct($stream)
{
if (!is_string($stream)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Inputdata is not of type String');
}
$this->_stream = $stream;
$this->_needle = 0;
$this->_streamLength = strlen($stream);
$this->_bigEndian = (pack('l', 1) === "\x00\x00\x00\x01");
}
/**
* Returns the current stream
*
* @return string
*/
public function getStream()
{
return $this->_stream;
}
/**
* Read the number of bytes in a row for the length supplied.
*
* @todo Should check that there are enough bytes left in the stream we are about to read.
* @param int $length
* @return string
* @throws Zend_Amf_Exception for buffer underrun
*/
public function readBytes($length)
{
if (($length + $this->_needle) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
$bytes = substr($this->_stream, $this->_needle, $length);
$this->_needle+= $length;
return $bytes;
}
/**
* Write any length of bytes to the stream
*
* Usually a string.
*
* @param string $bytes
* @return Zend_Amf_Util_BinaryStream
*/
public function writeBytes($bytes)
{
$this->_stream.= $bytes;
return $this;
}
/**
* Reads a signed byte
*
* @return int Value is in the range of -128 to 127.
*/
public function readByte()
{
if (($this->_needle + 1) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
return ord($this->_stream{$this->_needle++});
}
/**
* Writes the passed string into a signed byte on the stream.
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeByte($stream)
{
$this->_stream.= pack('c', $stream);
return $this;
}
/**
* Reads a signed 32-bit integer from the data stream.
*
* @return int Value is in the range of -2147483648 to 2147483647
*/
public function readInt()
{
return ($this->readByte() << 8) + $this->readByte();
}
/**
* Write an the integer to the output stream as a 32 bit signed integer
*
* @param int $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeInt($stream)
{
$this->_stream.= pack('n', $stream);
return $this;
}
/**
* Reads a UTF-8 string from the data stream
*
* @return string A UTF-8 string produced by the byte representation of characters
*/
public function readUtf()
{
$length = $this->readInt();
return $this->readBytes($length);
}
/**
* Wite a UTF-8 string to the outputstream
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeUtf($stream)
{
$this->writeInt(strlen($stream));
$this->_stream.= $stream;
return $this;
}
/**
* Read a long UTF string
*
* @return string
*/
public function readLongUtf()
{
$length = $this->readLong();
return $this->readBytes($length);
}
/**
* Write a long UTF string to the buffer
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLongUtf($stream)
{
$this->writeLong(strlen($stream));
$this->_stream.= $stream;
}
/**
* Read a long numeric value
*
* @return double
*/
public function readLong()
{
return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
}
/**
* Write long numeric value to output stream
*
* @param int|string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLong($stream)
{
$this->_stream.= pack('N', $stream);
return $this;
}
/**
* Read a 16 bit unsigned short.
*
* @todo This could use the unpack() w/ S,n, or v
* @return double
*/
public function readUnsignedShort()
{
$byte1 = $this->readByte();
$byte2 = $this->readByte();
return (($byte1 << 8) | $byte2);
}
/**
* Reads an IEEE 754 double-precision floating point number from the data stream.
*
* @return double Floating point number
*/
public function readDouble()
{
$bytes = substr($this->_stream, $this->_needle, 8);
$this->_needle+= 8;
if (!$this->_bigEndian) {
$bytes = strrev($bytes);
}
$double = unpack('dflt', $bytes);
return $double['flt'];
}
/**
* Writes an IEEE 754 double-precision floating point number from the data stream.
*
* @param string|double $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeDouble($stream)
{
$stream = pack('d', $stream);
if (!$this->_bigEndian) {
$stream = strrev($stream);
}
$this->_stream.= $stream;
return $this;
}
}
| gpl-2.0 |
T0MM0R/magento | web/js/mage/adminhtml/tabs.js | 10013 | /**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
}
| gpl-2.0 |
xtao/openduckbill | src/helper.py | 3110 | #!/usr/bin/python2.4
# Copyright 2008 Google Inc.
# Author : Anoop Chandran <[email protected]>
#
# openduckbill is a simple backup application. It offers support for
# transferring data to a local backup directory, NFS. It also provides
# file system monitoring of directories marked for backup. Please read
# the README file for more details.
#
# 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.
"""Helper class, does command execution and returns value.
This class has the method RunCommandPopen which executes commands passed to
it and returns the status.
"""
import os
import subprocess
import sys
class CommandHelper:
"""Run command and return status, either using Popen or call
"""
def __init__(self, log_handle=''):
"""Initialise logging state
Logging enabled in debug mode.
Args:
log_handle: Object - a handle to the logging subsystem.
"""
self.logmsg = log_handle
if self.logmsg.debug:
self.stdout_debug = None
self.stderr_debug = None
else:
self.stdout_debug = 1
self.stderr_debug = 1
def RunCommandPopen(self, runcmd):
"""Uses subprocess.Popen to run the command.
Also prints the command output if being run in debug mode.
Args:
runcmd: List - path to executable and its arguments.
Retuns:
runretval: Integer - exit value of the command, after execution.
"""
stdout_val=self.stdout_debug
stderr_val=self.stderr_debug
if stdout_val:
stdout_l = file(os.devnull, 'w')
else:
stdout_l=subprocess.PIPE
if stderr_val:
stderr_l = file(os.devnull, 'w')
else:
stderr_l=subprocess.STDOUT
try:
run_proc = subprocess.Popen(runcmd, bufsize=0,
executable=None, stdin=None,
stdout=stdout_l, stderr=stderr_l)
if self.logmsg.debug:
output = run_proc.stdout
while 1:
line = output.readline()
if not line:
break
line = line.rstrip()
self.logmsg.logger.debug("Command output: %s" % line)
run_proc.wait()
runretval = run_proc.returncode
except OSError, e:
self.logmsg.logger.error('%s', e)
runretval = 1
except KeyboardInterrupt, e:
self.logmsg.logger.error('User interrupt')
sys.exit(1)
if stdout_l:
pass
#stderr_l.close()
if stderr_l:
pass
#stderr_l.close()
return runretval
| gpl-2.0 |
cifren/opussalon | administrator/components/com_joomailermailchimpintegration/libraries/TwitterZoid.php | 3467 | <?php
/**
* -----------------------------------------------------------------------------
*
* Functions for TwitterZoid PHP Script
* Copyright (c) 2008 Philip Newborough <[email protected]>
*
* http://crunchbang.org/archives/2008/02/20/twitterzoid-php-script/
*
* 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.
*
* http://www.gnu.org/licenses/
*
* -----------------------------------------------------------------------------
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted Access' );
function timesince($i,$date){
if($i >= time()){
$timeago = JText::_('JM_0_SECONDS_AGO');
return $timeago;
}
$seconds = time()-$i;
$units = array('JM_SECOND' => 1,'JM_MINUTE' => 60,'JM_HOUR' => 3600,'JM_DAY' => 86400,'JM_MONTH' => 2629743,'JM_YEAR' => 31556926);
foreach($units as $key => $val){
if($seconds >= $val){
$results = floor($seconds/$val);
if($key == 'JM_DAY' | $key == 'JM_MONTH' | $key == 'JM_YEAR'){
$timeago = $date;
}else{
$timeago = ($results >= 2) ? JText::_('JM_ABOUT').' ' . $results . ' ' . JText::_($key) . JText::_('JM_S_AGO') : JText::_('JM_ABOUT').' '. $results . ' ' . JText::_($key) .' '. JText::_('JM_AGO');
}
}
}
return $timeago;
}
function twitterit(&$text, $twitter_username, $target='_blank', $nofollow=true){
$urls = _autolink_find_URLS( $text );
if(!empty($urls)){
array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
$text = strtr( $text, $urls );
}
$text = preg_replace("/(\s@|^@)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = preg_replace("/(\s#|^#)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/#!/search?q=$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = str_replace($twitter_username.": ", "",$text);
return $text;
}
function _autolink_find_URLS($text){
$scheme = '(http:\/\/|https:\/\/)';
$www = 'www\.';
$ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$subdomain = '[-a-z0-9_]+\.';
$name = '[a-z][-a-z0-9]+\.';
$tld = '[a-z]+(\.[a-z]{2,2})?';
$the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
$pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";
$pattern = '/'.$pattern.'/is';
$c = preg_match_all($pattern, $text, $m);
unset($text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern);
if($c){
return(array_flip($m[0]));
}
return(array());
}
function _autolink_create_html_tags(&$value, $key, $other=null){
$target = $nofollow = null;
if(is_array($other)){
$target = ($other['target'] ? " target=\"$other[target]\"":null);
$nofollow = ($other['nofollow'] ? ' rel="nofollow"':null);
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}
?>
| gpl-2.0 |
dmacvicar/spacewalk | monitoring/NOCpulsePlugins/SQLServer/SessionsBlocked.pm | 858 | package SQLServer::SessionsBlocked;
use strict;
use SQLServer::Sessions;
sub run {
my %args = @_;
my $result = $args{result};
my %params = %{$args{params}};
my $seconds = $params{sessionTime};
my $millisec = $seconds * 1000;
my $owner = $params{sessionOwner};
my $ss = $args{data_source_factory}->sqlserver(%params);
my $row = $ss->fetch_first(qq{
select 'sessions' = count(*)
from master..sysprocesses
where rtrim(loginame) like '$owner'
and waittime > $millisec
}, ['master..sysprocesses']);
my $sessions = $row->{sessions};
$result->context(SQLServer::Sessions::format_context($owner, 'blocked', $seconds));
$result->metric_value('blocked_sessions', $sessions, '%d');
SQLServer::Sessions::session_percentage($sessions, $ss, $result, 'blocked');
}
1;
| gpl-2.0 |
mattstock/binutils-bexkat1 | gdb/testsuite/gdb.python/py-unwind.c | 2643 | /* This test program is part of GDB, the GNU debugger.
Copyright 2015-2020 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/>. */
/* This is the test program loaded into GDB by the py-unwind test. */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static void *
swap_value (void **location, void *new_value)
{
void *old_value = *location;
*location = new_value;
return old_value;
}
static void
bad_layout(void **variable_ptr, void *fp)
{
fprintf (stderr, "First variable should be allocated one word below "
"the frame. Got variable's address %p, frame at %p instead.\n",
variable_ptr, fp);
abort();
}
#define MY_FRAME (__builtin_frame_address (0))
static void
corrupt_frame_inner (void)
{
/* Save outer frame address, then corrupt the unwind chain by
setting the outer frame address in it to self. This is
ABI-specific: the first word of the frame contains previous frame
address in amd64. */
void *previous_fp = swap_value ((void **) MY_FRAME, MY_FRAME);
/* Verify the compiler allocates the first local variable one word
below frame. This is where the test unwinder expects to find the
correct outer frame address. */
if (&previous_fp + 1 != (void **) MY_FRAME)
bad_layout (&previous_fp + 1, MY_FRAME);
/* Now restore it so that we can return. The test sets the
breakpoint just before this happens, and GDB will not be able to
show the backtrace without JIT reader. */
swap_value ((void **) MY_FRAME, previous_fp); /* break backtrace-broken */
}
static void
corrupt_frame_outer (void)
{
/* See above for the explanation of the code here. This function
corrupts its frame, too, and then calls the inner one. */
void *previous_fp = swap_value ((void **) MY_FRAME, MY_FRAME);
if (&previous_fp + 1 != (void **) MY_FRAME)
bad_layout (&previous_fp, MY_FRAME);
corrupt_frame_inner ();
swap_value ((void **) MY_FRAME, previous_fp);
}
int
main ()
{
corrupt_frame_outer ();
return 0;
}
| gpl-2.0 |
atmark-techno/atmark-dist | user/ruby/ruby-2.1.2/test/rubygems/test_gem_commands_which_command.rb | 1872 | require 'rubygems/test_case'
require 'rubygems/commands/which_command'
class TestGemCommandsWhichCommand < Gem::TestCase
def setup
super
Gem::Specification.reset
@cmd = Gem::Commands::WhichCommand.new
end
def test_execute
util_foo_bar
@cmd.handle_options %w[foo_bar]
use_ui @ui do
@cmd.execute
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_equal '', @ui.error
end
def test_execute_directory
@cmd.handle_options %w[directory]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library directory\n%,
@ui.error
end
def test_execute_one_missing
# TODO: this test fails in isolation
util_foo_bar
@cmd.handle_options %w[foo_bar missinglib]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal "#{@foo_bar.full_gem_path}/lib/foo_bar.rb\n", @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def test_execute_missing
@cmd.handle_options %w[missinglib]
use_ui @ui do
assert_raises Gem::MockGemUi::TermError do
@cmd.execute
end
end
assert_equal '', @ui.output
assert_match %r%Can.t find ruby library file or shared library missinglib\n%,
@ui.error
end
def util_foo_bar
files = %w[lib/foo_bar.rb lib/directory/baz.rb Rakefile]
@foo_bar = util_spec 'foo_bar' do |gem|
gem.files = files
end
files.each do |file|
filename = File.join(@foo_bar.full_gem_path, file)
FileUtils.mkdir_p File.dirname filename
FileUtils.touch filename
end
end
end
| gpl-2.0 |
foxsat-hdr/linux-kernel | drivers/media/dvb/frontends/dvb-pll.h | 661 | /*
* $Id: dvb-pll.h,v 1.2 2005/02/10 11:43:41 kraxel Exp $
*/
#ifndef __DVB_PLL_H__
#define __DVB_PLL_H__
struct dvb_pll_desc {
char *name;
u32 min;
u32 max;
void (*setbw)(u8 *buf, int bandwidth);
int count;
struct {
u32 limit;
u32 offset;
u32 stepsize;
u8 cb1;
u8 cb2;
} entries[9];
};
extern struct dvb_pll_desc dvb_pll_thomson_dtt7579;
extern struct dvb_pll_desc dvb_pll_thomson_dtt759x;
extern struct dvb_pll_desc dvb_pll_thomson_dtt7610;
extern struct dvb_pll_desc dvb_pll_lg_z201;
extern struct dvb_pll_desc dvb_pll_unknown_1;
int dvb_pll_configure(struct dvb_pll_desc *desc, u8 *buf,
u32 freq, int bandwidth);
#endif
| gpl-2.0 |
orgads/psi | src/contactlistmodelupdater.h | 2389 | /*
* contactlistmodelupdater.h - class to group model update operations together
* Copyright (C) 2008-2010 Yandex LLC (Michail Pishchagin)
*
* 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 library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#ifndef CONTACTLISTMODELUPDATER_H
#define CONTACTLISTMODELUPDATER_H
#include <QObject>
#include <QHash>
#include <QDateTime>
class QTimer;
class PsiContact;
class PsiContactList;
class ContactListModelUpdater : public QObject
{
Q_OBJECT
public:
ContactListModelUpdater(PsiContactList* contactList, QObject *parent);
~ContactListModelUpdater();
bool updatesEnabled() const;
void setUpdatesEnabled(bool updatesEnabled);
public slots:
void commit();
void clear();
signals:
void addedContact(PsiContact*);
void removedContact(PsiContact*);
void contactAlert(PsiContact*);
void contactAnim(PsiContact*);
void contactUpdated(PsiContact*);
void contactGroupsChanged(PsiContact*);
void beginBulkContactUpdate();
void endBulkContactUpdate();
public slots:
void addContact(PsiContact*);
private slots:
void removeContact(PsiContact*);
void contactAlert();
void contactAnim();
void contactUpdated();
void contactGroupsChanged();
void beginBulkUpdate();
void endBulkUpdate();
private:
bool updatesEnabled_;
PsiContactList* contactList_;
QTimer* commitTimer_;
QDateTime commitTimerStartTime_;
QHash<PsiContact*, bool> monitoredContacts_;
enum Operation {
AddContact = 1 << 0,
RemoveContact = 1 << 1,
UpdateContact = 1 << 2,
ContactGroupsChanged = 1 << 3,
AnimateContact = 1 << 4
};
QHash<PsiContact*, int> operationQueue_;
void addOperation(PsiContact* contact, Operation operation);
int simplifiedOperationList(int operations) const;
};
#endif
| gpl-2.0 |
thisismeonmounteverest/rox | build/places/templates/memberlist.php | 2396 | <?php
echo '<h2 class="paddingtop">' . $words->get('members') . '</h2>';
$User = new APP_User;
$words = new MOD_words();
$layoutbits = new MOD_layoutbits;
$url = '/places/' . htmlspecialchars($this->countryName) . '/' . $this->countryCode . '/';
if ($this->regionCode) {
$url .= htmlspecialchars($this->regionName) . '/' . $this->regionCode . '/';
}
if ($this->cityCode) {
$url .= htmlspecialchars($this->cityName) . '/' . $this->cityCode . '/';
}
$loginUrlOpen = '<a href="login' . $url . '#login-widget">';
$loginUrlClose = '</a>';
if (!$this->members) {
if ($this->totalMemberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
} else {
echo $words->get('PlacesNoMembersFound', htmlspecialchars($this->placeName));
}
} else {
if ($this->totalMemberCount != $this->memberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
}
// divide members into pages of Places::MEMBERS_PER_PAGE (20)
$params = new StdClass;
$params->strategy = new HalfPagePager('right');
$params->page_url = $url;
$params->page_url_marker = 'page';
$params->page_method = 'url';
$params->items = $this->memberCount;
$params->active_page = $this->pageNumber;
$params->items_per_page = Places::MEMBERS_PER_PAGE;
$pager = new PagerWidget($params);
// show members if there are any to show
echo '<ul class="clearfix">';
foreach ($this->members as $member) {
$image = new MOD_images_Image('',$member->username);
if ($member->HideBirthDate=="No") {
$member->age = floor($layoutbits->fage_value($member->BirthDate));
} else {
$member->age = $words->get("Hidden");
}
echo '<li class="userpicbox float_left">';
echo MOD_layoutbits::PIC_50_50($member->username,'',$style='framed float_left');
echo '<div class="userinfo">';
echo ' <a class="username" href="members/'.$member->username.'">'.
$member->username.'</a><br />';
echo ' <span class="small">'.$words->get("yearsold",$member->age).
'<br />'.$member->city.'</span>';
echo '</div>';
echo '</li>';
}
echo '</ul>';
$pager->render();
}
?>
| gpl-2.0 |
eriser/marsyas | src/marsyas/marsystems/RealvecSource.h | 1968 | /*
** Copyright (C) 1998-2006 George Tzanetakis <[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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#ifndef MARSYAS_REALVECSOURCE_H
#define MARSYAS_REALVECSOURCE_H
#include <marsyas/system/MarSystem.h>
namespace Marsyas
{
/**
\class RealvecSource
\ingroup IO
A RealvecSource takes a realvec and uses it as a source for your
MarSystem network. It is similar to a SoundFileSource except that
as taking a sound file as the input, it takes a realvec that you
create as input.
It is very useful for getting numbers from external sources into
your Marsystems, for example when reading external files of data.
It is also very useful when writing tests for your Marsystems.
You can load up a realvec with data, and then run it through a
Marsystem to test it.
When you feed in a realvec, the rows turn into observations and
the columns turn into samples.
*/
class RealvecSource: public MarSystem
{
private:
MarControlPtr ctrl_data_;
void addControls();
void myUpdate(MarControlPtr sender);
mrs_natural count_;
mrs_natural samplesToUse_;
public:
RealvecSource(std::string name);
RealvecSource(const RealvecSource& a);
~RealvecSource();
MarSystem* clone() const;
void myProcess(realvec& in, realvec& out);
};
}//namespace Marsyas
#endif
| gpl-2.0 |
marcelo-duffles/linux-rat-2.6.10 | drivers/pci/pci.c | 21181 | /*
* $Id: pci.c,v 1.91 1999/01/21 13:34:01 davem Exp $
*
* PCI Bus Services, see include/linux/pci.h for further explanation.
*
* Copyright 1993 -- 1997 Drew Eckhardt, Frederic Potter,
* David Mosberger-Tang
*
* Copyright 1997 -- 2000 Martin Mares <[email protected]>
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <asm/dma.h> /* isa_dma_bridge_buggy */
#undef DEBUG
#ifdef DEBUG
#define DBG(x...) printk(x)
#else
#define DBG(x...)
#endif
/**
* pci_bus_max_busnr - returns maximum PCI bus number of given bus' children
* @bus: pointer to PCI bus structure to search
*
* Given a PCI bus, returns the highest PCI bus number present in the set
* including the given PCI bus and its list of child PCI buses.
*/
unsigned char __devinit
pci_bus_max_busnr(struct pci_bus* bus)
{
struct list_head *tmp;
unsigned char max, n;
max = bus->number;
list_for_each(tmp, &bus->children) {
n = pci_bus_max_busnr(pci_bus_b(tmp));
if(n > max)
max = n;
}
return max;
}
/**
* pci_max_busnr - returns maximum PCI bus number
*
* Returns the highest PCI bus number present in the system global list of
* PCI buses.
*/
unsigned char __devinit
pci_max_busnr(void)
{
struct pci_bus *bus = NULL;
unsigned char max, n;
max = 0;
while ((bus = pci_find_next_bus(bus)) != NULL) {
n = pci_bus_max_busnr(bus);
if(n > max)
max = n;
}
return max;
}
static int __pci_bus_find_cap(struct pci_bus *bus, unsigned int devfn, u8 hdr_type, int cap)
{
u16 status;
u8 pos, id;
int ttl = 48;
pci_bus_read_config_word(bus, devfn, PCI_STATUS, &status);
if (!(status & PCI_STATUS_CAP_LIST))
return 0;
switch (hdr_type) {
case PCI_HEADER_TYPE_NORMAL:
case PCI_HEADER_TYPE_BRIDGE:
pci_bus_read_config_byte(bus, devfn, PCI_CAPABILITY_LIST, &pos);
break;
case PCI_HEADER_TYPE_CARDBUS:
pci_bus_read_config_byte(bus, devfn, PCI_CB_CAPABILITY_LIST, &pos);
break;
default:
return 0;
}
while (ttl-- && pos >= 0x40) {
pos &= ~3;
pci_bus_read_config_byte(bus, devfn, pos + PCI_CAP_LIST_ID, &id);
if (id == 0xff)
break;
if (id == cap)
return pos;
pci_bus_read_config_byte(bus, devfn, pos + PCI_CAP_LIST_NEXT, &pos);
}
return 0;
}
/**
* pci_find_capability - query for devices' capabilities
* @dev: PCI device to query
* @cap: capability code
*
* Tell if a device supports a given PCI capability.
* Returns the address of the requested capability structure within the
* device's PCI configuration space or 0 in case the device does not
* support it. Possible values for @cap:
*
* %PCI_CAP_ID_PM Power Management
* %PCI_CAP_ID_AGP Accelerated Graphics Port
* %PCI_CAP_ID_VPD Vital Product Data
* %PCI_CAP_ID_SLOTID Slot Identification
* %PCI_CAP_ID_MSI Message Signalled Interrupts
* %PCI_CAP_ID_CHSWP CompactPCI HotSwap
* %PCI_CAP_ID_PCIX PCI-X
* %PCI_CAP_ID_EXP PCI Express
*/
int pci_find_capability(struct pci_dev *dev, int cap)
{
return __pci_bus_find_cap(dev->bus, dev->devfn, dev->hdr_type, cap);
}
/**
* pci_bus_find_capability - query for devices' capabilities
* @bus: the PCI bus to query
* @devfn: PCI device to query
* @cap: capability code
*
* Like pci_find_capability() but works for pci devices that do not have a
* pci_dev structure set up yet.
*
* Returns the address of the requested capability structure within the
* device's PCI configuration space or 0 in case the device does not
* support it.
*/
int pci_bus_find_capability(struct pci_bus *bus, unsigned int devfn, int cap)
{
u8 hdr_type;
pci_bus_read_config_byte(bus, devfn, PCI_HEADER_TYPE, &hdr_type);
return __pci_bus_find_cap(bus, devfn, hdr_type & 0x7f, cap);
}
/**
* pci_find_ext_capability - Find an extended capability
* @dev: PCI device to query
* @cap: capability code
*
* Returns the address of the requested extended capability structure
* within the device's PCI configuration space or 0 if the device does
* not support it. Possible values for @cap:
*
* %PCI_EXT_CAP_ID_ERR Advanced Error Reporting
* %PCI_EXT_CAP_ID_VC Virtual Channel
* %PCI_EXT_CAP_ID_DSN Device Serial Number
* %PCI_EXT_CAP_ID_PWR Power Budgeting
*/
int pci_find_ext_capability(struct pci_dev *dev, int cap)
{
u32 header;
int ttl = 480; /* 3840 bytes, minimum 8 bytes per capability */
int pos = 0x100;
if (dev->cfg_size <= 256)
return 0;
if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
return 0;
/*
* If we have no capabilities, this is indicated by cap ID,
* cap version and next pointer all being 0.
*/
if (header == 0)
return 0;
while (ttl-- > 0) {
if (PCI_EXT_CAP_ID(header) == cap)
return pos;
pos = PCI_EXT_CAP_NEXT(header);
if (pos < 0x100)
break;
if (pci_read_config_dword(dev, pos, &header) != PCIBIOS_SUCCESSFUL)
break;
}
return 0;
}
/**
* pci_find_parent_resource - return resource region of parent bus of given region
* @dev: PCI device structure contains resources to be searched
* @res: child resource record for which parent is sought
*
* For given resource region of given device, return the resource
* region of parent bus the given region is contained in or where
* it should be allocated from.
*/
struct resource *
pci_find_parent_resource(const struct pci_dev *dev, struct resource *res)
{
const struct pci_bus *bus = dev->bus;
int i;
struct resource *best = NULL;
for(i = 0; i < PCI_BUS_NUM_RESOURCES; i++) {
struct resource *r = bus->resource[i];
if (!r)
continue;
if (res->start && !(res->start >= r->start && res->end <= r->end))
continue; /* Not contained */
if ((res->flags ^ r->flags) & (IORESOURCE_IO | IORESOURCE_MEM))
continue; /* Wrong type */
if (!((res->flags ^ r->flags) & IORESOURCE_PREFETCH))
return r; /* Exact match */
if ((res->flags & IORESOURCE_PREFETCH) && !(r->flags & IORESOURCE_PREFETCH))
best = r; /* Approximating prefetchable by non-prefetchable */
}
return best;
}
/**
* pci_set_power_state - Set the power state of a PCI device
* @dev: PCI device to be suspended
* @state: Power state we're entering
*
* Transition a device to a new power state, using the Power Management
* Capabilities in the device's config space.
*
* RETURN VALUE:
* -EINVAL if trying to enter a lower state than we're already in.
* 0 if we're already in the requested state.
* -EIO if device does not support PCI PM.
* 0 if we can successfully change the power state.
*/
int
pci_set_power_state(struct pci_dev *dev, int state)
{
int pm;
u16 pmcsr;
/* bound the state we're entering */
if (state > 3) state = 3;
/* Validate current state:
* Can enter D0 from any state, but if we can only go deeper
* to sleep if we're already in a low power state
*/
if (state > 0 && dev->current_state > state)
return -EINVAL;
else if (dev->current_state == state)
return 0; /* we're already there */
/* find PCI PM capability in list */
pm = pci_find_capability(dev, PCI_CAP_ID_PM);
/* abort if the device doesn't support PM capabilities */
if (!pm) return -EIO;
/* check if this device supports the desired state */
if (state == 1 || state == 2) {
u16 pmc;
pci_read_config_word(dev,pm + PCI_PM_PMC,&pmc);
if (state == 1 && !(pmc & PCI_PM_CAP_D1)) return -EIO;
else if (state == 2 && !(pmc & PCI_PM_CAP_D2)) return -EIO;
}
/* If we're in D3, force entire word to 0.
* This doesn't affect PME_Status, disables PME_En, and
* sets PowerState to 0.
*/
if (dev->current_state >= 3)
pmcsr = 0;
else {
pci_read_config_word(dev, pm + PCI_PM_CTRL, &pmcsr);
pmcsr &= ~PCI_PM_CTRL_STATE_MASK;
pmcsr |= state;
}
/* enter specified state */
pci_write_config_word(dev, pm + PCI_PM_CTRL, pmcsr);
/* Mandatory power management transition delays */
/* see PCI PM 1.1 5.6.1 table 18 */
if(state == 3 || dev->current_state == 3)
msleep(10);
else if(state == 2 || dev->current_state == 2)
udelay(200);
dev->current_state = state;
return 0;
}
/**
* pci_save_state - save the PCI configuration space of a device before suspending
* @dev: - PCI device that we're dealing with
* @buffer: - buffer to hold config space context
*
* @buffer must be large enough to hold the entire PCI 2.2 config space
* (>= 64 bytes).
*/
int
pci_save_state(struct pci_dev *dev)
{
int i;
/* XXX: 100% dword access ok here? */
for (i = 0; i < 16; i++)
pci_read_config_dword(dev, i * 4,&dev->saved_config_space[i]);
return 0;
}
/**
* pci_restore_state - Restore the saved state of a PCI device
* @dev: - PCI device that we're dealing with
* @buffer: - saved PCI config space
*
*/
int
pci_restore_state(struct pci_dev *dev)
{
int i;
for (i = 0; i < 16; i++)
pci_write_config_dword(dev,i * 4, dev->saved_config_space[i]);
return 0;
}
/**
* pci_enable_device_bars - Initialize some of a device for use
* @dev: PCI device to be initialized
* @bars: bitmask of BAR's that must be configured
*
* Initialize device before it's used by a driver. Ask low-level code
* to enable selected I/O and memory resources. Wake up the device if it
* was suspended. Beware, this function can fail.
*/
int
pci_enable_device_bars(struct pci_dev *dev, int bars)
{
int err;
pci_set_power_state(dev, 0);
if ((err = pcibios_enable_device(dev, bars)) < 0)
return err;
return 0;
}
/**
* pci_enable_device - Initialize device before it's used by a driver.
* @dev: PCI device to be initialized
*
* Initialize device before it's used by a driver. Ask low-level code
* to enable I/O and memory. Wake up the device if it was suspended.
* Beware, this function can fail.
*/
int
pci_enable_device(struct pci_dev *dev)
{
int err;
dev->is_enabled = 1;
if ((err = pci_enable_device_bars(dev, (1 << PCI_NUM_RESOURCES) - 1)))
return err;
pci_fixup_device(pci_fixup_enable, dev);
return 0;
}
/**
* pcibios_disable_device - disable arch specific PCI resources for device dev
* @dev: the PCI device to disable
*
* Disables architecture specific PCI resources for the device. This
* is the default implementation. Architecture implementations can
* override this.
*/
void __attribute__ ((weak)) pcibios_disable_device (struct pci_dev *dev) {}
/**
* pci_disable_device - Disable PCI device after use
* @dev: PCI device to be disabled
*
* Signal to the system that the PCI device is not in use by the system
* anymore. This only involves disabling PCI bus-mastering, if active.
*/
void
pci_disable_device(struct pci_dev *dev)
{
u16 pci_command;
dev->is_enabled = 0;
dev->is_busmaster = 0;
pci_read_config_word(dev, PCI_COMMAND, &pci_command);
if (pci_command & PCI_COMMAND_MASTER) {
pci_command &= ~PCI_COMMAND_MASTER;
pci_write_config_word(dev, PCI_COMMAND, pci_command);
}
pcibios_disable_device(dev);
}
/**
* pci_enable_wake - enable device to generate PME# when suspended
* @dev: - PCI device to operate on
* @state: - Current state of device.
* @enable: - Flag to enable or disable generation
*
* Set the bits in the device's PM Capabilities to generate PME# when
* the system is suspended.
*
* -EIO is returned if device doesn't have PM Capabilities.
* -EINVAL is returned if device supports it, but can't generate wake events.
* 0 if operation is successful.
*
*/
int pci_enable_wake(struct pci_dev *dev, u32 state, int enable)
{
int pm;
u16 value;
/* find PCI PM capability in list */
pm = pci_find_capability(dev, PCI_CAP_ID_PM);
/* If device doesn't support PM Capabilities, but request is to disable
* wake events, it's a nop; otherwise fail */
if (!pm)
return enable ? -EIO : 0;
/* Check device's ability to generate PME# */
pci_read_config_word(dev,pm+PCI_PM_PMC,&value);
value &= PCI_PM_CAP_PME_MASK;
value >>= ffs(PCI_PM_CAP_PME_MASK) - 1; /* First bit of mask */
/* Check if it can generate PME# from requested state. */
if (!value || !(value & (1 << state)))
return enable ? -EINVAL : 0;
pci_read_config_word(dev, pm + PCI_PM_CTRL, &value);
/* Clear PME_Status by writing 1 to it and enable PME# */
value |= PCI_PM_CTRL_PME_STATUS | PCI_PM_CTRL_PME_ENABLE;
if (!enable)
value &= ~PCI_PM_CTRL_PME_ENABLE;
pci_write_config_word(dev, pm + PCI_PM_CTRL, value);
return 0;
}
int
pci_get_interrupt_pin(struct pci_dev *dev, struct pci_dev **bridge)
{
u8 pin;
pci_read_config_byte(dev, PCI_INTERRUPT_PIN, &pin);
if (!pin)
return -1;
pin--;
while (dev->bus->self) {
pin = (pin + PCI_SLOT(dev->devfn)) % 4;
dev = dev->bus->self;
}
*bridge = dev;
return pin;
}
/**
* pci_release_region - Release a PCI bar
* @pdev: PCI device whose resources were previously reserved by pci_request_region
* @bar: BAR to release
*
* Releases the PCI I/O and memory resources previously reserved by a
* successful call to pci_request_region. Call this function only
* after all use of the PCI regions has ceased.
*/
void pci_release_region(struct pci_dev *pdev, int bar)
{
if (pci_resource_len(pdev, bar) == 0)
return;
if (pci_resource_flags(pdev, bar) & IORESOURCE_IO)
release_region(pci_resource_start(pdev, bar),
pci_resource_len(pdev, bar));
else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM)
release_mem_region(pci_resource_start(pdev, bar),
pci_resource_len(pdev, bar));
}
/**
* pci_request_region - Reserved PCI I/O and memory resource
* @pdev: PCI device whose resources are to be reserved
* @bar: BAR to be reserved
* @res_name: Name to be associated with resource.
*
* Mark the PCI region associated with PCI device @pdev BR @bar as
* being reserved by owner @res_name. Do not access any
* address inside the PCI regions unless this call returns
* successfully.
*
* Returns 0 on success, or %EBUSY on error. A warning
* message is also printed on failure.
*/
int pci_request_region(struct pci_dev *pdev, int bar, char *res_name)
{
if (pci_resource_len(pdev, bar) == 0)
return 0;
if (pci_resource_flags(pdev, bar) & IORESOURCE_IO) {
if (!request_region(pci_resource_start(pdev, bar),
pci_resource_len(pdev, bar), res_name))
goto err_out;
}
else if (pci_resource_flags(pdev, bar) & IORESOURCE_MEM) {
if (!request_mem_region(pci_resource_start(pdev, bar),
pci_resource_len(pdev, bar), res_name))
goto err_out;
}
return 0;
err_out:
printk (KERN_WARNING "PCI: Unable to reserve %s region #%d:%lx@%lx for device %s\n",
pci_resource_flags(pdev, bar) & IORESOURCE_IO ? "I/O" : "mem",
bar + 1, /* PCI BAR # */
pci_resource_len(pdev, bar), pci_resource_start(pdev, bar),
pci_name(pdev));
return -EBUSY;
}
/**
* pci_release_regions - Release reserved PCI I/O and memory resources
* @pdev: PCI device whose resources were previously reserved by pci_request_regions
*
* Releases all PCI I/O and memory resources previously reserved by a
* successful call to pci_request_regions. Call this function only
* after all use of the PCI regions has ceased.
*/
void pci_release_regions(struct pci_dev *pdev)
{
int i;
for (i = 0; i < 6; i++)
pci_release_region(pdev, i);
}
/**
* pci_request_regions - Reserved PCI I/O and memory resources
* @pdev: PCI device whose resources are to be reserved
* @res_name: Name to be associated with resource.
*
* Mark all PCI regions associated with PCI device @pdev as
* being reserved by owner @res_name. Do not access any
* address inside the PCI regions unless this call returns
* successfully.
*
* Returns 0 on success, or %EBUSY on error. A warning
* message is also printed on failure.
*/
int pci_request_regions(struct pci_dev *pdev, char *res_name)
{
int i;
for (i = 0; i < 6; i++)
if(pci_request_region(pdev, i, res_name))
goto err_out;
return 0;
err_out:
while(--i >= 0)
pci_release_region(pdev, i);
return -EBUSY;
}
/**
* pci_set_master - enables bus-mastering for device dev
* @dev: the PCI device to enable
*
* Enables bus-mastering on the device and calls pcibios_set_master()
* to do the needed arch specific settings.
*/
void
pci_set_master(struct pci_dev *dev)
{
u16 cmd;
pci_read_config_word(dev, PCI_COMMAND, &cmd);
if (! (cmd & PCI_COMMAND_MASTER)) {
DBG("PCI: Enabling bus mastering for device %s\n", pci_name(dev));
cmd |= PCI_COMMAND_MASTER;
pci_write_config_word(dev, PCI_COMMAND, cmd);
}
dev->is_busmaster = 1;
pcibios_set_master(dev);
}
#ifndef HAVE_ARCH_PCI_MWI
/* This can be overridden by arch code. */
u8 pci_cache_line_size = L1_CACHE_BYTES >> 2;
/**
* pci_generic_prep_mwi - helper function for pci_set_mwi
* @dev: the PCI device for which MWI is enabled
*
* Helper function for generic implementation of pcibios_prep_mwi
* function. Originally copied from drivers/net/acenic.c.
* Copyright 1998-2001 by Jes Sorensen, <[email protected]>.
*
* RETURNS: An appropriate -ERRNO error value on error, or zero for success.
*/
static int
pci_generic_prep_mwi(struct pci_dev *dev)
{
u8 cacheline_size;
if (!pci_cache_line_size)
return -EINVAL; /* The system doesn't support MWI. */
/* Validate current setting: the PCI_CACHE_LINE_SIZE must be
equal to or multiple of the right value. */
pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
if (cacheline_size >= pci_cache_line_size &&
(cacheline_size % pci_cache_line_size) == 0)
return 0;
/* Write the correct value. */
pci_write_config_byte(dev, PCI_CACHE_LINE_SIZE, pci_cache_line_size);
/* Read it back. */
pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &cacheline_size);
if (cacheline_size == pci_cache_line_size)
return 0;
printk(KERN_DEBUG "PCI: cache line size of %d is not supported "
"by device %s\n", pci_cache_line_size << 2, pci_name(dev));
return -EINVAL;
}
#endif /* !HAVE_ARCH_PCI_MWI */
/**
* pci_set_mwi - enables memory-write-invalidate PCI transaction
* @dev: the PCI device for which MWI is enabled
*
* Enables the Memory-Write-Invalidate transaction in %PCI_COMMAND,
* and then calls @pcibios_set_mwi to do the needed arch specific
* operations or a generic mwi-prep function.
*
* RETURNS: An appropriate -ERRNO error value on error, or zero for success.
*/
int
pci_set_mwi(struct pci_dev *dev)
{
int rc;
u16 cmd;
#ifdef HAVE_ARCH_PCI_MWI
rc = pcibios_prep_mwi(dev);
#else
rc = pci_generic_prep_mwi(dev);
#endif
if (rc)
return rc;
pci_read_config_word(dev, PCI_COMMAND, &cmd);
if (! (cmd & PCI_COMMAND_INVALIDATE)) {
DBG("PCI: Enabling Mem-Wr-Inval for device %s\n", pci_name(dev));
cmd |= PCI_COMMAND_INVALIDATE;
pci_write_config_word(dev, PCI_COMMAND, cmd);
}
return 0;
}
/**
* pci_clear_mwi - disables Memory-Write-Invalidate for device dev
* @dev: the PCI device to disable
*
* Disables PCI Memory-Write-Invalidate transaction on the device
*/
void
pci_clear_mwi(struct pci_dev *dev)
{
u16 cmd;
pci_read_config_word(dev, PCI_COMMAND, &cmd);
if (cmd & PCI_COMMAND_INVALIDATE) {
cmd &= ~PCI_COMMAND_INVALIDATE;
pci_write_config_word(dev, PCI_COMMAND, cmd);
}
}
#ifndef HAVE_ARCH_PCI_SET_DMA_MASK
/*
* These can be overridden by arch-specific implementations
*/
int
pci_set_dma_mask(struct pci_dev *dev, u64 mask)
{
if (!pci_dma_supported(dev, mask))
return -EIO;
dev->dma_mask = mask;
return 0;
}
int
pci_dac_set_dma_mask(struct pci_dev *dev, u64 mask)
{
if (!pci_dac_dma_supported(dev, mask))
return -EIO;
dev->dma_mask = mask;
return 0;
}
int
pci_set_consistent_dma_mask(struct pci_dev *dev, u64 mask)
{
if (!pci_dma_supported(dev, mask))
return -EIO;
dev->dev.coherent_dma_mask = mask;
return 0;
}
#endif
static int __devinit pci_init(void)
{
struct pci_dev *dev = NULL;
while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) {
pci_fixup_device(pci_fixup_final, dev);
}
return 0;
}
static int __devinit pci_setup(char *str)
{
while (str) {
char *k = strchr(str, ',');
if (k)
*k++ = 0;
if (*str && (str = pcibios_setup(str)) && *str) {
/* PCI layer options should be handled here */
printk(KERN_ERR "PCI: Unknown option `%s'\n", str);
}
str = k;
}
return 1;
}
device_initcall(pci_init);
__setup("pci=", pci_setup);
#if defined(CONFIG_ISA) || defined(CONFIG_EISA)
/* FIXME: Some boxes have multiple ISA bridges! */
struct pci_dev *isa_bridge;
EXPORT_SYMBOL(isa_bridge);
#endif
EXPORT_SYMBOL(pci_enable_device_bars);
EXPORT_SYMBOL(pci_enable_device);
EXPORT_SYMBOL(pci_disable_device);
EXPORT_SYMBOL(pci_max_busnr);
EXPORT_SYMBOL(pci_bus_max_busnr);
EXPORT_SYMBOL(pci_find_capability);
EXPORT_SYMBOL(pci_bus_find_capability);
EXPORT_SYMBOL(pci_release_regions);
EXPORT_SYMBOL(pci_request_regions);
EXPORT_SYMBOL(pci_release_region);
EXPORT_SYMBOL(pci_request_region);
EXPORT_SYMBOL(pci_set_master);
EXPORT_SYMBOL(pci_set_mwi);
EXPORT_SYMBOL(pci_clear_mwi);
EXPORT_SYMBOL(pci_set_dma_mask);
EXPORT_SYMBOL(pci_dac_set_dma_mask);
EXPORT_SYMBOL(pci_set_consistent_dma_mask);
EXPORT_SYMBOL(pci_assign_resource);
EXPORT_SYMBOL(pci_find_parent_resource);
EXPORT_SYMBOL(pci_set_power_state);
EXPORT_SYMBOL(pci_save_state);
EXPORT_SYMBOL(pci_restore_state);
EXPORT_SYMBOL(pci_enable_wake);
/* Quirk info */
EXPORT_SYMBOL(isa_dma_bridge_buggy);
EXPORT_SYMBOL(pci_pci_problems);
| gpl-2.0 |
kynesim/wireshark | epan/dissectors/packet-ccsds.c | 26397 | /* packet-ccsds.c
* Routines for CCSDS dissection
* Copyright 2000, Scott Hovis [email protected]
* Enhanced 2008, Matt Dunkle [email protected]
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* 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 <epan/packet.h>
#include <epan/expert.h>
#include <epan/prefs.h>
#include <epan/to_str.h>
void proto_register_ccsds(void);
void proto_reg_handoff_ccsds(void);
/*
* See
*
* http://public.ccsds.org/publications/archive/133x0b1c1.pdf section 4.1 -- CCSDS 133.0-B-1 replaces CCSDS 701.0-B-2
* http://www.everyspec.com/NASA/NASA+-+JSC/NASA+-+SSP+PUBS/download.php?spec=SSP_52050E.003096.pdf section 3.1.3
*
* for some information.
*/
/* Initialize the protocol and registered fields */
static int proto_ccsds = -1;
/* primary ccsds header */
static int hf_ccsds_header_flags = -1;
static int hf_ccsds_apid = -1;
static int hf_ccsds_version = -1;
static int hf_ccsds_secheader = -1;
static int hf_ccsds_type = -1;
static int hf_ccsds_seqnum = -1;
static int hf_ccsds_seqflag = -1;
static int hf_ccsds_length = -1;
/* common ccsds secondary header */
static int hf_ccsds_coarse_time = -1;
static int hf_ccsds_fine_time = -1;
static int hf_ccsds_timeid = -1;
static int hf_ccsds_checkword_flag = -1;
/* payload specific ccsds secondary header */
static int hf_ccsds_zoe = -1;
static int hf_ccsds_packet_type_unused = -1;
static int hf_ccsds_vid = -1;
static int hf_ccsds_dcc = -1;
/* core specific ccsds secondary header */
/* static int hf_ccsds_spare1 = -1; */
static int hf_ccsds_packet_type = -1;
/* static int hf_ccsds_spare2 = -1; */
static int hf_ccsds_element_id = -1;
static int hf_ccsds_cmd_data_packet = -1;
static int hf_ccsds_format_version_id = -1;
static int hf_ccsds_extended_format_id = -1;
/* static int hf_ccsds_spare3 = -1; */
static int hf_ccsds_frame_id = -1;
static int hf_ccsds_embedded_time = -1;
static int hf_ccsds_user_data = -1;
/* ccsds checkword (checksum) */
static int hf_ccsds_checkword = -1;
static int hf_ccsds_checkword_good = -1;
static int hf_ccsds_checkword_bad = -1;
/* Initialize the subtree pointers */
static gint ett_ccsds_primary_header_flags = -1;
static gint ett_ccsds = -1;
static gint ett_ccsds_primary_header = -1;
static gint ett_ccsds_secondary_header = -1;
static gint ett_ccsds_checkword = -1;
static expert_field ei_ccsds_length_error = EI_INIT;
static expert_field ei_ccsds_checkword = EI_INIT;
/* Dissectot table */
static dissector_table_t ccsds_dissector_table;
static const enum_val_t dissect_checkword[] = {
{ "hdr", "Use header flag", 2 },
{ "no", "Override header flag to be false", 0 },
{ "yes", "Override header flag to be true", 1 },
{ NULL, NULL, 0 }
};
/* Global preferences */
/* As defined above, default is to use header flag */
static gint global_dissect_checkword = 2;
/*
* Bits in the first 16-bit header word
*/
#define HDR_VERSION 0xe000
#define HDR_TYPE 0x1000
#define HDR_SECHDR 0x0800
#define HDR_APID 0x07ff
/* some basic sizing parameters */
enum
{
IP_HEADER_LENGTH = 48,
VCDU_HEADER_LENGTH = 6,
CCSDS_PRIMARY_HEADER_LENGTH = 6,
CCSDS_SECONDARY_HEADER_LENGTH = 10
};
/* leap year macro */
#ifndef Leap
# define Leap(yr) ( ( 0 == (yr)%4 && 0 != (yr)%100 ) || ( 0 == (yr)%400 ) )
#endif
static const value_string ccsds_primary_header_sequence_flags[] = {
{ 0, "Continuation segment" },
{ 1, "First segment" },
{ 2, "Last segment" },
{ 3, "Unsegmented data" },
{ 0, NULL }
};
static const value_string ccsds_secondary_header_type[] = {
{ 0, "Core" },
{ 1, "Payload" },
{ 0, NULL }
};
static const value_string ccsds_secondary_header_packet_type[] = {
{ 0, "UNDEFINED" },
{ 1, "Data Dump" },
{ 2, "UNDEFINED" },
{ 3, "UNDEFINED" },
{ 4, "TLM/Status" },
{ 5, "UNDEFINED" },
{ 6, "Payload Private/Science" },
{ 7, "Ancillary Data" },
{ 8, "Essential Cmd" },
{ 9, "System Cmd" },
{ 10, "Payload Cmd" },
{ 11, "Data Load/File Transfer" },
{ 12, "UNDEFINED" },
{ 13, "UNDEFINED" },
{ 14, "UNDEFINED" },
{ 15, "UNDEFINED" },
{ 0, NULL }
};
static const value_string ccsds_secondary_header_element_id[] = {
{ 0, "NASA (Ground Test Only)" },
{ 1, "NASA" },
{ 2, "ESA/APM" },
{ 3, "NASDA" },
{ 4, "RSA" },
{ 5, "CSA" },
{ 6, "ESA/ATV" },
{ 7, "ASI" },
{ 8, "ESA/ERA" },
{ 9, "Reserved" },
{ 10, "RSA SPP" },
{ 11, "NASDA HTV" },
{ 12, "Reserved" },
{ 13, "Reserved" },
{ 14, "Reserved" },
{ 15, "Reserved" },
{ 0, NULL }
};
static const value_string ccsds_secondary_header_cmd_data_packet[] = {
{ 0, "Command Packet" },
{ 1, "Data Packet" },
{ 0, NULL }
};
static const value_string ccsds_secondary_header_format_id[] = {
{ 0, "Reserved" },
{ 1, "Essential Telemetry" },
{ 2, "Housekeeping Tlm - 1" },
{ 3, "Housekeeping Tlm - 2" },
{ 4, "PCS DDT" },
{ 5, "CCS S-Band Command Response" },
{ 6, "Contingency Telemetry via the SMCC" },
{ 7, "Normal Data Dump" },
{ 8, "Extended Data Dump" },
{ 9, "Reserved" },
{ 10, "Reserved" },
{ 11, "Broadcast Ancillary Data" },
{ 12, "Reserved" },
{ 13, "NCS to OIU Telemetry and ECOMM Telemetry" },
{ 14, "CCS to OIU Telemetry - Direct" },
{ 15, "Reserved" },
{ 16, "Normal File Dump" },
{ 17, "Extended File Dump" },
{ 18, "NCS to FGB Telemetry" },
{ 19, "Reserved" },
{ 20, "ZOE Normal Dump (S-Band)" },
{ 21, "ZOE Extended Dump (S-Band)" },
{ 22, "EMU S-Band TLM Packet" },
{ 23, "Reserved" },
{ 24, "Reserved" },
{ 25, "Reserved" },
{ 26, "CCS to OIU Telemetry via UHF" },
{ 27, "OSTP Telemetry (After Flight 1E, CCS R5)" },
{ 28, "Reserved" },
{ 29, "Reserved" },
{ 30, "Reserved" },
{ 31, "Reserved" },
{ 32, "Reserved" },
{ 33, "Reserved" },
{ 34, "Reserved" },
{ 35, "Reserved" },
{ 36, "Reserved" },
{ 37, "Reserved" },
{ 38, "Reserved" },
{ 39, "Reserved" },
{ 40, "Reserved" },
{ 41, "Reserved" },
{ 42, "Reserved" },
{ 43, "Reserved" },
{ 44, "Reserved" },
{ 45, "Reserved" },
{ 46, "Reserved" },
{ 47, "Reserved" },
{ 48, "Reserved" },
{ 49, "Reserved" },
{ 50, "Reserved" },
{ 51, "Reserved" },
{ 52, "Reserved" },
{ 53, "Reserved" },
{ 54, "Reserved" },
{ 55, "Reserved" },
{ 56, "Reserved" },
{ 57, "Reserved" },
{ 58, "Reserved" },
{ 59, "Reserved" },
{ 60, "Reserved" },
{ 61, "Reserved" },
{ 62, "Reserved" },
{ 63, "Reserved" },
{ 0, NULL }
};
static value_string_ext ccsds_secondary_header_format_id_ext = VALUE_STRING_EXT_INIT(ccsds_secondary_header_format_id);
/* convert ccsds embedded time to a human readable string - NOT THREAD SAFE */
static const char* embedded_time_to_string ( int coarse_time, int fine_time )
{
static int utcdiff = 0;
nstime_t t;
int yr;
int fraction;
int multiplier = 1000;
/* compute the static constant difference in seconds
* between midnight 5-6 January 1980 (GPS time) and
* seconds since 1/1/1970 (UTC time) just this once
*/
if ( 0 == utcdiff )
{
for ( yr = 1970; yr < 1980; ++yr )
{
utcdiff += ( Leap(yr) ? 366 : 365 ) * 24 * 60 * 60;
}
utcdiff += 5 * 24 * 60 * 60; /* five days of January 1980 */
}
t.secs = coarse_time + utcdiff;
fraction = ( multiplier * ( (int)fine_time & 0xff ) ) / 256;
t.nsecs = fraction*1000000; /* msecs to nsecs */
return abs_time_to_str(wmem_packet_scope(), &t, ABSOLUTE_TIME_DOY_UTC, TRUE);
}
/* Code to actually dissect the packets */
static int
dissect_ccsds(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_)
{
int offset = 0;
proto_item *ccsds_packet;
proto_tree *ccsds_tree;
proto_item *primary_header;
proto_tree *primary_header_tree;
guint16 first_word;
guint32 coarse_time;
guint8 fine_time;
proto_item *secondary_header;
proto_tree *secondary_header_tree;
const char *time_string;
gint ccsds_length;
gint length = 0;
gint reported_length;
guint8 checkword_flag = 0;
gint counter = 0;
proto_item *item, *checkword_item = NULL;
proto_tree *checkword_tree;
guint16 checkword_field = 0;
guint16 checkword_sum = 0;
tvbuff_t *next_tvb;
static const int * header_flags[] = {
&hf_ccsds_version,
&hf_ccsds_type,
&hf_ccsds_secheader,
&hf_ccsds_apid,
NULL
};
col_set_str(pinfo->cinfo, COL_PROTOCOL, "CCSDS");
col_set_str(pinfo->cinfo, COL_INFO, "CCSDS Packet");
first_word = tvb_get_ntohs(tvb, 0);
col_add_fstr(pinfo->cinfo, COL_INFO, "APID %4d (0x%03X)", first_word&HDR_APID, first_word&HDR_APID);
reported_length = tvb_reported_length_remaining(tvb, 0);
ccsds_length = tvb_get_ntohs(tvb, 4) + CCSDS_PRIMARY_HEADER_LENGTH + 1;
/* Min length is size of headers, whereas max length is reported length.
* If the length field in the CCSDS header is outside of these bounds,
* use the value it violates. Otherwise, use the length field value.
*/
if (ccsds_length > reported_length)
length = reported_length;
else if (ccsds_length < CCSDS_PRIMARY_HEADER_LENGTH + CCSDS_SECONDARY_HEADER_LENGTH)
length = CCSDS_PRIMARY_HEADER_LENGTH + CCSDS_SECONDARY_HEADER_LENGTH;
else
length = ccsds_length;
ccsds_packet = proto_tree_add_item(tree, proto_ccsds, tvb, 0, length, ENC_NA);
ccsds_tree = proto_item_add_subtree(ccsds_packet, ett_ccsds);
/* build the ccsds primary header tree */
primary_header_tree = proto_tree_add_subtree(ccsds_tree, tvb, offset, CCSDS_PRIMARY_HEADER_LENGTH,
ett_ccsds_primary_header, &primary_header, "Primary CCSDS Header");
proto_tree_add_bitmask(primary_header_tree, tvb, offset, hf_ccsds_header_flags,
ett_ccsds_primary_header_flags, header_flags, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(primary_header_tree, hf_ccsds_seqflag, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(primary_header_tree, hf_ccsds_seqnum, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
item = proto_tree_add_item(primary_header_tree, hf_ccsds_length, tvb, offset, 2, ENC_BIG_ENDIAN);
if (ccsds_length > reported_length) {
expert_add_info(pinfo, item, &ei_ccsds_length_error);
}
offset += 2;
proto_item_set_end(primary_header, tvb, offset);
/* build the ccsds secondary header tree */
if ( first_word & HDR_SECHDR )
{
secondary_header_tree = proto_tree_add_subtree(ccsds_tree, tvb, offset, CCSDS_SECONDARY_HEADER_LENGTH,
ett_ccsds_secondary_header, &secondary_header, "Secondary CCSDS Header");
/* command ccsds secondary header flags */
coarse_time = tvb_get_ntohl(tvb, offset);
proto_tree_add_item(secondary_header_tree, hf_ccsds_coarse_time, tvb, offset, 4, ENC_BIG_ENDIAN);
offset += 4;
fine_time = tvb_get_guint8(tvb, offset);
proto_tree_add_item(secondary_header_tree, hf_ccsds_fine_time, tvb, offset, 1, ENC_BIG_ENDIAN);
++offset;
time_string = embedded_time_to_string ( coarse_time, fine_time );
proto_tree_add_string(secondary_header_tree, hf_ccsds_embedded_time, tvb, offset-5, 5, time_string);
proto_tree_add_item(secondary_header_tree, hf_ccsds_timeid, tvb, offset, 1, ENC_BIG_ENDIAN);
checkword_item = proto_tree_add_item(secondary_header_tree, hf_ccsds_checkword_flag, tvb, offset, 1, ENC_BIG_ENDIAN);
/* Global Preference: how to handle checkword flag */
switch (global_dissect_checkword) {
case 0:
/* force checkword presence flag to be false */
checkword_flag = 0;
break;
case 1:
/* force checkword presence flag to be true */
checkword_flag = 1;
break;
default:
/* use value of checkword presence flag from header */
checkword_flag = (tvb_get_guint8(tvb, offset)&0x20) >> 5;
break;
}
/* payload specific ccsds secondary header flags */
if ( first_word & HDR_TYPE )
{
proto_tree_add_item(secondary_header_tree, hf_ccsds_zoe, tvb, offset, 1, ENC_BIG_ENDIAN);
proto_tree_add_item(secondary_header_tree, hf_ccsds_packet_type_unused, tvb, offset, 1, ENC_BIG_ENDIAN);
++offset;
proto_tree_add_item(secondary_header_tree, hf_ccsds_vid, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
proto_tree_add_item(secondary_header_tree, hf_ccsds_dcc, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
}
/* core specific ccsds secondary header flags */
else
{
/* proto_tree_add_item(secondary_header_tree, hf_ccsds_spare1, tvb, offset, 1, ENC_BIG_ENDIAN); */
proto_tree_add_item(secondary_header_tree, hf_ccsds_packet_type, tvb, offset, 1, ENC_BIG_ENDIAN);
++offset;
/* proto_tree_add_item(secondary_header_tree, hf_ccsds_spare2, tvb, offset, 2, ENC_BIG_ENDIAN); */
proto_tree_add_item(secondary_header_tree, hf_ccsds_element_id, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(secondary_header_tree, hf_ccsds_cmd_data_packet, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(secondary_header_tree, hf_ccsds_format_version_id, tvb, offset, 2, ENC_BIG_ENDIAN);
proto_tree_add_item(secondary_header_tree, hf_ccsds_extended_format_id, tvb, offset, 2, ENC_BIG_ENDIAN);
offset += 2;
/* proto_tree_add_item(secondary_header_tree, hf_ccsds_spare3, tvb, offset, 1, ENC_BIG_ENDIAN); */
++offset;
proto_tree_add_item(secondary_header_tree, hf_ccsds_frame_id, tvb, offset, 1, ENC_BIG_ENDIAN);
++offset;
}
/* finish the ccsds secondary header */
proto_item_set_end(secondary_header, tvb, offset);
}
/* If there wasn't a full packet, then don't allow a tree item for checkword. */
if (reported_length < ccsds_length || ccsds_length < CCSDS_PRIMARY_HEADER_LENGTH + CCSDS_SECONDARY_HEADER_LENGTH) {
/* Label CCSDS payload 'User Data' */
if (length > offset)
proto_tree_add_item(ccsds_tree, hf_ccsds_user_data, tvb, offset, length-offset, ENC_NA);
offset += length-offset;
if (checkword_flag == 1)
expert_add_info(pinfo, checkword_item, &ei_ccsds_checkword);
}
/* Handle checkword according to CCSDS preference setting. */
else {
next_tvb = tvb_new_subset_remaining(tvb, offset);
/* Look for a subdissector for the CCSDS payload */
if (!dissector_try_uint(ccsds_dissector_table, first_word&HDR_APID, next_tvb, pinfo, tree)) {
/* If no subdissector is found, label the CCSDS payload as 'User Data' */
proto_tree_add_item(ccsds_tree, hf_ccsds_user_data, tvb, offset, length-offset-2*checkword_flag, ENC_NA);
}
offset += length-offset-2*checkword_flag;
/* If checkword is present, calculate packet checksum (16-bit running sum) for comparison */
if (checkword_flag == 1) {
/* don't count the checkword as part of the checksum */
while (counter < ccsds_length-2) {
checkword_sum += tvb_get_ntohs(tvb, counter);
counter += 2;
}
checkword_field = tvb_get_ntohs(tvb, offset);
/* Report checkword status */
if (checkword_sum == checkword_field) {
item = proto_tree_add_uint_format_value(ccsds_tree, hf_ccsds_checkword, tvb, offset, 2, checkword_field,
"0x%04x [correct]", checkword_field);
checkword_tree = proto_item_add_subtree(item, ett_ccsds_checkword);
item = proto_tree_add_boolean(checkword_tree, hf_ccsds_checkword_good, tvb, offset, 2, TRUE);
PROTO_ITEM_SET_GENERATED(item);
item = proto_tree_add_boolean(checkword_tree, hf_ccsds_checkword_bad, tvb, offset, 2, FALSE);
PROTO_ITEM_SET_GENERATED(item);
} else {
item = proto_tree_add_uint_format_value(ccsds_tree, hf_ccsds_checkword, tvb, offset, 2, checkword_field,
"0x%04x [incorrect, should be 0x%04x]", checkword_field, checkword_sum);
checkword_tree = proto_item_add_subtree(item, ett_ccsds_checkword);
item = proto_tree_add_boolean(checkword_tree, hf_ccsds_checkword_good, tvb, offset, 2, FALSE);
PROTO_ITEM_SET_GENERATED(item);
item = proto_tree_add_boolean(checkword_tree, hf_ccsds_checkword_bad, tvb, offset, 2, TRUE);
PROTO_ITEM_SET_GENERATED(item);
}
offset += 2;
}
}
/* Give the data dissector any bytes past the CCSDS packet length */
call_data_dissector(tvb_new_subset_remaining(tvb, offset), pinfo, tree);
return tvb_captured_length(tvb);
}
void
proto_register_ccsds(void)
{
static hf_register_info hf[] = {
/* primary ccsds header flags */
{ &hf_ccsds_header_flags,
{ "Header Flags", "ccsds.header_flags",
FT_UINT16, BASE_HEX, NULL, 0x0,
NULL, HFILL }
},
{ &hf_ccsds_version,
{ "Version", "ccsds.version",
FT_UINT16, BASE_DEC, NULL, HDR_VERSION,
NULL, HFILL }
},
{ &hf_ccsds_type,
{ "Type", "ccsds.type",
FT_UINT16, BASE_DEC, VALS(ccsds_secondary_header_type), HDR_TYPE,
NULL, HFILL }
},
{ &hf_ccsds_secheader,
{ "Secondary Header", "ccsds.secheader",
FT_BOOLEAN, 16, NULL, HDR_SECHDR,
"Secondary Header Present", HFILL }
},
{ &hf_ccsds_apid,
{ "APID", "ccsds.apid",
FT_UINT16, BASE_DEC, NULL, HDR_APID,
NULL, HFILL }
},
{ &hf_ccsds_seqflag,
{ "Sequence Flags", "ccsds.seqflag",
FT_UINT16, BASE_DEC, VALS(ccsds_primary_header_sequence_flags), 0xc000,
NULL, HFILL }
},
{ &hf_ccsds_seqnum,
{ "Sequence Number", "ccsds.seqnum",
FT_UINT16, BASE_DEC, NULL, 0x3fff,
NULL, HFILL }
},
{ &hf_ccsds_length,
{ "Packet Length", "ccsds.length",
FT_UINT16, BASE_DEC, NULL, 0xffff,
NULL, HFILL }
},
/* common ccsds secondary header flags */
{ &hf_ccsds_coarse_time,
{ "Coarse Time", "ccsds.coarse_time",
FT_UINT32, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_ccsds_fine_time,
{ "Fine Time", "ccsds.fine_time",
FT_UINT8, BASE_DEC, NULL, 0xff,
NULL, HFILL }
},
{ &hf_ccsds_timeid,
{ "Time Identifier", "ccsds.timeid",
FT_UINT8, BASE_DEC, NULL, 0xc0,
NULL, HFILL }
},
{ &hf_ccsds_checkword_flag,
{ "Checkword Indicator", "ccsds.checkword_flag",
FT_BOOLEAN, 8, NULL, 0x20,
"Checkword present", HFILL }
},
/* payload specific ccsds secondary header flags */
{ &hf_ccsds_zoe,
{ "ZOE TLM", "ccsds.zoe",
FT_UINT8, BASE_DEC, NULL, 0x10,
"Contains S-band ZOE Packets", HFILL }
},
{ &hf_ccsds_packet_type_unused,
{ "Packet Type (unused for Ku-band)", "ccsds.packet_type",
FT_UINT8, BASE_DEC, NULL, 0x0f,
NULL, HFILL }
},
{ &hf_ccsds_vid,
{ "Version Identifier", "ccsds.vid",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
{ &hf_ccsds_dcc,
{ "Data Cycle Counter", "ccsds.dcc",
FT_UINT16, BASE_DEC, NULL, 0x0,
NULL, HFILL }
},
/* core specific ccsds secondary header flags */
#if 0
{ &hf_ccsds_spare1,
{ "Spare Bit 1", "ccsds.spare1",
FT_UINT8, BASE_DEC, NULL, 0x10,
"unused spare bit 1", HFILL }
},
#endif
{ &hf_ccsds_packet_type,
{ "Packet Type", "ccsds.packet_type",
FT_UINT8, BASE_DEC, VALS(ccsds_secondary_header_packet_type), 0x0f,
NULL, HFILL }
},
#if 0
{ &hf_ccsds_spare2,
{ "Spare Bit 2", "ccsds.spare2",
FT_UINT16, BASE_DEC, NULL, 0x8000,
NULL, HFILL }
},
#endif
{ &hf_ccsds_element_id,
{ "Element ID", "ccsds.element_id",
FT_UINT16, BASE_DEC, VALS(ccsds_secondary_header_element_id), 0x7800,
NULL, HFILL }
},
{ &hf_ccsds_cmd_data_packet,
{ "Cmd/Data Packet Indicator", "ccsds.cmd_data_packet",
FT_UINT16, BASE_DEC, VALS(ccsds_secondary_header_cmd_data_packet), 0x0400,
NULL, HFILL }
},
{ &hf_ccsds_format_version_id,
{ "Format Version ID", "ccsds.format_version_id",
FT_UINT16, BASE_DEC, NULL, 0x03c0,
NULL, HFILL }
},
{ &hf_ccsds_extended_format_id,
{ "Extended Format ID", "ccsds.extended_format_id",
FT_UINT16, BASE_DEC | BASE_EXT_STRING, &ccsds_secondary_header_format_id_ext, 0x003f,
NULL, HFILL }
},
#if 0
{ &hf_ccsds_spare3,
{ "Spare Bits 3", "ccsds.spare3",
FT_UINT8, BASE_DEC, NULL, 0xff,
NULL, HFILL }
},
#endif
{ &hf_ccsds_frame_id,
{ "Frame ID", "ccsds.frame_id",
FT_UINT8, BASE_DEC, NULL, 0xff,
NULL, HFILL }
},
{ &hf_ccsds_embedded_time,
{ "Embedded Time", "ccsds.embedded_time",
FT_STRING, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_ccsds_user_data,
{ "User Data", "ccsds.user_data",
FT_BYTES, BASE_NONE, NULL, 0x0,
NULL, HFILL }
},
{ &hf_ccsds_checkword,
{ "CCSDS checkword", "ccsds.checkword",
FT_UINT16, BASE_HEX, NULL, 0x0,
"CCSDS checkword: 16-bit running sum of all bytes excluding the checkword", HFILL }
},
{ &hf_ccsds_checkword_good,
{ "Good", "ccsds.checkword_good",
FT_BOOLEAN, BASE_NONE, NULL, 0x0,
"True: checkword matches packet content; False: doesn't match content", HFILL }
},
{ &hf_ccsds_checkword_bad,
{ "Bad", "ccsds.checkword_bad",
FT_BOOLEAN, BASE_NONE, NULL, 0x0,
"True: checkword doesn't match packet content; False: matches content", HFILL }
}
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_ccsds_primary_header_flags,
&ett_ccsds,
&ett_ccsds_primary_header,
&ett_ccsds_secondary_header,
&ett_ccsds_checkword
};
static ei_register_info ei[] = {
{ &ei_ccsds_length_error, { "ccsds.length.error", PI_MALFORMED, PI_ERROR, "Length field value is greater than the packet seen on the wire", EXPFILL }},
{ &ei_ccsds_checkword, { "ccsds.no_checkword", PI_PROTOCOL, PI_WARN, "Packet does not contain a Checkword", EXPFILL }},
};
/* Define the CCSDS preferences module */
module_t *ccsds_module;
expert_module_t* expert_ccsds;
/* Register the protocol name and description */
proto_ccsds = proto_register_protocol("CCSDS", "CCSDS", "ccsds");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array(proto_ccsds, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_ccsds = expert_register_protocol(proto_ccsds);
expert_register_field_array(expert_ccsds, ei, array_length(ei));
register_dissector ( "ccsds", dissect_ccsds, proto_ccsds );
/* Register preferences module */
ccsds_module = prefs_register_protocol(proto_ccsds, NULL);
prefs_register_enum_preference(ccsds_module, "global_pref_checkword",
"How to handle the CCSDS checkword",
"Specify how the dissector should handle the CCSDS checkword",
&global_dissect_checkword, dissect_checkword, FALSE);
/* Dissector table for sub-dissetors */
ccsds_dissector_table = register_dissector_table("ccsds.apid", "CCSDS apid", proto_ccsds, FT_UINT16, BASE_DEC, DISSECTOR_TABLE_NOT_ALLOW_DUPLICATE);
}
void
proto_reg_handoff_ccsds(void)
{
dissector_add_for_decode_as ( "udp.port", find_dissector("ccsds") );
}
/*
* Editor modelines - http://www.wireshark.org/tools/modelines.html
*
* Local variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* vi: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| gpl-2.0 |
id-Software/DOOM-iOS | code/iphone/UIFontLabel.h | 426 | /*
=======================================================================================
Copyright (C) 2009-2011 id Software LLC, a ZeniMax Media company. All Right Reserved.
This file is part of the DOOM Classic iOS v2.1 GPL Source Code.
=======================================================================================
*/
#import <Foundation/Foundation.h>
@interface UIFontLabel : UILabel {
}
@end
| gpl-2.0 |
project-magpie/tdt-driver | stgfb/stmfb-3.1_stm24_0104/soc/sti7108/sti7108vdp.h | 918 | /***********************************************************************
*
* File: soc/sti7108/sti7108vdp.h
* Copyright (c) 2009 STMicroelectronics Limited.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*
\***********************************************************************/
#ifndef _STI7108_VDP_H
#define _STI7108_VDP_H
#include <Gamma/DEIVideoPipe.h>
class CSTi7108VDP: public CDEIVideoPipe
{
public:
CSTi7108VDP(stm_plane_id_t planeID,
CGammaVideoPlug *plug,
ULONG vdpBaseAddr): CDEIVideoPipe(planeID,plug,vdpBaseAddr)
{
m_bHaveDeinterlacer = false;
m_keepHistoricBufferForDeinterlacing = false;
}
private:
CSTi7108VDP (const CSTi7108VDP &);
CSTi7108VDP& operator= (const CSTi7108VDP &);
};
#endif // _STI7108_VDP_H
| gpl-2.0 |
fleeboy/tatt2tatt | core/modules/views/tests/src/Controller/ViewAjaxControllerTest.php | 8895 | <?php
/**
* @file
* Contains \Drupal\views\Tests\Controller\ViewAjaxControllerTest.
*/
namespace Drupal\views\Tests\Controller {
use Drupal\Tests\UnitTestCase;
use Drupal\views\Ajax\ViewAjaxResponse;
use Drupal\views\Controller\ViewAjaxController;
use Symfony\Component\HttpFoundation\Request;
/**
* @coversDefaultClass \Drupal\views\Controller\ViewAjaxController
* @group views
*/
class ViewAjaxControllerTest extends UnitTestCase {
/**
* The mocked view entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $viewStorage;
/**
* The mocked executable factory.
*
* @var \Drupal\views\ViewExecutableFactory|\PHPUnit_Framework_MockObject_MockObject
*/
protected $executableFactory;
/**
* The tested views ajax controller.
*
* @var \Drupal\views\Controller\ViewAjaxController
*/
protected $viewAjaxController;
protected function setUp() {
$this->viewStorage = $this->getMock('Drupal\Core\Entity\EntityStorageInterface');
$this->executableFactory = $this->getMockBuilder('Drupal\views\ViewExecutableFactory')
->disableOriginalConstructor()
->getMock();
$this->viewAjaxController = new TestViewAjaxController($this->viewStorage, $this->executableFactory);
}
/**
* Tests missing view_name and view_display_id
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testMissingViewName() {
$request = new Request();
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests with view_name and view_display_id but not existing view.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
*/
public function testMissingView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue(FALSE));
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests a view without having access to it.
*
* @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
*/
public function testAccessDeniedView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue($view));
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$executable->expects($this->once())
->method('access')
->will($this->returnValue(FALSE));
$this->executableFactory->expects($this->once())
->method('get')
->with($view)
->will($this->returnValue($executable));
$this->viewAjaxController->ajaxView($request);
}
/**
* Tests a valid view without arguments pagers etc.
*/
public function testAjaxView() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
list($view, $executable) = $this->setupValidMocks();
$display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
// Ensure that the pager element is not set.
$display_handler->expects($this->never())
->method('setOption');
$display_bag = $this->getMockBuilder('Drupal\views\DisplayBag')
->disableOriginalConstructor()
->getMock();
$display_bag->expects($this->any())
->method('get')
->with('page_1')
->will($this->returnValue($display_handler));
$executable->displayHandlers = $display_bag;
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$this->assertSame($response->getView(), $executable);
$this->assertViewResultCommand($response);
}
/**
* Tests a valid view with arguments.
*/
public function testAjaxViewWithArguments() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$request->request->set('view_args', 'arg1/arg2');
list($view, $executable) = $this->setupValidMocks();
$executable->expects($this->once())
->method('preview')
->with('page_1', array('arg1', 'arg2'));
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$this->assertViewResultCommand($response);
}
/**
* Tests a valid view with a pager.
*/
public function testAjaxViewWithPager() {
$request = new Request();
$request->request->set('view_name', 'test_view');
$request->request->set('view_display_id', 'page_1');
$dom_id = $this->randomMachineName(20);
$request->request->set('view_dom_id', $dom_id);
$request->request->set('pager_element', '0');
list($view, $executable) = $this->setupValidMocks();
$display_handler = $this->getMockBuilder('Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMock();
$display_handler->expects($this->once())
->method('setOption', '0')
->with($this->equalTo('pager_element'));
$display_bag = $this->getMockBuilder('Drupal\views\DisplayBag')
->disableOriginalConstructor()
->getMock();
$display_bag->expects($this->any())
->method('get')
->with('page_1')
->will($this->returnValue($display_handler));
$executable->displayHandlers = $display_bag;
$response = $this->viewAjaxController->ajaxView($request);
$this->assertTrue($response instanceof ViewAjaxResponse);
$commands = $this->getCommands($response);
$this->assertEquals('viewsScrollTop', $commands[0]['command']);
$this->assertEquals('.view-dom-id-' . $dom_id, $commands[0]['selector']);
$this->assertViewResultCommand($response, 1);
}
/**
* Sets up a bunch of valid mocks like the view entity and executable.
*/
protected function setupValidMocks() {
$view = $this->getMockBuilder('Drupal\views\Entity\View')
->disableOriginalConstructor()
->getMock();
$this->viewStorage->expects($this->once())
->method('load')
->with('test_view')
->will($this->returnValue($view));
$executable = $this->getMockBuilder('Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$executable->expects($this->once())
->method('access')
->will($this->returnValue(TRUE));
$executable->expects($this->once())
->method('preview')
->will($this->returnValue(array('#markup' => 'View result')));
$this->executableFactory->expects($this->once())
->method('get')
->with($view)
->will($this->returnValue($executable));
return array($view, $executable);
}
/**
* Gets the commands entry from the response object.
*
* @param \Drupal\views\Ajax\ViewAjaxResponse $response
* The views ajax response object.
*
* @return mixed
* Returns the commands.
*/
protected function getCommands(ViewAjaxResponse $response) {
$reflection_property = new \ReflectionProperty('Drupal\views\Ajax\ViewAjaxResponse', 'commands');
$reflection_property->setAccessible(TRUE);
$commands = $reflection_property->getValue($response);
return $commands;
}
/**
* Ensures that the main view content command is added.
*
* @param \Drupal\views\Ajax\ViewAjaxResponse $response
* The response object.
* @param int $position
* The position where the view content command is expected.
*/
protected function assertViewResultCommand(ViewAjaxResponse $response, $position = 0) {
$commands = $this->getCommands($response);
$this->assertEquals('insert', $commands[$position]['command']);
$this->assertEquals('View result', $commands[$position]['data']);
}
}
/**
* Overrides ViewAjaxController::drupalRender to protect the parent method.
*/
class TestViewAjaxController extends ViewAjaxController {
// @todo Remove once drupal_render is converted to autoloadable code.
protected function drupalRender(array $elements) {
return isset($elements['#markup']) ? $elements['#markup'] : '';
}
}
}
namespace {
// @todo Remove once drupal_get_destination is converted to autoloadable code.
if (!function_exists('drupal_static')) {
function &drupal_static($key) {
return $key;
}
}
}
| gpl-2.0 |
FPLD/project0 | vendor/magento/framework/View/File.php | 2453 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\View;
use Magento\Framework\View\Design\ThemeInterface;
/**
* View file in the file system with context of its identity
*/
class File
{
/**
* File name
*
* @var string
*/
protected $filename;
/**
* Module
*
* @var string
*/
protected $module;
/**
* Theme
*
* @var ThemeInterface
*/
protected $theme;
/**
* Base flag
*
* @var string
*/
protected $isBase;
/**
* Identifier
*
* @var string
*/
protected $identifier;
/**
* Constructor
*
* @param string $filename
* @param string $module
* @param ThemeInterface $theme
* @param bool $isBase
*/
public function __construct($filename, $module, ThemeInterface $theme = null, $isBase = false)
{
$this->filename = $filename;
$this->module = $module;
$this->theme = $theme;
$this->isBase = $isBase;
}
/**
* Retrieve full filename
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* Retrieve name of a file without a directory path
*
* @return string
*/
public function getName()
{
return basename($this->filename);
}
/**
* Retrieve fully-qualified name of a module a file belongs to
*
* @return string
*/
public function getModule()
{
return $this->module;
}
/**
* Retrieve instance of a theme a file belongs to
*
* @return ThemeInterface|null
*/
public function getTheme()
{
return $this->theme;
}
/**
* Whether file is a base one
*
* @return bool
*/
public function isBase()
{
return $this->theme === null;
}
/**
* Calculate unique identifier for a view file
*
* @return string
*/
public function getFileIdentifier()
{
if (null === $this->identifier) {
$theme = $this->getTheme() ? ('|theme:' . $this->theme->getFullPath()) : '';
$this->identifier = ($this->isBase ? 'base' : '')
. $theme . '|module:' . $this->getModule() . '|file:' . $this->getName();
}
return $this->identifier;
}
}
| gpl-2.0 |
Gurgel100/gcc | gcc/selftest-rtl.h | 3235 | /* A self-testing framework, for use by -fself-test.
Copyright (C) 2016-2021 Free Software Foundation, Inc.
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation; either version 3, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#ifndef GCC_SELFTEST_RTL_H
#define GCC_SELFTEST_RTL_H
/* The selftest code should entirely disappear in a production
configuration, hence we guard all of it with #if CHECKING_P. */
#if CHECKING_P
class rtx_reuse_manager;
namespace selftest {
/* Verify that X is dumped as EXPECTED_DUMP, using compact mode.
Use LOC as the effective location when reporting errors. */
extern void
assert_rtl_dump_eq (const location &loc, const char *expected_dump, rtx x,
rtx_reuse_manager *reuse_manager);
/* Verify that RTX is dumped as EXPECTED_DUMP, using compact mode. */
#define ASSERT_RTL_DUMP_EQ(EXPECTED_DUMP, RTX) \
assert_rtl_dump_eq (SELFTEST_LOCATION, (EXPECTED_DUMP), (RTX), NULL)
/* As above, but using REUSE_MANAGER when dumping. */
#define ASSERT_RTL_DUMP_EQ_WITH_REUSE(EXPECTED_DUMP, RTX, REUSE_MANAGER) \
assert_rtl_dump_eq (SELFTEST_LOCATION, (EXPECTED_DUMP), (RTX), \
(REUSE_MANAGER))
#define ASSERT_RTX_EQ(EXPECTED, ACTUAL) \
SELFTEST_BEGIN_STMT \
const char *desc_ = "ASSERT_RTX_EQ (" #EXPECTED ", " #ACTUAL ")"; \
::selftest::assert_rtx_eq_at (SELFTEST_LOCATION, desc_, (EXPECTED), \
(ACTUAL)); \
SELFTEST_END_STMT
extern void assert_rtx_eq_at (const location &, const char *, rtx, rtx);
/* Evaluate rtx EXPECTED and ACTUAL and compare them with ==
(i.e. pointer equality), calling ::selftest::pass if they are
equal, aborting if they are non-equal. */
#define ASSERT_RTX_PTR_EQ(EXPECTED, ACTUAL) \
SELFTEST_BEGIN_STMT \
const char *desc_ = "ASSERT_RTX_PTR_EQ (" #EXPECTED ", " #ACTUAL ")"; \
::selftest::assert_rtx_ptr_eq_at (SELFTEST_LOCATION, desc_, (EXPECTED), \
(ACTUAL)); \
SELFTEST_END_STMT
/* Compare rtx EXPECTED and ACTUAL by pointer equality, calling
::selftest::pass if they are equal, aborting if they are non-equal.
LOC is the effective location of the assertion, MSG describes it. */
extern void assert_rtx_ptr_eq_at (const location &loc, const char *msg,
rtx expected, rtx actual);
/* A class for testing RTL function dumps. */
class rtl_dump_test
{
public:
/* Takes ownership of PATH. */
rtl_dump_test (const location &loc, char *path);
~rtl_dump_test ();
private:
char *m_path;
};
/* Get the insn with the given uid, or NULL if not found. */
extern rtx_insn *get_insn_by_uid (int uid);
extern void verify_three_block_rtl_cfg (function *fun);
} /* end of namespace selftest. */
#endif /* #if CHECKING_P */
#endif /* GCC_SELFTEST_RTL_H */
| gpl-2.0 |
dolorespark/android_kernel_hisense_m470bsa | drivers/video/backlight/backlight.c | 11044 | /*
* Backlight Lowlevel Control Abstraction
*
* Copyright (C) 2003,2004 Hewlett-Packard Company
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/backlight.h>
#include <linux/notifier.h>
#include <linux/ctype.h>
#include <linux/err.h>
#include <linux/fb.h>
#include <linux/slab.h>
#ifdef CONFIG_PMAC_BACKLIGHT
#include <asm/backlight.h>
#endif
static const char *const backlight_types[] = {
[BACKLIGHT_RAW] = "raw",
[BACKLIGHT_PLATFORM] = "platform",
[BACKLIGHT_FIRMWARE] = "firmware",
};
#if defined(CONFIG_FB) || (defined(CONFIG_FB_MODULE) && \
defined(CONFIG_BACKLIGHT_CLASS_DEVICE_MODULE))
/* This callback gets called when something important happens inside a
* framebuffer driver. We're looking if that important event is blanking,
* and if it is, we're switching backlight power as well ...
*/
static int fb_notifier_callback(struct notifier_block *self,
unsigned long event, void *data)
{
struct backlight_device *bd;
struct fb_event *evdata = data;
/* If we aren't interested in this event, skip it immediately ... */
if (event != FB_EVENT_BLANK && event != FB_EVENT_CONBLANK)
return 0;
bd = container_of(self, struct backlight_device, fb_notif);
mutex_lock(&bd->ops_lock);
if (bd->ops)
if (!bd->ops->check_fb ||
bd->ops->check_fb(bd, evdata->info)) {
bd->props.fb_blank = *(int *)evdata->data;
if (bd->props.fb_blank == FB_BLANK_UNBLANK)
bd->props.state &= ~BL_CORE_FBBLANK;
else
bd->props.state |= BL_CORE_FBBLANK;
backlight_update_status(bd);
}
mutex_unlock(&bd->ops_lock);
return 0;
}
static int backlight_register_fb(struct backlight_device *bd)
{
memset(&bd->fb_notif, 0, sizeof(bd->fb_notif));
bd->fb_notif.notifier_call = fb_notifier_callback;
return fb_register_client(&bd->fb_notif);
}
static void backlight_unregister_fb(struct backlight_device *bd)
{
fb_unregister_client(&bd->fb_notif);
}
#else
static inline int backlight_register_fb(struct backlight_device *bd)
{
return 0;
}
static inline void backlight_unregister_fb(struct backlight_device *bd)
{
}
#endif /* CONFIG_FB */
static void backlight_generate_event(struct backlight_device *bd,
enum backlight_update_reason reason)
{
char *envp[2];
switch (reason) {
case BACKLIGHT_UPDATE_SYSFS:
envp[0] = "SOURCE=sysfs";
break;
case BACKLIGHT_UPDATE_HOTKEY:
envp[0] = "SOURCE=hotkey";
break;
default:
envp[0] = "SOURCE=unknown";
break;
}
envp[1] = NULL;
kobject_uevent_env(&bd->dev.kobj, KOBJ_CHANGE, envp);
sysfs_notify(&bd->dev.kobj, NULL, "actual_brightness");
}
static ssize_t backlight_show_power(struct device *dev,
struct device_attribute *attr,char *buf)
{
struct backlight_device *bd = to_backlight_device(dev);
return sprintf(buf, "%d\n", bd->props.power);
}
static ssize_t backlight_store_power(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int rc;
struct backlight_device *bd = to_backlight_device(dev);
unsigned long power;
rc = strict_strtoul(buf, 0, &power);
if (rc)
return rc;
rc = -ENXIO;
mutex_lock(&bd->ops_lock);
if (bd->ops) {
pr_debug("backlight: set power to %lu\n", power);
if (bd->props.power != power) {
bd->props.power = power;
backlight_update_status(bd);
}
rc = count;
}
mutex_unlock(&bd->ops_lock);
return rc;
}
static ssize_t backlight_show_brightness(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct backlight_device *bd = to_backlight_device(dev);
return sprintf(buf, "%d\n", bd->props.brightness);
}
static ssize_t backlight_store_brightness(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int rc;
struct backlight_device *bd = to_backlight_device(dev);
unsigned long brightness;
rc = strict_strtoul(buf, 0, &brightness);
if (rc)
return rc;
rc = -ENXIO;
mutex_lock(&bd->ops_lock);
if (bd->ops) {
if (brightness > bd->props.max_brightness)
rc = -EINVAL;
else {
pr_debug("backlight: set brightness to %lu\n",
brightness);
bd->props.brightness = brightness;
backlight_update_status(bd);
rc = count;
}
}
mutex_unlock(&bd->ops_lock);
backlight_generate_event(bd, BACKLIGHT_UPDATE_SYSFS);
return rc;
}
static ssize_t backlight_show_type(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct backlight_device *bd = to_backlight_device(dev);
return sprintf(buf, "%s\n", backlight_types[bd->props.type]);
}
static ssize_t backlight_show_max_brightness(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct backlight_device *bd = to_backlight_device(dev);
return sprintf(buf, "%d\n", bd->props.max_brightness);
}
static ssize_t backlight_show_actual_brightness(struct device *dev,
struct device_attribute *attr, char *buf)
{
int rc = -ENXIO;
struct backlight_device *bd = to_backlight_device(dev);
mutex_lock(&bd->ops_lock);
if (bd->ops && bd->ops->get_brightness)
rc = sprintf(buf, "%d\n", bd->ops->get_brightness(bd));
mutex_unlock(&bd->ops_lock);
return rc;
}
//heqi add for test
/*
#include <linux/gpio.h>
static ssize_t backlight_store_gpio(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int rc;
struct backlight_device *bd = to_backlight_device(dev);
unsigned short val;
rc = strict_strtoul(buf, 0, &val);
if (rc)
return rc;
rc = -ENXIO;
mutex_lock(&bd->ops_lock);
if (val){
tegra_gpio_enable(56);
gpio_direction_output(56, 1);
}
else {
tegra_gpio_disable(56);
}
rc = count;
mutex_unlock(&bd->ops_lock);
return rc;
}
*/
static struct class *backlight_class;
static int backlight_suspend(struct device *dev, pm_message_t state)
{
struct backlight_device *bd = to_backlight_device(dev);
mutex_lock(&bd->ops_lock);
if (bd->ops && bd->ops->options & BL_CORE_SUSPENDRESUME) {
bd->props.state |= BL_CORE_SUSPENDED;
backlight_update_status(bd);
}
mutex_unlock(&bd->ops_lock);
return 0;
}
static int backlight_resume(struct device *dev)
{
struct backlight_device *bd = to_backlight_device(dev);
mutex_lock(&bd->ops_lock);
if (bd->ops && bd->ops->options & BL_CORE_SUSPENDRESUME) {
bd->props.state &= ~BL_CORE_SUSPENDED;
backlight_update_status(bd);
}
mutex_unlock(&bd->ops_lock);
return 0;
}
static void bl_device_release(struct device *dev)
{
struct backlight_device *bd = to_backlight_device(dev);
kfree(bd);
}
static struct device_attribute bl_device_attributes[] = {
__ATTR(bl_power, 0644, backlight_show_power, backlight_store_power),
__ATTR(brightness, 0644, backlight_show_brightness,
backlight_store_brightness),
__ATTR(actual_brightness, 0444, backlight_show_actual_brightness,
NULL),
__ATTR(max_brightness, 0444, backlight_show_max_brightness, NULL),
__ATTR(type, 0444, backlight_show_type, NULL),
//__ATTR(gpio, 0644, NULL, backlight_store_gpio),
__ATTR_NULL,
};
/**
* backlight_force_update - tell the backlight subsystem that hardware state
* has changed
* @bd: the backlight device to update
*
* Updates the internal state of the backlight in response to a hardware event,
* and generate a uevent to notify userspace
*/
void backlight_force_update(struct backlight_device *bd,
enum backlight_update_reason reason)
{
mutex_lock(&bd->ops_lock);
if (bd->ops && bd->ops->get_brightness)
bd->props.brightness = bd->ops->get_brightness(bd);
mutex_unlock(&bd->ops_lock);
backlight_generate_event(bd, reason);
}
EXPORT_SYMBOL(backlight_force_update);
/**
* backlight_device_register - create and register a new object of
* backlight_device class.
* @name: the name of the new object(must be the same as the name of the
* respective framebuffer device).
* @parent: a pointer to the parent device
* @devdata: an optional pointer to be stored for private driver use. The
* methods may retrieve it by using bl_get_data(bd).
* @ops: the backlight operations structure.
*
* Creates and registers new backlight device. Returns either an
* ERR_PTR() or a pointer to the newly allocated device.
*/
struct backlight_device *backlight_device_register(const char *name,
struct device *parent, void *devdata, const struct backlight_ops *ops,
const struct backlight_properties *props)
{
struct backlight_device *new_bd;
int rc;
pr_debug("backlight_device_register: name=%s\n", name);
new_bd = kzalloc(sizeof(struct backlight_device), GFP_KERNEL);
if (!new_bd)
return ERR_PTR(-ENOMEM);
mutex_init(&new_bd->update_lock);
mutex_init(&new_bd->ops_lock);
new_bd->dev.class = backlight_class;
new_bd->dev.parent = parent;
new_bd->dev.release = bl_device_release;
dev_set_name(&new_bd->dev, name);
dev_set_drvdata(&new_bd->dev, devdata);
/* Set default properties */
if (props) {
memcpy(&new_bd->props, props,
sizeof(struct backlight_properties));
if (props->type <= 0 || props->type >= BACKLIGHT_TYPE_MAX) {
WARN(1, "%s: invalid backlight type", name);
new_bd->props.type = BACKLIGHT_RAW;
}
} else {
new_bd->props.type = BACKLIGHT_RAW;
}
rc = device_register(&new_bd->dev);
if (rc) {
kfree(new_bd);
return ERR_PTR(rc);
}
rc = backlight_register_fb(new_bd);
if (rc) {
device_unregister(&new_bd->dev);
return ERR_PTR(rc);
}
new_bd->ops = ops;
#ifdef CONFIG_PMAC_BACKLIGHT
mutex_lock(&pmac_backlight_mutex);
if (!pmac_backlight)
pmac_backlight = new_bd;
mutex_unlock(&pmac_backlight_mutex);
#endif
return new_bd;
}
EXPORT_SYMBOL(backlight_device_register);
/**
* backlight_device_unregister - unregisters a backlight device object.
* @bd: the backlight device object to be unregistered and freed.
*
* Unregisters a previously registered via backlight_device_register object.
*/
void backlight_device_unregister(struct backlight_device *bd)
{
if (!bd)
return;
#ifdef CONFIG_PMAC_BACKLIGHT
mutex_lock(&pmac_backlight_mutex);
if (pmac_backlight == bd)
pmac_backlight = NULL;
mutex_unlock(&pmac_backlight_mutex);
#endif
mutex_lock(&bd->ops_lock);
bd->ops = NULL;
mutex_unlock(&bd->ops_lock);
backlight_unregister_fb(bd);
device_unregister(&bd->dev);
}
EXPORT_SYMBOL(backlight_device_unregister);
static void __exit backlight_class_exit(void)
{
class_destroy(backlight_class);
}
static int __init backlight_class_init(void)
{
backlight_class = class_create(THIS_MODULE, "backlight");
if (IS_ERR(backlight_class)) {
printk(KERN_WARNING "Unable to create backlight class; errno = %ld\n",
PTR_ERR(backlight_class));
return PTR_ERR(backlight_class);
}
backlight_class->dev_attrs = bl_device_attributes;
backlight_class->suspend = backlight_suspend;
backlight_class->resume = backlight_resume;
return 0;
}
/*
* if this is compiled into the kernel, we need to ensure that the
* class is registered before users of the class try to register lcd's
*/
postcore_initcall(backlight_class_init);
module_exit(backlight_class_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jamey Hicks <[email protected]>, Andrew Zabolotny <[email protected]>");
MODULE_DESCRIPTION("Backlight Lowlevel Control Abstraction");
| gpl-2.0 |
brharp/hjckrrh | profiles/ug/modules/ug/ug_demo/data/images/public/js/js_GWG8O3mHf8xRnabCEJIqQCLluQ1UIMRNp4CIToqq9Ow.js | 17330 | (function ($) {
/**
* Attaches double-click behavior to toggle full path of Krumo elements.
*/
Drupal.behaviors.devel = {
attach: function (context, settings) {
// Add hint to footnote
$('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>');
var krumo_name = [];
var krumo_type = [];
function krumo_traverse(el) {
krumo_name.push($(el).html());
krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]);
if ($(el).closest('.krumo-nest').length > 0) {
krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name'));
}
}
$('.krumo-child > div:first-child', context).dblclick(
function(e) {
if ($(this).find('> .krumo-php-path').length > 0) {
// Remove path if shown.
$(this).find('> .krumo-php-path').remove();
}
else {
// Get elements.
krumo_traverse($(this).find('> a.krumo-name'));
// Create path.
var krumo_path_string = '';
for (var i = krumo_name.length - 1; i >= 0; --i) {
// Start element.
if ((krumo_name.length - 1) == i)
krumo_path_string += '$' + krumo_name[i];
if (typeof krumo_name[(i-1)] !== 'undefined') {
if (krumo_type[i] == 'Array') {
krumo_path_string += "[";
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += krumo_name[(i-1)];
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += "]";
}
if (krumo_type[i] == 'Object')
krumo_path_string += '->' + krumo_name[(i-1)];
}
}
$(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>');
// Reset arrays.
krumo_name = [];
krumo_type = [];
}
}
);
}
};
})(jQuery);
;
(function ($) {
/**
* Attach the machine-readable name form element behavior.
*/
Drupal.behaviors.machineName = {
/**
* Attaches the behavior.
*
* @param settings.machineName
* A list of elements to process, keyed by the HTML ID of the form element
* containing the human-readable value. Each element is an object defining
* the following properties:
* - target: The HTML ID of the machine name form element.
* - suffix: The HTML ID of a container to show the machine name preview in
* (usually a field suffix after the human-readable name form element).
* - label: The label to show for the machine name preview.
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - standalone: Whether the preview should stay in its own element rather
* than the suffix of the source element.
* - field_prefix: The #field_prefix of the form element.
* - field_suffix: The #field_suffix of the form element.
*/
attach: function (context, settings) {
var self = this;
$.each(settings.machineName, function (source_id, options) {
var $source = $(source_id, context).addClass('machine-name-source');
var $target = $(options.target, context).addClass('machine-name-target');
var $suffix = $(options.suffix, context);
var $wrapper = $target.closest('.form-item');
// All elements have to exist.
if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) {
return;
}
// Skip processing upon a form validation error on the machine name.
if ($target.hasClass('error')) {
return;
}
// Figure out the maximum length for the machine name.
options.maxlength = $target.attr('maxlength');
// Hide the form item container of the machine name form element.
$wrapper.hide();
// Determine the initial machine name value. Unless the machine name form
// element is disabled or not empty, the initial default value is based on
// the human-readable form element value.
if ($target.is(':disabled') || $target.val() != '') {
var machine = $target.val();
}
else {
var machine = self.transliterate($source.val(), options);
}
// Append the machine name preview to the source field.
var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>');
$suffix.empty();
if (options.label) {
$suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>');
}
$suffix.append(' ').append($preview);
// If the machine name cannot be edited, stop further processing.
if ($target.is(':disabled')) {
return;
}
// If it is editable, append an edit link.
var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>')
.click(function () {
$wrapper.show();
$target.focus();
$suffix.hide();
$source.unbind('.machineName');
return false;
});
$suffix.append(' ').append($link);
// Preview the machine name in realtime when the human-readable name
// changes, but only if there is no machine name yet; i.e., only upon
// initial creation, not when editing.
if ($target.val() == '') {
$source.bind('keyup.machineName change.machineName input.machineName', function () {
machine = self.transliterate($(this).val(), options);
// Set the machine name to the transliterated value.
if (machine != '') {
if (machine != options.replace) {
$target.val(machine);
$preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix);
}
$suffix.show();
}
else {
$suffix.hide();
$target.val(machine);
$preview.empty();
}
});
// Initialize machine name preview.
$source.keyup();
}
});
},
/**
* Transliterate a human-readable name to a machine name.
*
* @param source
* A string to transliterate.
* @param settings
* The machine name settings for the corresponding field, containing:
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - maxlength: The maximum length of the machine name.
*
* @return
* The transliterated source string.
*/
transliterate: function (source, settings) {
var rx = new RegExp(settings.replace_pattern, 'g');
return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength);
}
};
})(jQuery);
;
(function ($) {
Drupal.behaviors.textarea = {
attach: function (context, settings) {
$('.form-textarea-wrapper.resizable', context).once('textarea', function () {
var staticOffset = null;
var textarea = $(this).addClass('resizable-textarea').find('textarea');
var grippie = $('<div class="grippie"></div>').mousedown(startDrag);
grippie.insertAfter(textarea);
function startDrag(e) {
staticOffset = textarea.height() - e.pageY;
textarea.css('opacity', 0.25);
$(document).mousemove(performDrag).mouseup(endDrag);
return false;
}
function performDrag(e) {
textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
return false;
}
function endDrag(e) {
$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
textarea.css('opacity', 1);
}
});
}
};
})(jQuery);
;
(function ($) {
Drupal.toolbar = Drupal.toolbar || {};
/**
* Attach toggling behavior and notify the overlay of the toolbar.
*/
Drupal.behaviors.toolbar = {
attach: function(context) {
// Set the initial state of the toolbar.
$('#toolbar', context).once('toolbar', Drupal.toolbar.init);
// Toggling toolbar drawer.
$('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) {
Drupal.toolbar.toggle();
// Allow resize event handlers to recalculate sizes/positions.
$(window).triggerHandler('resize');
return false;
});
}
};
/**
* Retrieve last saved cookie settings and set up the initial toolbar state.
*/
Drupal.toolbar.init = function() {
// Retrieve the collapsed status from a stored cookie.
var collapsed = $.cookie('Drupal.toolbar.collapsed');
// Expand or collapse the toolbar based on the cookie value.
if (collapsed == 1) {
Drupal.toolbar.collapse();
}
else {
Drupal.toolbar.expand();
}
};
/**
* Collapse the toolbar.
*/
Drupal.toolbar.collapse = function() {
var toggle_text = Drupal.t('Show shortcuts');
$('#toolbar div.toolbar-drawer').addClass('collapsed');
$('#toolbar a.toggle')
.removeClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
1,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Expand the toolbar.
*/
Drupal.toolbar.expand = function() {
var toggle_text = Drupal.t('Hide shortcuts');
$('#toolbar div.toolbar-drawer').removeClass('collapsed');
$('#toolbar a.toggle')
.addClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
0,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Toggle the toolbar.
*/
Drupal.toolbar.toggle = function() {
if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) {
Drupal.toolbar.expand();
}
else {
Drupal.toolbar.collapse();
}
};
Drupal.toolbar.height = function() {
var $toolbar = $('#toolbar');
var height = $toolbar.outerHeight();
// In modern browsers (including IE9), when box-shadow is defined, use the
// normal height.
var cssBoxShadowValue = $toolbar.css('box-shadow');
var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
// In IE8 and below, we use the shadow filter to apply box-shadow styles to
// the toolbar. It adds some extra height that we need to remove.
if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) {
height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength;
}
return height;
};
})(jQuery);
;
/**
* @file
* A JavaScript file for the theme.
* This file should be used as a template for your other js files.
* It defines a drupal behavior the "Drupal way".
*
*/
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
'use strict';
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.hideSubmitBlockit = {
attach: function(context) {
var timeoutId = null;
$('form', context).once('hideSubmitButton', function () {
var $form = $(this);
// Bind to input elements.
if (Drupal.settings.hide_submit.hide_submit_method === 'indicator') {
// Replace input elements with buttons.
$('input.form-submit', $form).each(function(index, el) {
var attrs = {};
$.each($(this)[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
$(this).replaceWith(function() {
return $("<button/>", attrs).append($(this).attr('value'));
});
});
// Add needed attributes to the submit buttons.
$('button.form-submit', $form).each(function(index, el) {
$(this).addClass('ladda-button button').attr({
'data-style': Drupal.settings.hide_submit.hide_submit_indicator_style,
'data-spinner-color': Drupal.settings.hide_submit.hide_submit_spinner_color,
'data-spinner-lines': Drupal.settings.hide_submit.hide_submit_spinner_lines
});
});
Ladda.bind('.ladda-button', $form, {
timeout: Drupal.settings.hide_submit.hide_submit_reset_time
});
}
else {
$('input.form-submit, button.form-submit', $form).click(function (e) {
var el = $(this);
el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
return true;
});
}
// Bind to form submit.
$('form', context).submit(function (e) {
var $inp;
if (!e.isPropagationStopped()) {
if (Drupal.settings.hide_submit.hide_submit_method === 'disable') {
$('input.form-submit, button.form-submit', $form).attr('disabled', 'disabled').each(function (i) {
var $button = $(this);
if (Drupal.settings.hide_submit.hide_submit_css) {
$button.addClass(Drupal.settings.hide_submit.hide_submit_css);
}
if (Drupal.settings.hide_submit.hide_submit_abtext) {
$button.val($button.val() + ' ' + Drupal.settings.hide_submit.hide_submit_abtext);
}
$inp = $button;
});
if ($inp && Drupal.settings.hide_submit.hide_submit_atext) {
$inp.after('<span class="hide-submit-text">' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_atext) + '</span>');
}
}
else if (Drupal.settings.hide_submit.hide_submit_method !== 'indicator'){
var pdiv = '<div class="hide-submit-text' + (Drupal.settings.hide_submit.hide_submit_hide_css ? ' ' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css) + '"' : '') + '>' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_text) + '</div>';
if (Drupal.settings.hide_submit.hide_submit_hide_fx) {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).fadeOut(100).eq(0).after(pdiv);
$('input.form-submit, button.form-submit', $form).next().fadeIn(100);
}
else {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).hide().eq(0).after(pdiv);
}
}
// Add a timeout to reset the buttons (if needed).
if (Drupal.settings.hide_submit.hide_submit_reset_time) {
timeoutId = window.setTimeout(function() {
hideSubmitResetButtons(null, $form);
}, Drupal.settings.hide_submit.hide_submit_reset_time);
}
}
return true;
});
});
// Bind to clientsideValidationFormHasErrors to support clientside validation.
// $(document).bind('clientsideValidationFormHasErrors', function(event, form) {
//hideSubmitResetButtons(event, form.form);
// });
// Reset all buttons.
function hideSubmitResetButtons(event, form) {
// Clear timer.
window.clearTimeout(timeoutId);
timeoutId = null;
switch (Drupal.settings.hide_submit.hide_submit_method) {
case 'disable':
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.removeAttr('disabled');
});
$('.hide-submit-text', form).remove();
break;
case 'indicator':
Ladda.stopAll();
break;
default:
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).stop()
.removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.show();
});
$('.hide-submit-text', form).remove();
}
}
}
};
})(jQuery, Drupal, window, this.document);
;
| gpl-2.0 |
dengbiao/tc_kernel_linux | arch/mips/math-emu/cp1emu.c | 29606 | /*
* cp1emu.c: a MIPS coprocessor 1 (fpu) instruction emulator
*
* MIPS floating point support
* Copyright (C) 1994-2000 Algorithmics Ltd.
*
* Kevin D. Kissell, [email protected] and Carsten Langgaard, [email protected]
* Copyright (C) 2000 MIPS Technologies, Inc.
*
* This program is free software; you can distribute 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 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.
*
* A complete emulator for MIPS coprocessor 1 instructions. This is
* required for #float(switch) or #float(trap), where it catches all
* COP1 instructions via the "CoProcessor Unusable" exception.
*
* More surprisingly it is also required for #float(ieee), to help out
* the hardware fpu at the boundaries of the IEEE-754 representation
* (denormalised values, infinities, underflow, etc). It is made
* quite nasty because emulation of some non-COP1 instructions is
* required, e.g. in branch delay slots.
*
* Note if you know that you won't have an fpu, then you'll get much
* better performance by compiling with -msoft-float!
*/
#include <linux/sched.h>
#include <linux/module.h>
#include <linux/debugfs.h>
#include <asm/inst.h>
#include <asm/bootinfo.h>
#include <asm/processor.h>
#include <asm/ptrace.h>
#include <asm/signal.h>
#include <asm/mipsregs.h>
#include <asm/fpu_emulator.h>
#include <asm/uaccess.h>
#include <asm/branch.h>
#include "ieee754.h"
/* Strap kernel emulator for full MIPS IV emulation */
#ifdef __mips
#undef __mips
#endif
#define __mips 4
/* Function which emulates a floating point instruction. */
static int fpu_emu(struct pt_regs *, struct mips_fpu_struct *,
mips_instruction);
#if __mips >= 4 && __mips != 32
static int fpux_emu(struct pt_regs *,
struct mips_fpu_struct *, mips_instruction);
#endif
/* Further private data for which no space exists in mips_fpu_struct */
#ifdef CONFIG_DEBUG_FS
DEFINE_PER_CPU(struct mips_fpu_emulator_stats, fpuemustats);
#endif
/* Control registers */
#define FPCREG_RID 0 /* $0 = revision id */
#define FPCREG_CSR 31 /* $31 = csr */
/* Determine rounding mode from the RM bits of the FCSR */
#define modeindex(v) ((v) & FPU_CSR_RM)
/* Convert Mips rounding mode (0..3) to IEEE library modes. */
static const unsigned char ieee_rm[4] = {
[FPU_CSR_RN] = IEEE754_RN,
[FPU_CSR_RZ] = IEEE754_RZ,
[FPU_CSR_RU] = IEEE754_RU,
[FPU_CSR_RD] = IEEE754_RD,
};
/* Convert IEEE library modes to Mips rounding mode (0..3). */
static const unsigned char mips_rm[4] = {
[IEEE754_RN] = FPU_CSR_RN,
[IEEE754_RZ] = FPU_CSR_RZ,
[IEEE754_RD] = FPU_CSR_RD,
[IEEE754_RU] = FPU_CSR_RU,
};
#if __mips >= 4
/* convert condition code register number to csr bit */
static const unsigned int fpucondbit[8] = {
FPU_CSR_COND0,
FPU_CSR_COND1,
FPU_CSR_COND2,
FPU_CSR_COND3,
FPU_CSR_COND4,
FPU_CSR_COND5,
FPU_CSR_COND6,
FPU_CSR_COND7
};
#endif
/*
* Redundant with logic already in kernel/branch.c,
* embedded in compute_return_epc. At some point,
* a single subroutine should be used across both
* modules.
*/
static int isBranchInstr(mips_instruction * i)
{
switch (MIPSInst_OPCODE(*i)) {
case spec_op:
switch (MIPSInst_FUNC(*i)) {
case jalr_op:
case jr_op:
return 1;
}
break;
case bcond_op:
switch (MIPSInst_RT(*i)) {
case bltz_op:
case bgez_op:
case bltzl_op:
case bgezl_op:
case bltzal_op:
case bgezal_op:
case bltzall_op:
case bgezall_op:
return 1;
}
break;
case j_op:
case jal_op:
case jalx_op:
case beq_op:
case bne_op:
case blez_op:
case bgtz_op:
case beql_op:
case bnel_op:
case blezl_op:
case bgtzl_op:
return 1;
case cop0_op:
case cop1_op:
case cop2_op:
case cop1x_op:
if (MIPSInst_RS(*i) == bc_op)
return 1;
break;
}
return 0;
}
/*
* In the Linux kernel, we support selection of FPR format on the
* basis of the Status.FR bit. If an FPU is not present, the FR bit
* is hardwired to zero, which would imply a 32-bit FPU even for
* 64-bit CPUs. For 64-bit kernels with no FPU we use TIF_32BIT_REGS
* as a proxy for the FR bit so that a 64-bit FPU is emulated. In any
* case, for a 32-bit kernel which uses the O32 MIPS ABI, only the
* even FPRs are used (Status.FR = 0).
*/
static inline int cop1_64bit(struct pt_regs *xcp)
{
if (cpu_has_fpu)
return xcp->cp0_status & ST0_FR;
#ifdef CONFIG_64BIT
return !test_thread_flag(TIF_32BIT_REGS);
#else
return 0;
#endif
}
#define SIFROMREG(si, x) ((si) = cop1_64bit(xcp) || !(x & 1) ? \
(int)ctx->fpr[x] : (int)(ctx->fpr[x & ~1] >> 32))
#define SITOREG(si, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = \
cop1_64bit(xcp) || !(x & 1) ? \
ctx->fpr[x & ~1] >> 32 << 32 | (u32)(si) : \
ctx->fpr[x & ~1] << 32 >> 32 | (u64)(si) << 32)
#define DIFROMREG(di, x) ((di) = ctx->fpr[x & ~(cop1_64bit(xcp) == 0)])
#define DITOREG(di, x) (ctx->fpr[x & ~(cop1_64bit(xcp) == 0)] = (di))
#define SPFROMREG(sp, x) SIFROMREG((sp).bits, x)
#define SPTOREG(sp, x) SITOREG((sp).bits, x)
#define DPFROMREG(dp, x) DIFROMREG((dp).bits, x)
#define DPTOREG(dp, x) DITOREG((dp).bits, x)
/*
* Emulate the single floating point instruction pointed at by EPC.
* Two instructions if the instruction is in a branch delay slot.
*/
static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx)
{
mips_instruction ir;
unsigned long emulpc, contpc;
unsigned int cond;
if (get_user(ir, (mips_instruction __user *) xcp->cp0_epc)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
/* XXX NEC Vr54xx bug workaround */
if ((xcp->cp0_cause & CAUSEF_BD) && !isBranchInstr(&ir))
xcp->cp0_cause &= ~CAUSEF_BD;
if (xcp->cp0_cause & CAUSEF_BD) {
/*
* The instruction to be emulated is in a branch delay slot
* which means that we have to emulate the branch instruction
* BEFORE we do the cop1 instruction.
*
* This branch could be a COP1 branch, but in that case we
* would have had a trap for that instruction, and would not
* come through this route.
*
* Linux MIPS branch emulator operates on context, updating the
* cp0_epc.
*/
emulpc = xcp->cp0_epc + 4; /* Snapshot emulation target */
if (__compute_return_epc(xcp)) {
#ifdef CP1DBG
printk("failed to emulate branch at %p\n",
(void *) (xcp->cp0_epc));
#endif
return SIGILL;
}
if (get_user(ir, (mips_instruction __user *) emulpc)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
/* __compute_return_epc() will have updated cp0_epc */
contpc = xcp->cp0_epc;
/* In order not to confuse ptrace() et al, tweak context */
xcp->cp0_epc = emulpc - 4;
} else {
emulpc = xcp->cp0_epc;
contpc = xcp->cp0_epc + 4;
}
emul:
MIPS_FPU_EMU_INC_STATS(emulated);
switch (MIPSInst_OPCODE(ir)) {
case ldc1_op:{
u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u64 val;
MIPS_FPU_EMU_INC_STATS(loads);
if (get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
DITOREG(val, MIPSInst_RT(ir));
break;
}
case sdc1_op:{
u64 __user *va = (u64 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u64 val;
MIPS_FPU_EMU_INC_STATS(stores);
DIFROMREG(val, MIPSInst_RT(ir));
if (put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
break;
}
case lwc1_op:{
u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u32 val;
MIPS_FPU_EMU_INC_STATS(loads);
if (get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
SITOREG(val, MIPSInst_RT(ir));
break;
}
case swc1_op:{
u32 __user *va = (u32 __user *) (xcp->regs[MIPSInst_RS(ir)] +
MIPSInst_SIMM(ir));
u32 val;
MIPS_FPU_EMU_INC_STATS(stores);
SIFROMREG(val, MIPSInst_RT(ir));
if (put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
break;
}
case cop1_op:
switch (MIPSInst_RS(ir)) {
#if defined(__mips64)
case dmfc_op:
/* copregister fs -> gpr[rt] */
if (MIPSInst_RT(ir) != 0) {
DIFROMREG(xcp->regs[MIPSInst_RT(ir)],
MIPSInst_RD(ir));
}
break;
case dmtc_op:
/* copregister fs <- rt */
DITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir));
break;
#endif
case mfc_op:
/* copregister rd -> gpr[rt] */
if (MIPSInst_RT(ir) != 0) {
SIFROMREG(xcp->regs[MIPSInst_RT(ir)],
MIPSInst_RD(ir));
}
break;
case mtc_op:
/* copregister rd <- rt */
SITOREG(xcp->regs[MIPSInst_RT(ir)], MIPSInst_RD(ir));
break;
case cfc_op:{
/* cop control register rd -> gpr[rt] */
u32 value;
if (MIPSInst_RD(ir) == FPCREG_CSR) {
value = ctx->fcr31;
value = (value & ~FPU_CSR_RM) |
mips_rm[modeindex(value)];
#ifdef CSRTRACE
printk("%p gpr[%d]<-csr=%08x\n",
(void *) (xcp->cp0_epc),
MIPSInst_RT(ir), value);
#endif
}
else if (MIPSInst_RD(ir) == FPCREG_RID)
value = 0;
else
value = 0;
if (MIPSInst_RT(ir))
xcp->regs[MIPSInst_RT(ir)] = value;
break;
}
case ctc_op:{
/* copregister rd <- rt */
u32 value;
if (MIPSInst_RT(ir) == 0)
value = 0;
else
value = xcp->regs[MIPSInst_RT(ir)];
/* we only have one writable control reg
*/
if (MIPSInst_RD(ir) == FPCREG_CSR) {
#ifdef CSRTRACE
printk("%p gpr[%d]->csr=%08x\n",
(void *) (xcp->cp0_epc),
MIPSInst_RT(ir), value);
#endif
/*
* Don't write reserved bits,
* and convert to ieee library modes
*/
ctx->fcr31 = (value &
~(FPU_CSR_RSVD | FPU_CSR_RM)) |
ieee_rm[modeindex(value)];
}
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
return SIGFPE;
}
break;
}
case bc_op:{
int likely = 0;
if (xcp->cp0_cause & CAUSEF_BD)
return SIGILL;
#if __mips >= 4
cond = ctx->fcr31 & fpucondbit[MIPSInst_RT(ir) >> 2];
#else
cond = ctx->fcr31 & FPU_CSR_COND;
#endif
switch (MIPSInst_RT(ir) & 3) {
case bcfl_op:
likely = 1;
case bcf_op:
cond = !cond;
break;
case bctl_op:
likely = 1;
case bct_op:
break;
default:
/* thats an illegal instruction */
return SIGILL;
}
xcp->cp0_cause |= CAUSEF_BD;
if (cond) {
/* branch taken: emulate dslot
* instruction
*/
xcp->cp0_epc += 4;
contpc = (xcp->cp0_epc +
(MIPSInst_SIMM(ir) << 2));
if (get_user(ir,
(mips_instruction __user *) xcp->cp0_epc)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
switch (MIPSInst_OPCODE(ir)) {
case lwc1_op:
case swc1_op:
#if (__mips >= 2 || defined(__mips64))
case ldc1_op:
case sdc1_op:
#endif
case cop1_op:
#if __mips >= 4 && __mips != 32
case cop1x_op:
#endif
/* its one of ours */
goto emul;
#if __mips >= 4
case spec_op:
if (MIPSInst_FUNC(ir) == movc_op)
goto emul;
break;
#endif
}
/*
* Single step the non-cp1
* instruction in the dslot
*/
return mips_dsemul(xcp, ir, contpc);
}
else {
/* branch not taken */
if (likely) {
/*
* branch likely nullifies
* dslot if not taken
*/
xcp->cp0_epc += 4;
contpc += 4;
/*
* else continue & execute
* dslot as normal insn
*/
}
}
break;
}
default:
if (!(MIPSInst_RS(ir) & 0x10))
return SIGILL;
{
int sig;
/* a real fpu computation instruction */
if ((sig = fpu_emu(xcp, ctx, ir)))
return sig;
}
}
break;
#if __mips >= 4 && __mips != 32
case cop1x_op:{
int sig;
if ((sig = fpux_emu(xcp, ctx, ir)))
return sig;
break;
}
#endif
#if __mips >= 4
case spec_op:
if (MIPSInst_FUNC(ir) != movc_op)
return SIGILL;
cond = fpucondbit[MIPSInst_RT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) == ((MIPSInst_RT(ir) & 1) != 0))
xcp->regs[MIPSInst_RD(ir)] =
xcp->regs[MIPSInst_RS(ir)];
break;
#endif
default:
return SIGILL;
}
/* we did it !! */
xcp->cp0_epc = contpc;
xcp->cp0_cause &= ~CAUSEF_BD;
return 0;
}
/*
* Conversion table from MIPS compare ops 48-63
* cond = ieee754dp_cmp(x,y,IEEE754_UN,sig);
*/
static const unsigned char cmptab[8] = {
0, /* cmp_0 (sig) cmp_sf */
IEEE754_CUN, /* cmp_un (sig) cmp_ngle */
IEEE754_CEQ, /* cmp_eq (sig) cmp_seq */
IEEE754_CEQ | IEEE754_CUN, /* cmp_ueq (sig) cmp_ngl */
IEEE754_CLT, /* cmp_olt (sig) cmp_lt */
IEEE754_CLT | IEEE754_CUN, /* cmp_ult (sig) cmp_nge */
IEEE754_CLT | IEEE754_CEQ, /* cmp_ole (sig) cmp_le */
IEEE754_CLT | IEEE754_CEQ | IEEE754_CUN, /* cmp_ule (sig) cmp_ngt */
};
#if __mips >= 4 && __mips != 32
/*
* Additional MIPS4 instructions
*/
#define DEF3OP(name, p, f1, f2, f3) \
static ieee754##p fpemu_##p##_##name(ieee754##p r, ieee754##p s, \
ieee754##p t) \
{ \
struct _ieee754_csr ieee754_csr_save; \
s = f1(s, t); \
ieee754_csr_save = ieee754_csr; \
s = f2(s, r); \
ieee754_csr_save.cx |= ieee754_csr.cx; \
ieee754_csr_save.sx |= ieee754_csr.sx; \
s = f3(s); \
ieee754_csr.cx |= ieee754_csr_save.cx; \
ieee754_csr.sx |= ieee754_csr_save.sx; \
return s; \
}
static ieee754dp fpemu_dp_recip(ieee754dp d)
{
return ieee754dp_div(ieee754dp_one(0), d);
}
static ieee754dp fpemu_dp_rsqrt(ieee754dp d)
{
return ieee754dp_div(ieee754dp_one(0), ieee754dp_sqrt(d));
}
static ieee754sp fpemu_sp_recip(ieee754sp s)
{
return ieee754sp_div(ieee754sp_one(0), s);
}
static ieee754sp fpemu_sp_rsqrt(ieee754sp s)
{
return ieee754sp_div(ieee754sp_one(0), ieee754sp_sqrt(s));
}
DEF3OP(madd, sp, ieee754sp_mul, ieee754sp_add, );
DEF3OP(msub, sp, ieee754sp_mul, ieee754sp_sub, );
DEF3OP(nmadd, sp, ieee754sp_mul, ieee754sp_add, ieee754sp_neg);
DEF3OP(nmsub, sp, ieee754sp_mul, ieee754sp_sub, ieee754sp_neg);
DEF3OP(madd, dp, ieee754dp_mul, ieee754dp_add, );
DEF3OP(msub, dp, ieee754dp_mul, ieee754dp_sub, );
DEF3OP(nmadd, dp, ieee754dp_mul, ieee754dp_add, ieee754dp_neg);
DEF3OP(nmsub, dp, ieee754dp_mul, ieee754dp_sub, ieee754dp_neg);
static int fpux_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
mips_instruction ir)
{
unsigned rcsr = 0; /* resulting csr */
MIPS_FPU_EMU_INC_STATS(cp1xops);
switch (MIPSInst_FMA_FFMT(ir)) {
case s_fmt:{ /* 0 */
ieee754sp(*handler) (ieee754sp, ieee754sp, ieee754sp);
ieee754sp fd, fr, fs, ft;
u32 __user *va;
u32 val;
switch (MIPSInst_FUNC(ir)) {
case lwxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(loads);
if (get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
SITOREG(val, MIPSInst_FD(ir));
break;
case swxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(stores);
SIFROMREG(val, MIPSInst_FS(ir));
if (put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
break;
case madd_s_op:
handler = fpemu_sp_madd;
goto scoptop;
case msub_s_op:
handler = fpemu_sp_msub;
goto scoptop;
case nmadd_s_op:
handler = fpemu_sp_nmadd;
goto scoptop;
case nmsub_s_op:
handler = fpemu_sp_nmsub;
goto scoptop;
scoptop:
SPFROMREG(fr, MIPSInst_FR(ir));
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
fd = (*handler) (fr, fs, ft);
SPTOREG(fd, MIPSInst_FD(ir));
copcsr:
if (ieee754_cxtest(IEEE754_INEXACT))
rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S;
if (ieee754_cxtest(IEEE754_UNDERFLOW))
rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S;
if (ieee754_cxtest(IEEE754_OVERFLOW))
rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S;
if (ieee754_cxtest(IEEE754_INVALID_OPERATION))
rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S;
ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr;
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
/*printk ("SIGFPE: fpu csr = %08x\n",
ctx->fcr31); */
return SIGFPE;
}
break;
default:
return SIGILL;
}
break;
}
case d_fmt:{ /* 1 */
ieee754dp(*handler) (ieee754dp, ieee754dp, ieee754dp);
ieee754dp fd, fr, fs, ft;
u64 __user *va;
u64 val;
switch (MIPSInst_FUNC(ir)) {
case ldxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(loads);
if (get_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
DITOREG(val, MIPSInst_FD(ir));
break;
case sdxc1_op:
va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] +
xcp->regs[MIPSInst_FT(ir)]);
MIPS_FPU_EMU_INC_STATS(stores);
DIFROMREG(val, MIPSInst_FS(ir));
if (put_user(val, va)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
break;
case madd_d_op:
handler = fpemu_dp_madd;
goto dcoptop;
case msub_d_op:
handler = fpemu_dp_msub;
goto dcoptop;
case nmadd_d_op:
handler = fpemu_dp_nmadd;
goto dcoptop;
case nmsub_d_op:
handler = fpemu_dp_nmsub;
goto dcoptop;
dcoptop:
DPFROMREG(fr, MIPSInst_FR(ir));
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
fd = (*handler) (fr, fs, ft);
DPTOREG(fd, MIPSInst_FD(ir));
goto copcsr;
default:
return SIGILL;
}
break;
}
case 0x7: /* 7 */
if (MIPSInst_FUNC(ir) != pfetch_op) {
return SIGILL;
}
/* ignore prefx operation */
break;
default:
return SIGILL;
}
return 0;
}
#endif
/*
* Emulate a single COP1 arithmetic instruction.
*/
static int fpu_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
mips_instruction ir)
{
int rfmt; /* resulting format */
unsigned rcsr = 0; /* resulting csr */
unsigned cond;
union {
ieee754dp d;
ieee754sp s;
int w;
#ifdef __mips64
s64 l;
#endif
} rv; /* resulting value */
MIPS_FPU_EMU_INC_STATS(cp1ops);
switch (rfmt = (MIPSInst_FFMT(ir) & 0xf)) {
case s_fmt:{ /* 0 */
union {
ieee754sp(*b) (ieee754sp, ieee754sp);
ieee754sp(*u) (ieee754sp);
} handler;
switch (MIPSInst_FUNC(ir)) {
/* binary ops */
case fadd_op:
handler.b = ieee754sp_add;
goto scopbop;
case fsub_op:
handler.b = ieee754sp_sub;
goto scopbop;
case fmul_op:
handler.b = ieee754sp_mul;
goto scopbop;
case fdiv_op:
handler.b = ieee754sp_div;
goto scopbop;
/* unary ops */
#if __mips >= 2 || defined(__mips64)
case fsqrt_op:
handler.u = ieee754sp_sqrt;
goto scopuop;
#endif
#if __mips >= 4 && __mips != 32
case frsqrt_op:
handler.u = fpemu_sp_rsqrt;
goto scopuop;
case frecip_op:
handler.u = fpemu_sp_recip;
goto scopuop;
#endif
#if __mips >= 4
case fmovc_op:
cond = fpucondbit[MIPSInst_FT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) !=
((MIPSInst_FT(ir) & 1) != 0))
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
case fmovz_op:
if (xcp->regs[MIPSInst_FT(ir)] != 0)
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
case fmovn_op:
if (xcp->regs[MIPSInst_FT(ir)] == 0)
return 0;
SPFROMREG(rv.s, MIPSInst_FS(ir));
break;
#endif
case fabs_op:
handler.u = ieee754sp_abs;
goto scopuop;
case fneg_op:
handler.u = ieee754sp_neg;
goto scopuop;
case fmov_op:
/* an easy one */
SPFROMREG(rv.s, MIPSInst_FS(ir));
goto copcsr;
/* binary op on handler */
scopbop:
{
ieee754sp fs, ft;
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
rv.s = (*handler.b) (fs, ft);
goto copcsr;
}
scopuop:
{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.s = (*handler.u) (fs);
goto copcsr;
}
copcsr:
if (ieee754_cxtest(IEEE754_INEXACT))
rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S;
if (ieee754_cxtest(IEEE754_UNDERFLOW))
rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S;
if (ieee754_cxtest(IEEE754_OVERFLOW))
rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S;
if (ieee754_cxtest(IEEE754_ZERO_DIVIDE))
rcsr |= FPU_CSR_DIV_X | FPU_CSR_DIV_S;
if (ieee754_cxtest(IEEE754_INVALID_OPERATION))
rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S;
break;
/* unary conv ops */
case fcvts_op:
return SIGILL; /* not defined */
case fcvtd_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.d = ieee754dp_fsp(fs);
rfmt = d_fmt;
goto copcsr;
}
case fcvtw_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.w = ieee754sp_tint(fs);
rfmt = w_fmt;
goto copcsr;
}
#if __mips >= 2 || defined(__mips64)
case fround_op:
case ftrunc_op:
case fceil_op:
case ffloor_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.w = ieee754sp_tint(fs);
ieee754_csr.rm = oldrm;
rfmt = w_fmt;
goto copcsr;
}
#endif /* __mips >= 2 */
#if defined(__mips64)
case fcvtl_op:{
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
rv.l = ieee754sp_tlong(fs);
rfmt = l_fmt;
goto copcsr;
}
case froundl_op:
case ftruncl_op:
case fceill_op:
case ffloorl_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754sp fs;
SPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.l = ieee754sp_tlong(fs);
ieee754_csr.rm = oldrm;
rfmt = l_fmt;
goto copcsr;
}
#endif /* defined(__mips64) */
default:
if (MIPSInst_FUNC(ir) >= fcmp_op) {
unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op;
ieee754sp fs, ft;
SPFROMREG(fs, MIPSInst_FS(ir));
SPFROMREG(ft, MIPSInst_FT(ir));
rv.w = ieee754sp_cmp(fs, ft,
cmptab[cmpop & 0x7], cmpop & 0x8);
rfmt = -1;
if ((cmpop & 0x8) && ieee754_cxtest
(IEEE754_INVALID_OPERATION))
rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S;
else
goto copcsr;
}
else {
return SIGILL;
}
break;
}
break;
}
case d_fmt:{
union {
ieee754dp(*b) (ieee754dp, ieee754dp);
ieee754dp(*u) (ieee754dp);
} handler;
switch (MIPSInst_FUNC(ir)) {
/* binary ops */
case fadd_op:
handler.b = ieee754dp_add;
goto dcopbop;
case fsub_op:
handler.b = ieee754dp_sub;
goto dcopbop;
case fmul_op:
handler.b = ieee754dp_mul;
goto dcopbop;
case fdiv_op:
handler.b = ieee754dp_div;
goto dcopbop;
/* unary ops */
#if __mips >= 2 || defined(__mips64)
case fsqrt_op:
handler.u = ieee754dp_sqrt;
goto dcopuop;
#endif
#if __mips >= 4 && __mips != 32
case frsqrt_op:
handler.u = fpemu_dp_rsqrt;
goto dcopuop;
case frecip_op:
handler.u = fpemu_dp_recip;
goto dcopuop;
#endif
#if __mips >= 4
case fmovc_op:
cond = fpucondbit[MIPSInst_FT(ir) >> 2];
if (((ctx->fcr31 & cond) != 0) !=
((MIPSInst_FT(ir) & 1) != 0))
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
case fmovz_op:
if (xcp->regs[MIPSInst_FT(ir)] != 0)
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
case fmovn_op:
if (xcp->regs[MIPSInst_FT(ir)] == 0)
return 0;
DPFROMREG(rv.d, MIPSInst_FS(ir));
break;
#endif
case fabs_op:
handler.u = ieee754dp_abs;
goto dcopuop;
case fneg_op:
handler.u = ieee754dp_neg;
goto dcopuop;
case fmov_op:
/* an easy one */
DPFROMREG(rv.d, MIPSInst_FS(ir));
goto copcsr;
/* binary op on handler */
dcopbop:{
ieee754dp fs, ft;
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
rv.d = (*handler.b) (fs, ft);
goto copcsr;
}
dcopuop:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.d = (*handler.u) (fs);
goto copcsr;
}
/* unary conv ops */
case fcvts_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.s = ieee754sp_fdp(fs);
rfmt = s_fmt;
goto copcsr;
}
case fcvtd_op:
return SIGILL; /* not defined */
case fcvtw_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.w = ieee754dp_tint(fs); /* wrong */
rfmt = w_fmt;
goto copcsr;
}
#if __mips >= 2 || defined(__mips64)
case fround_op:
case ftrunc_op:
case fceil_op:
case ffloor_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.w = ieee754dp_tint(fs);
ieee754_csr.rm = oldrm;
rfmt = w_fmt;
goto copcsr;
}
#endif
#if defined(__mips64)
case fcvtl_op:{
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
rv.l = ieee754dp_tlong(fs);
rfmt = l_fmt;
goto copcsr;
}
case froundl_op:
case ftruncl_op:
case fceill_op:
case ffloorl_op:{
unsigned int oldrm = ieee754_csr.rm;
ieee754dp fs;
DPFROMREG(fs, MIPSInst_FS(ir));
ieee754_csr.rm = ieee_rm[modeindex(MIPSInst_FUNC(ir))];
rv.l = ieee754dp_tlong(fs);
ieee754_csr.rm = oldrm;
rfmt = l_fmt;
goto copcsr;
}
#endif /* __mips >= 3 */
default:
if (MIPSInst_FUNC(ir) >= fcmp_op) {
unsigned cmpop = MIPSInst_FUNC(ir) - fcmp_op;
ieee754dp fs, ft;
DPFROMREG(fs, MIPSInst_FS(ir));
DPFROMREG(ft, MIPSInst_FT(ir));
rv.w = ieee754dp_cmp(fs, ft,
cmptab[cmpop & 0x7], cmpop & 0x8);
rfmt = -1;
if ((cmpop & 0x8)
&&
ieee754_cxtest
(IEEE754_INVALID_OPERATION))
rcsr = FPU_CSR_INV_X | FPU_CSR_INV_S;
else
goto copcsr;
}
else {
return SIGILL;
}
break;
}
break;
}
case w_fmt:{
ieee754sp fs;
switch (MIPSInst_FUNC(ir)) {
case fcvts_op:
/* convert word to single precision real */
SPFROMREG(fs, MIPSInst_FS(ir));
rv.s = ieee754sp_fint(fs.bits);
rfmt = s_fmt;
goto copcsr;
case fcvtd_op:
/* convert word to double precision real */
SPFROMREG(fs, MIPSInst_FS(ir));
rv.d = ieee754dp_fint(fs.bits);
rfmt = d_fmt;
goto copcsr;
default:
return SIGILL;
}
break;
}
#if defined(__mips64)
case l_fmt:{
switch (MIPSInst_FUNC(ir)) {
case fcvts_op:
/* convert long to single precision real */
rv.s = ieee754sp_flong(ctx->fpr[MIPSInst_FS(ir)]);
rfmt = s_fmt;
goto copcsr;
case fcvtd_op:
/* convert long to double precision real */
rv.d = ieee754dp_flong(ctx->fpr[MIPSInst_FS(ir)]);
rfmt = d_fmt;
goto copcsr;
default:
return SIGILL;
}
break;
}
#endif
default:
return SIGILL;
}
/*
* Update the fpu CSR register for this operation.
* If an exception is required, generate a tidy SIGFPE exception,
* without updating the result register.
* Note: cause exception bits do not accumulate, they are rewritten
* for each op; only the flag/sticky bits accumulate.
*/
ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr;
if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) {
/*printk ("SIGFPE: fpu csr = %08x\n",ctx->fcr31); */
return SIGFPE;
}
/*
* Now we can safely write the result back to the register file.
*/
switch (rfmt) {
case -1:{
#if __mips >= 4
cond = fpucondbit[MIPSInst_FD(ir) >> 2];
#else
cond = FPU_CSR_COND;
#endif
if (rv.w)
ctx->fcr31 |= cond;
else
ctx->fcr31 &= ~cond;
break;
}
case d_fmt:
DPTOREG(rv.d, MIPSInst_FD(ir));
break;
case s_fmt:
SPTOREG(rv.s, MIPSInst_FD(ir));
break;
case w_fmt:
SITOREG(rv.w, MIPSInst_FD(ir));
break;
#if defined(__mips64)
case l_fmt:
DITOREG(rv.l, MIPSInst_FD(ir));
break;
#endif
default:
return SIGILL;
}
return 0;
}
int fpu_emulator_cop1Handler(struct pt_regs *xcp, struct mips_fpu_struct *ctx,
int has_fpu)
{
unsigned long oldepc, prevepc;
mips_instruction insn;
int sig = 0;
oldepc = xcp->cp0_epc;
do {
prevepc = xcp->cp0_epc;
if (get_user(insn, (mips_instruction __user *) xcp->cp0_epc)) {
MIPS_FPU_EMU_INC_STATS(errors);
return SIGBUS;
}
if (insn == 0)
xcp->cp0_epc += 4; /* skip nops */
else {
/*
* The 'ieee754_csr' is an alias of
* ctx->fcr31. No need to copy ctx->fcr31 to
* ieee754_csr. But ieee754_csr.rm is ieee
* library modes. (not mips rounding mode)
*/
/* convert to ieee library modes */
ieee754_csr.rm = ieee_rm[ieee754_csr.rm];
sig = cop1Emulate(xcp, ctx);
/* revert to mips rounding mode */
ieee754_csr.rm = mips_rm[ieee754_csr.rm];
}
if (has_fpu)
break;
if (sig)
break;
cond_resched();
} while (xcp->cp0_epc > prevepc);
/* SIGILL indicates a non-fpu instruction */
if (sig == SIGILL && xcp->cp0_epc != oldepc)
/* but if epc has advanced, then ignore it */
sig = 0;
return sig;
}
#ifdef CONFIG_DEBUG_FS
static int fpuemu_stat_get(void *data, u64 *val)
{
int cpu;
unsigned long sum = 0;
for_each_online_cpu(cpu) {
struct mips_fpu_emulator_stats *ps;
local_t *pv;
ps = &per_cpu(fpuemustats, cpu);
pv = (void *)ps + (unsigned long)data;
sum += local_read(pv);
}
*val = sum;
return 0;
}
DEFINE_SIMPLE_ATTRIBUTE(fops_fpuemu_stat, fpuemu_stat_get, NULL, "%llu\n");
extern struct dentry *mips_debugfs_dir;
static int __init debugfs_fpuemu(void)
{
struct dentry *d, *dir;
if (!mips_debugfs_dir)
return -ENODEV;
dir = debugfs_create_dir("fpuemustats", mips_debugfs_dir);
if (!dir)
return -ENOMEM;
#define FPU_STAT_CREATE(M) \
do { \
d = debugfs_create_file(#M , S_IRUGO, dir, \
(void *)offsetof(struct mips_fpu_emulator_stats, M), \
&fops_fpuemu_stat); \
if (!d) \
return -ENOMEM; \
} while (0)
FPU_STAT_CREATE(emulated);
FPU_STAT_CREATE(loads);
FPU_STAT_CREATE(stores);
FPU_STAT_CREATE(cp1ops);
FPU_STAT_CREATE(cp1xops);
FPU_STAT_CREATE(errors);
return 0;
}
__initcall(debugfs_fpuemu);
#endif
| gpl-2.0 |
ysleu/RTL8685 | uClinux-dist/linux-2.6.x/rtk_voip-single_cpu/voip_drivers/iphone/base_i2c_core.c | 5874 | // move to voip_drivers/i2c.c
#if 0
#include <linux/config.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/list.h>
#include <linux/string.h>
#include "base_gpio.h"
#include "base_i2c_core.h"
/************************* I2C read/write function ************************/
void i2c_serial_write(i2c_dev_t* pI2C_Dev, unsigned char *data)
{
int i;
char j;
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
for (j=7;j>=0;j--) {
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
__i2c_setGpioDataBit( pI2C_Dev->sdio, ((*data)>>j)&0x00000001);//write data,from MSB to LSB
//delay 2 us.
#ifdef __kernel_used__
udelay(2*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<2000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
}
return;
}
unsigned char i2c_ACK(i2c_dev_t* pI2C_Dev)
{
int i;
unsigned int buf;
#if 0
__i2c_setGpioDataBit( pI2C_Dev->sdio, 0); /* fall down sdio*/
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_IN, GPIO_INT_DISABLE);//change sdio to input
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
#endif
//__i2c_setGpioDataBit( pI2C_Dev->sdio, 0); /* fall down sdio*/
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_IN, GPIO_INT_DISABLE);//change sdio to input
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_getGpioDataBit(pI2C_Dev->sdio,&buf);
if (buf != 0)
printk("NO ACK\n");
//__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_INT_DISABLE);//change sdio to output
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
#if 0
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
#endif
return buf;
}
void i2c_ACK_w(i2c_dev_t* pI2C_Dev, unsigned char data)
{
int i;
#if 0
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
__i2c_setGpioDataBit( pI2C_Dev->sdio, data); /* sdio send 0 for ACK, 1 for NACK*/
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
//for (i=0;i<500*I2C_RATING_FACTOR;i++);
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
__i2c_setGpioDataBit( pI2C_Dev->sdio, data); /* sdio send 0 for ACK, 1 for NACK*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_IN, GPIO_INT_DISABLE);//change sdio to input
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
#if 0
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
#endif
return;
}
void i2c_serial_read(i2c_dev_t* pI2C_Dev, unsigned short int *data)
{
int i;
char j;
unsigned int buf;
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_IN, GPIO_INT_DISABLE);//change sdio to input
for (j=7;j>=0;j--) {
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
//delay 2 us.
#ifdef __kernel_used__
udelay(2*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<2000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
__i2c_getGpioDataBit( pI2C_Dev->sdio, &buf);//read data,from MSB to LSB
*data |= (buf<<j);
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
}
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
return;
}
void i2c_start_condition(i2c_dev_t* pI2C_Dev)
{
int i;
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
__i2c_setGpioDataBit( pI2C_Dev->sdio, 1); /* raise sdio*/
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sdio, 0); /* fall down sdio*//*start condition*/
//delay 2 us.
#ifdef __kernel_used__
udelay(2*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<2000*I2C_RATING_FACTOR;i++);
#endif
}
void i2c_stop_condition(i2c_dev_t* pI2C_Dev)
{
int i;
__i2c_setGpioDataBit( pI2C_Dev->sclk, 0); /* fall down sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_setGpioDataBit( pI2C_Dev->sclk, 1); /* raise sclk*/
//delay 1 us.
#ifdef __kernel_used__
udelay(1*I2C_RATING_FACTOR);
#endif
#ifdef __test_program_used__
for (i=0;i<1000*I2C_RATING_FACTOR;i++);
#endif
__i2c_initGpioPin(pI2C_Dev->sdio, GPIO_DIR_OUT, GPIO_INT_DISABLE);//change sdio to output
__i2c_setGpioDataBit( pI2C_Dev->sdio, 1); /* raise sdio*//*stop condition*/
}
#endif
| gpl-2.0 |
FilipBE/qtextended | qtopiacore/qt/src/gui/itemviews/qtreeview_p.h | 7954 | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 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 GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
****************************************************************************/
#ifndef QTREEVIEW_P_H
#define QTREEVIEW_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists purely as an
// implementation detail. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include "private/qabstractitemview_p.h"
#ifndef QT_NO_TREEVIEW
QT_BEGIN_NAMESPACE
struct QTreeViewItem
{
QTreeViewItem() : expanded(false), spanning(false), total(0), level(0), height(0) {}
QModelIndex index; // we remove items whenever the indexes are invalidated
uint expanded : 1;
uint spanning : 1;
uint total : 30; // total number of children visible
uint level : 16; // indentation
int height : 16; // row height
};
class QTreeViewPrivate : public QAbstractItemViewPrivate
{
Q_DECLARE_PUBLIC(QTreeView)
public:
QTreeViewPrivate()
: QAbstractItemViewPrivate(),
header(0), indent(20), lastViewedItem(0), defaultItemHeight(-1),
uniformRowHeights(false), rootDecoration(true),
itemsExpandable(true), sortingEnabled(false),
expandsOnDoubleClick(true),
allColumnsShowFocus(false),
animationsEnabled(false), columnResizeTimerID(0),
autoExpandDelay(-1), hoverBranch(-1), geometryRecursionBlock(false) {}
~QTreeViewPrivate() {}
void initialize();
struct AnimatedOperation
{
enum Type { Expand, Collapse };
int item;
int top;
int duration;
Type type;
QPixmap before;
QPixmap after;
};
void expand(int item, bool emitSignal);
void collapse(int item, bool emitSignal);
void prepareAnimatedOperation(int item, AnimatedOperation::Type type);
void beginAnimatedOperation();
void _q_endAnimatedOperation();
void drawAnimatedOperation(QPainter *painter) const;
QPixmap renderTreeToPixmap(const QRect &rect) const;
inline QRect animationRect() const
{ return QRect(0, animatedOperation.top, viewport->width(),
viewport->height() - animatedOperation.top); }
void _q_currentChanged(const QModelIndex&, const QModelIndex&);
void _q_columnsAboutToBeRemoved(const QModelIndex &, int, int);
void _q_columnsRemoved(const QModelIndex &, int, int);
void _q_modelAboutToBeReset();
void layout(int item);
int pageUp(int item) const;
int pageDown(int item) const;
inline int above(int item) const
{ return (--item < 0 ? 0 : item); }
inline int below(int item) const
{ return (++item >= viewItems.count() ? viewItems.count() - 1 : item); }
inline void invalidateHeightCache(int item) const
{ viewItems[item].height = 0; }
int itemHeight(int item) const;
int indentationForItem(int item) const;
int coordinateForItem(int item) const;
int itemAtCoordinate(int coordinate) const;
int viewIndex(const QModelIndex &index) const;
QModelIndex modelIndex(int i) const;
int firstVisibleItem(int *offset = 0) const;
int columnAt(int x) const;
bool hasVisibleChildren( const QModelIndex& parent) const;
void relayout(const QModelIndex &parent);
void reexpandChildren(const QModelIndex &parent);
void updateScrollBars();
int itemDecorationAt(const QPoint &pos) const;
QList<QPair<int, int> > columnRanges(const QModelIndex &topIndex, const QModelIndex &bottomIndex) const;
void select(const QModelIndex &start, const QModelIndex &stop, QItemSelectionModel::SelectionFlags command);
QPair<int,int> startAndEndColumns(const QRect &rect) const;
void updateChildCount(const int parentItem, const int delta);
void rowsRemoved(const QModelIndex &parent,
int start, int end, bool before);
void paintAlternatingRowColors(QPainter *painter, QStyleOptionViewItemV4 *option, int y, int bottom) const;
QHeaderView *header;
int indent;
mutable QVector<QTreeViewItem> viewItems;
mutable int lastViewedItem;
int defaultItemHeight; // this is just a number; contentsHeight() / numItems
bool uniformRowHeights; // used when all rows have the same height
bool rootDecoration;
bool itemsExpandable;
bool sortingEnabled;
bool expandsOnDoubleClick;
bool allColumnsShowFocus;
// used for drawing
mutable QPair<int,int> leftAndRight;
mutable int current;
mutable bool spanning;
// used when expanding and collapsing items
QList<QPersistentModelIndex> expandedIndexes;
QStack<bool> expandParent;
AnimatedOperation animatedOperation;
bool animationsEnabled;
inline bool storeExpanded(const QPersistentModelIndex &idx) {
QList<QPersistentModelIndex>::iterator it;
it = qLowerBound(expandedIndexes.begin(), expandedIndexes.end(), idx);
if (it == expandedIndexes.end() || *it != idx) {
expandedIndexes.insert(it, idx);
return true;
}
return false;
}
inline bool isIndexExpanded(const QPersistentModelIndex idx) const {
QList<QPersistentModelIndex>::const_iterator it;
it = qBinaryFind(expandedIndexes.constBegin(), expandedIndexes.constEnd(), idx);
return (it != expandedIndexes.constEnd());
}
// used when hiding and showing items
QVector<QPersistentModelIndex> hiddenIndexes;
inline bool isRowHidden(const QPersistentModelIndex idx) const {
QVector<QPersistentModelIndex>::const_iterator it;
it = qBinaryFind(hiddenIndexes.constBegin(), hiddenIndexes.constEnd(), idx);
return (it != hiddenIndexes.constEnd());
}
// used for spanning rows
QVector<QPersistentModelIndex> spanningIndexes;
// used for updating resized columns
int columnResizeTimerID;
QList<int> columnsToUpdate;
// used for the automatic opening of nodes during DND
int autoExpandDelay;
QBasicTimer openTimer;
// used for drawing hilighted expand/collapse indicators
int hoverBranch;
// used for blocking recursion when calling setViewportMargins from updateGeometries
bool geometryRecursionBlock;
};
QT_END_NAMESPACE
#endif // QT_NO_TREEVIEW
#endif // QTREEVIEW_P_H
| gpl-2.0 |
omerta/huayra | sno/sigesp_snorh_c_diaferiado.php | 16072 | <?php
class sigesp_snorh_c_diaferiado
{
var $io_sql;
var $io_mensajes;
var $io_funciones;
var $io_seguridad;
var $io_sno;
var $ls_codemp;
//-----------------------------------------------------------------------------------------------------------------------------------
function sigesp_snorh_c_diaferiado()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: sigesp_snorh_c_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Constructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
require_once("../shared/class_folder/sigesp_include.php");
$io_include=new sigesp_include();
$io_conexion=$io_include->uf_conectar();
require_once("../shared/class_folder/class_sql.php");
$this->io_sql=new class_sql($io_conexion);
require_once("../shared/class_folder/class_mensajes.php");
$this->io_mensajes=new class_mensajes();
require_once("../shared/class_folder/class_funciones.php");
$this->io_funciones=new class_funciones();
require_once("../shared/class_folder/sigesp_c_seguridad.php");
$this->io_seguridad=new sigesp_c_seguridad();
require_once("sigesp_sno.php");
$this->io_sno=new sigesp_sno();
$this->ls_codemp=$_SESSION["la_empresa"]["codemp"];
}// end function sigesp_snorh_c_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_destructor()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_destructor
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Destructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unset($io_include);
unset($io_conexion);
unset($this->io_sql);
unset($this->io_mensajes);
unset($this->io_funciones);
unset($this->io_seguridad);
unset($this->ls_codemp);
}// end function uf_destructor
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_diaferiado($as_campo,$as_valor)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_diaferiado
// Access: private
// Arguments: as_campo // Campo por el que se quiere filtrar
// as_valor // Valor del campo
// Returns: lb_existe True si existe ó False si no existe
// Description: Funcion que verifica si el día feriado está registrado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_existe=true;
$ls_sql="SELECT ".$as_campo." ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND ".$as_campo."='".$as_valor."'";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$lb_existe=false;
}
else
{
if(!$row=$this->io_sql->fetch_row($rs_data))
{
$lb_existe=false;
}
$this->io_sql->free_result($rs_data);
}
return $lb_existe;
}// end function uf_select_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el insert ó False si hubo error en el insert
// Description: Funcion que inserta en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="INSERT INTO sno_diaferiado".
"(codemp,fecfer,nomfer)VALUES('".$this->ls_codemp."','".$ad_fecfer."','".$as_nomfer."')";
$this->io_sql->begin_transaction() ;
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="INSERT";
$ls_descripcion ="Insertó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Dia Feriado fue registrado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_insert_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_update_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el update ó False si hubo error en el update
// Description: Funcion que actualiza en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="UPDATE sno_diaferiado ".
" SET nomfer='".$as_nomfer."' ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="UPDATE";
$ls_descripcion ="Actualizó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Actualizado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_update_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_guardar($as_existe,$ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_guardar
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si guardo ó False si hubo error al guardar
// Description: Funcion que almacena el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$lb_valido=false;
switch ($as_existe)
{
case "FALSE":
if($this->uf_select_diaferiado("fecfer",$ad_fecfer)===false)
{
$lb_valido=$this->uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado ya existe, no lo puede incluir.");
}
break;
case "TRUE":
if(($this->uf_select_diaferiado("fecfer",$ad_fecfer)))
{
$lb_valido=$this->uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado no existe, no lo puede actualizar.");
}
break;
}
return $lb_valido;
}// end function uf_guardar
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_delete_diaferiado($ad_fecfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_delete_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el delete ó False si hubo error en el delete
// Description: Funcion que elimina el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$ls_sql="DELETE ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="DELETE";
$ls_descripcion ="Eliminó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Eliminado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}// end function uf_delete_diaferiado
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_feriados($ad_fecdes,$ad_fechas)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_feriados
// Access: private
// Arguments: ad_fecdes // Fecha desde
// ad_fechas // Fecha Hasta
// Returns: li_total Toal de días feriados
// Description: Funcion que cuenta la cantidad de días feriados dada una fecha
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 07/09/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$li_total=0;
$ls_sql="SELECT fecfer ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer>='".$ad_fecdes."' ".
" AND fecfer<='".$ad_fechas."' ";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_feriados ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
}
else
{
while($row=$this->io_sql->fetch_row($rs_data))
{
$ld_fecfer=$row["fecfer"];
$ld_fecfer=$this->io_funciones->uf_convertirfecmostrar($ld_fecfer);
if($this->io_sno->uf_nro_sabydom($ld_fecfer,$ld_fecfer)==0)
{
$li_total=$li_total+1;
}
}
$this->io_sql->free_result($rs_data);
}
return $li_total;
}// end function uf_select_feriados
//-----------------------------------------------------------------------------------------------------------------------------------
}
?> | gpl-2.0 |
juampynr/DrupalCampEs | sites/all/themes/contrib/da_vinci/js/plugins/jquery.actual.min.js | 966 | (function(a){a.fn.addBack=a.fn.addBack||a.fn.andSelf;
a.fn.extend({actual:function(b,l){if(!this[b]){throw'$.actual => The jQuery method "'+b+'" you called does not exist';}var f={absolute:false,clone:false,includeMargin:false};
var i=a.extend(f,l);var e=this.eq(0);var h,j;if(i.clone===true){h=function(){var m="position: absolute !important; top: -1000 !important; ";e=e.clone().attr("style",m).appendTo("body");
};j=function(){e.remove();};}else{var g=[];var d="";var c;h=function(){c=e.parents().addBack().filter(":hidden");d+="visibility: hidden !important; display: block !important; ";
if(i.absolute===true){d+="position: absolute !important; ";}c.each(function(){var m=a(this);var n=m.attr("style");g.push(n);m.attr("style",n?n+";"+d:d);
});};j=function(){c.each(function(m){var o=a(this);var n=g[m];if(n===undefined){o.removeAttr("style");}else{o.attr("style",n);}});};}h();var k=/(outer)/.test(b)?e[b](i.includeMargin):e[b]();
j();return k;}});})(jQuery);
| gpl-2.0 |
gabi2/yast-yast2 | library/packages/test/product_test.rb | 11801 | #!/usr/bin/env rspec
require_relative "test_helper"
require "yaml"
# Important: Loads data in constructor
Yast.import "Product"
Yast.import "Mode"
Yast.import "Stage"
Yast.import "OSRelease"
Yast.import "PackageSystem"
Yast.import "Pkg"
Yast.import "PackageLock"
Yast.import "Mode"
Yast.import "Stage"
include Yast::Logger
# Path to a test data - service file - mocking the default data path
DATA_PATH = File.join(File.expand_path(File.dirname(__FILE__)), "data")
def load_zypp(file_name)
file_name = File.join(DATA_PATH, "zypp", file_name)
raise "File not found: #{file_name}" unless File.exist?(file_name)
log.info "Loading file: #{file_name}"
YAML.load_file(file_name)
end
PRODUCTS_FROM_ZYPP = load_zypp("products.yml").freeze
def stub_defaults
log.info "--------- Running test ---------"
Yast::Product.send(:reset)
allow(Yast::PackageSystem).to receive(:EnsureTargetInit).and_return(true)
allow(Yast::PackageSystem).to receive(:EnsureSourceInit).and_return(true)
allow(Yast::Pkg).to receive(:PkgSolve).and_return(true)
allow(Yast::PackageLock).to receive(:Check).and_return(true)
allow(Yast::Pkg).to receive(:ResolvableProperties).with("", :product, "").and_return(PRODUCTS_FROM_ZYPP.dup)
end
# Describes Product handling as a whole (due to lazy loading and internal caching),
# methods descriptions are below
describe "Yast::Product (integration)" do
before(:each) do
stub_defaults
end
context "while called in installation system without os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
end
describe "when the mode is Installation" do
it "reads product information from zypp and fills up internal variables" do
allow(Yast::Mode).to receive(:mode).and_return("installation")
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
end
end
describe "when the mode is Update" do
it "reads product information from zypp and fills up internal variables" do
allow(Yast::Mode).to receive(:mode).and_return("update")
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
end
end
end
context "while called on a running system with os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(true)
end
# This is the default behavior
context "OSRelease is complete" do
it "reads product information from OSRelease and fills up internal variables" do
release_info = "Happy Feet 2.0"
allow(Yast::OSRelease).to receive(:ReleaseName).and_return("anything")
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return("anything")
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return(release_info)
expect(Yast::Product.name).to eq(release_info)
end
end
# This is the fallback behavior
context "OSRelease is incomplete" do
it "reads product information from OSRelease and then zypp and fills up internal variables" do
release_name = "Happy Feet"
release_version = "1.0.1"
allow(Yast::OSRelease).to receive(:ReleaseName).and_return(release_name)
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return(release_version)
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return("")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
expect(Yast::Product.name).to eq("openSUSE (INSTALLED)")
end
end
end
context "while called on a running system without os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
end
it "reads product information from zypp and fills up internal variables" do
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
expect(Yast::Product.name).to eq("openSUSE (INSTALLED)")
end
end
end
# Describes Product methods
describe Yast::Product do
before(:each) do
stub_defaults
end
context "while called in installation without os-release file" do
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::Mode).to receive(:mode).and_return("installation")
end
describe "#name" do
it "reads data from zypp and returns product name" do
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
end
end
describe "#short_name" do
it "reads data from zypp and returns short product name" do
expect(Yast::Product.short_name).to eq("openSUSE")
end
end
describe "#version" do
it "reads data from zypp and returns product version" do
expect(Yast::Product.version).to eq("13.1")
end
end
describe "#run_you" do
it "reads data from zypp and returns whether running online update is requested" do
expect(Yast::Product.run_you).to eq(false)
end
end
describe "#relnotesurl" do
it "reads data from zypp and returns URL to release notes" do
expect(Yast::Product.relnotesurl).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"
)
end
end
describe "#relnotesurl_all" do
it "reads data from zypp and returns list of all URLs to release notes" do
expect(Yast::Product.relnotesurl_all).to eq(
["http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"]
)
end
end
describe "#product_of_relnotes" do
it "reads data from zypp and returns hash of release notes URLs linking to their product names" do
expect(Yast::Product.product_of_relnotes).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm" => "openSUSE (SELECTED)"
)
end
end
describe "#FindBaseProducts" do
it "reads data from zypp and returns list of base products selected for installation" do
list_of_products = Yast::Product.FindBaseProducts
expect(list_of_products).to be_a_kind_of(Array)
expect(list_of_products[0]).to be_a_kind_of(Hash)
expect(list_of_products[0]["display_name"]).to eq("openSUSE (SELECTED)")
expect(list_of_products[0]["status"]).to eq(:selected)
end
end
it "reports that method has been dropped" do
[:vendor, :dist, :distproduct, :distversion, :shortlabel].each do |method_name|
expect { Yast::Product.send(method_name) }.to raise_error(/#{method_name}.*dropped/)
end
end
end
context "while called on running system with os-release file" do
release_name = "Mraky a Internety"
release_version = "44.6"
release_info = "#{release_name} #{release_version} (Banana Juice)"
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(true)
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:ReleaseName).and_return(release_name)
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return(release_version)
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return(release_info)
end
describe "#name" do
it "reads data from os-release and returns product name" do
expect(Yast::Product.name).to eq(release_info)
end
end
describe "#short_name" do
it "reads data from os-release and returns short product name" do
expect(Yast::Product.short_name).to eq(release_name)
end
end
describe "#version" do
it "reads data from os-release and returns product version" do
expect(Yast::Product.version).to eq(release_version)
end
end
describe "#run_you" do
it "reads data from zypp and returns whether running online update is requested" do
expect(Yast::Product.run_you).to eq(false)
end
end
describe "#relnotesurl" do
it "reads data from zypp and returns URL to release notes" do
expect(Yast::Product.relnotesurl).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"
)
end
end
describe "#relnotesurl_all" do
it "reads data from zypp and returns list of all URLs to release notes" do
expect(Yast::Product.relnotesurl_all).to eq(
["http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"]
)
end
end
describe "#product_of_relnotes" do
it "reads data from zypp and returns hash of release notes URLs linking to their product names" do
expect(Yast::Product.product_of_relnotes).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm" => "openSUSE (INSTALLED)"
)
end
end
it "reports that method has been dropped" do
[:vendor, :dist, :distproduct, :distversion, :shortlabel].each do |method_name|
expect { Yast::Product.send(method_name) }.to raise_error(/#{method_name}.*dropped/)
end
end
end
# Methods that do not allow empty result
SUPPORTED_METHODS = [:name, :short_name, :version, :run_you, :flags, :relnotesurl]
# Empty result is allowed
SUPPORTED_METHODS_ALLOWED_EMPTY = [:relnotesurl_all, :product_of_relnotes]
context "while called on a broken system (no os-release, no zypp information)" do
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
allow(Yast::Pkg).to receive(:ResolvableProperties).with("", :product, "").and_return([])
end
context "in installation" do
it "reports that no base product was found" do
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::Mode).to receive(:mode).and_return("installation")
SUPPORTED_METHODS.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect { Yast::Product.send(method_name) }.to raise_error(/no base product found/i)
end
SUPPORTED_METHODS_ALLOWED_EMPTY.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect(Yast::Product.send(method_name)).to be_empty
end
end
end
context "on a running system" do
it "reports that no base product was found" do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
SUPPORTED_METHODS.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect { Yast::Product.send(method_name) }.to raise_error(/no base product found/i)
end
SUPPORTED_METHODS_ALLOWED_EMPTY.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect(Yast::Product.send(method_name)).to be_empty
end
end
end
end
end
| gpl-2.0 |
djbouche/nucog | Extdeps/ffmpeg/src/libavcodec/vorbis.c | 6921 | /**
* @file
* Common code for Vorbis I encoder and decoder
* @author Denes Balatoni ( dbalatoni programozo hu )
*
* 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
*/
/**
* @file
* Common code for Vorbis I encoder and decoder
* @author Denes Balatoni ( dbalatoni programozo hu )
*/
#define BITSTREAM_READER_LE
#include "avcodec.h"
#include "get_bits.h"
#include "vorbis.h"
/* Helper functions */
// x^(1/n)
unsigned int ff_vorbis_nth_root(unsigned int x, unsigned int n)
{
unsigned int ret = 0, i, j;
do {
++ret;
for (i = 0, j = ret; i < n - 1; i++)
j *= ret;
} while (j <= x);
return ret - 1;
}
// Generate vlc codes from vorbis huffman code lengths
// the two bits[p] > 32 checks should be redundant, all calling code should
// already ensure that, but since it allows overwriting the stack it seems
// reasonable to check redundantly.
int ff_vorbis_len2vlc(uint8_t *bits, uint32_t *codes, unsigned num)
{
uint32_t exit_at_level[33] = { 404 };
unsigned i, j, p, code;
#ifdef DEBUG
GetBitContext gb;
#endif
for (p = 0; (bits[p] == 0) && (p < num); ++p)
;
if (p == num) {
// av_log(vc->avccontext, AV_LOG_INFO, "An empty codebook. Heh?! \n");
return 0;
}
codes[p] = 0;
if (bits[p] > 32)
return 1;
for (i = 0; i < bits[p]; ++i)
exit_at_level[i+1] = 1 << i;
#ifdef DEBUG
av_log(NULL, AV_LOG_INFO, " %u. of %u code len %d code %d - ", p, num, bits[p], codes[p]);
init_get_bits(&gb, (uint8_t *)&codes[p], bits[p]);
for (i = 0; i < bits[p]; ++i)
av_log(NULL, AV_LOG_INFO, "%s", get_bits1(&gb) ? "1" : "0");
av_log(NULL, AV_LOG_INFO, "\n");
#endif
++p;
for (; p < num; ++p) {
if (bits[p] > 32)
return 1;
if (bits[p] == 0)
continue;
// find corresponding exit(node which the tree can grow further from)
for (i = bits[p]; i > 0; --i)
if (exit_at_level[i])
break;
if (!i) // overspecified tree
return 1;
code = exit_at_level[i];
exit_at_level[i] = 0;
// construct code (append 0s to end) and introduce new exits
for (j = i + 1 ;j <= bits[p]; ++j)
exit_at_level[j] = code + (1 << (j - 1));
codes[p] = code;
#ifdef DEBUG
av_log(NULL, AV_LOG_INFO, " %d. code len %d code %d - ", p, bits[p], codes[p]);
init_get_bits(&gb, (uint8_t *)&codes[p], bits[p]);
for (i = 0; i < bits[p]; ++i)
av_log(NULL, AV_LOG_INFO, "%s", get_bits1(&gb) ? "1" : "0");
av_log(NULL, AV_LOG_INFO, "\n");
#endif
}
//no exits should be left (underspecified tree - ie. unused valid vlcs - not allowed by SPEC)
for (p = 1; p < 33; p++)
if (exit_at_level[p])
return 1;
return 0;
}
int ff_vorbis_ready_floor1_list(AVCodecContext *avccontext,
vorbis_floor1_entry *list, int values)
{
int i;
list[0].sort = 0;
list[1].sort = 1;
for (i = 2; i < values; i++) {
int j;
list[i].low = 0;
list[i].high = 1;
list[i].sort = i;
for (j = 2; j < i; j++) {
int tmp = list[j].x;
if (tmp < list[i].x) {
if (tmp > list[list[i].low].x)
list[i].low = j;
} else {
if (tmp < list[list[i].high].x)
list[i].high = j;
}
}
}
for (i = 0; i < values - 1; i++) {
int j;
for (j = i + 1; j < values; j++) {
if (list[i].x == list[j].x) {
av_log(avccontext, AV_LOG_ERROR,
"Duplicate value found in floor 1 X coordinates\n");
return AVERROR_INVALIDDATA;
}
if (list[list[i].sort].x > list[list[j].sort].x) {
int tmp = list[i].sort;
list[i].sort = list[j].sort;
list[j].sort = tmp;
}
}
}
return 0;
}
static inline void render_line_unrolled(intptr_t x, int y, int x1,
intptr_t sy, int ady, int adx,
float *buf)
{
int err = -adx;
x -= x1 - 1;
buf += x1 - 1;
while (++x < 0) {
err += ady;
if (err >= 0) {
err += ady - adx;
y += sy;
buf[x++] = ff_vorbis_floor1_inverse_db_table[av_clip_uint8(y)];
}
buf[x] = ff_vorbis_floor1_inverse_db_table[av_clip_uint8(y)];
}
if (x <= 0) {
if (err + ady >= 0)
y += sy;
buf[x] = ff_vorbis_floor1_inverse_db_table[av_clip_uint8(y)];
}
}
static void render_line(int x0, int y0, int x1, int y1, float *buf)
{
int dy = y1 - y0;
int adx = x1 - x0;
int ady = FFABS(dy);
int sy = dy < 0 ? -1 : 1;
buf[x0] = ff_vorbis_floor1_inverse_db_table[av_clip_uint8(y0)];
if (ady*2 <= adx) { // optimized common case
render_line_unrolled(x0, y0, x1, sy, ady, adx, buf);
} else {
int base = dy / adx;
int x = x0;
int y = y0;
int err = -adx;
ady -= FFABS(base) * adx;
while (++x < x1) {
y += base;
err += ady;
if (err >= 0) {
err -= adx;
y += sy;
}
buf[x] = ff_vorbis_floor1_inverse_db_table[av_clip_uint8(y)];
}
}
}
void ff_vorbis_floor1_render_list(vorbis_floor1_entry * list, int values,
uint16_t *y_list, int *flag,
int multiplier, float *out, int samples)
{
int lx, ly, i;
lx = 0;
ly = y_list[0] * multiplier;
for (i = 1; i < values; i++) {
int pos = list[i].sort;
if (flag[pos]) {
int x1 = list[pos].x;
int y1 = y_list[pos] * multiplier;
if (lx < samples)
render_line(lx, ly, FFMIN(x1,samples), y1, out);
lx = x1;
ly = y1;
}
if (lx >= samples)
break;
}
if (lx < samples)
render_line(lx, ly, samples, ly, out);
}
| gpl-2.0 |
cvnhan/ncredmine | public/javascripts/context_menu.js | 6545 | var contextMenuObserving;
var contextMenuUrl;
function contextMenuRightClick(event) {
var target = $(event.target);
if (target.is('a')) {return;}
var tr = target.parents('tr').first();
if (!tr.hasClass('hascontextmenu')) {return;}
event.preventDefault();
if (!contextMenuIsSelected(tr)) {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
contextMenuSetLastSelected(tr);
}
contextMenuShow(event);
}
function contextMenuClick(event) {
var target = $(event.target);
var lastSelected;
if (target.is('a') && target.hasClass('submenu')) {
event.preventDefault();
return;
}
contextMenuHide();
if (target.is('a') || target.is('img')) { return; }
if (event.which == 1 || (navigator.appVersion.match(/\bMSIE\b/))) {
var tr = target.parents('tr').first();
if (tr.length && tr.hasClass('hascontextmenu')) {
// a row was clicked, check if the click was on checkbox
if (target.is('input')) {
// a checkbox may be clicked
if (target.prop('checked')) {
tr.addClass('context-menu-selection');
} else {
tr.removeClass('context-menu-selection');
}
} else {
if (event.ctrlKey || event.metaKey) {
contextMenuToggleSelection(tr);
} else if (event.shiftKey) {
lastSelected = contextMenuLastSelected();
if (lastSelected.length) {
var toggling = false;
$('.hascontextmenu').each(function(){
if (toggling || $(this).is(tr)) {
contextMenuAddSelection($(this));
}
if ($(this).is(tr) || $(this).is(lastSelected)) {
toggling = !toggling;
}
});
} else {
contextMenuAddSelection(tr);
}
} else {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
}
contextMenuSetLastSelected(tr);
}
} else {
// click is outside the rows
if (target.is('a') && (target.hasClass('disabled') || target.hasClass('submenu'))) {
event.preventDefault();
} else {
contextMenuUnselectAll();
}
}
}
}
function contextMenuCreate() {
if ($('#context-menu').length < 1) {
var menu = document.createElement("div");
menu.setAttribute("id", "context-menu");
menu.setAttribute("style", "display:none;");
document.getElementById("content").appendChild(menu);
}
}
function contextMenuShow(event) {
var mouse_x = event.pageX;
var mouse_y = event.pageY;
var render_x = mouse_x;
var render_y = mouse_y;
var dims;
var menu_width;
var menu_height;
var window_width;
var window_height;
var max_width;
var max_height;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').html('');
$.ajax({
url: contextMenuUrl,
data: $(event.target).parents('form').first().serialize(),
success: function(data, textStatus, jqXHR) {
$('#context-menu').html(data);
menu_width = $('#context-menu').width();
menu_height = $('#context-menu').height();
max_width = mouse_x + 2*menu_width;
max_height = mouse_y + menu_height;
var ws = window_size();
window_width = ws.width;
window_height = ws.height;
/* display the menu above and/or to the left of the click if needed */
if (max_width > window_width) {
render_x -= menu_width;
$('#context-menu').addClass('reverse-x');
} else {
$('#context-menu').removeClass('reverse-x');
}
if (max_height > window_height) {
render_y -= menu_height;
$('#context-menu').addClass('reverse-y');
} else {
$('#context-menu').removeClass('reverse-y');
}
if (render_x <= 0) render_x = 1;
if (render_y <= 0) render_y = 1;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').show();
//if (window.parseStylesheets) { window.parseStylesheets(); } // IE
}
});
}
function contextMenuSetLastSelected(tr) {
$('.cm-last').removeClass('cm-last');
tr.addClass('cm-last');
}
function contextMenuLastSelected() {
return $('.cm-last').first();
}
function contextMenuUnselectAll() {
$('.hascontextmenu').each(function(){
contextMenuRemoveSelection($(this));
});
$('.cm-last').removeClass('cm-last');
}
function contextMenuHide() {
$('#context-menu').hide();
}
function contextMenuToggleSelection(tr) {
if (contextMenuIsSelected(tr)) {
contextMenuRemoveSelection(tr);
} else {
contextMenuAddSelection(tr);
}
}
function contextMenuAddSelection(tr) {
tr.addClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, true);
contextMenuClearDocumentSelection();
}
function contextMenuRemoveSelection(tr) {
tr.removeClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, false);
}
function contextMenuIsSelected(tr) {
return tr.hasClass('context-menu-selection');
}
function contextMenuCheckSelectionBox(tr, checked) {
tr.find('input[type=checkbox]').prop('checked', checked);
}
function contextMenuClearDocumentSelection() {
// TODO
if (document.selection) {
document.selection.empty(); // IE
} else {
window.getSelection().removeAllRanges();
}
}
function contextMenuInit(url) {
contextMenuUrl = url;
contextMenuCreate();
contextMenuUnselectAll();
if (!contextMenuObserving) {
$(document).click(contextMenuClick);
$(document).contextmenu(contextMenuRightClick);
contextMenuObserving = true;
}
}
function toggleIssuesSelection(el) {
var boxes = $(el).parents('form').find('input[type=checkbox]');
var all_checked = true;
boxes.each(function(){ if (!$(this).prop('checked')) { all_checked = false; } });
boxes.each(function(){
if (all_checked) {
$(this).removeAttr('checked');
$(this).parents('tr').removeClass('context-menu-selection');
} else if (!$(this).prop('checked')) {
$(this).prop('checked', true);
$(this).parents('tr').addClass('context-menu-selection');
}
});
}
function window_size() {
var w;
var h;
if (window.innerWidth) {
w = window.innerWidth;
h = window.innerHeight;
} else if (document.documentElement) {
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
} else {
w = document.body.clientWidth;
h = document.body.clientHeight;
}
return {width: w, height: h};
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.