code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla modelform library jimport('joomla.application.component.modeladmin'); /** * Expert Model */ class ZOrderModelProduct extends JModelAdmin { /** * Method override to check if you can edit an existing record. * * @param array $data An array of input data. * @param string $key The name of the key for the primary key. * * @return boolean * @since 1.6 */ protected function allowEdit($data = array(), $key = 'id') { // Check specific edit permission then general edit permission. return JFactory::getUser()->authorise('core.edit', 'com_zorder.message.'.((int) isset($data[$key]) ? $data[$key] : 0)) or parent::allowEdit($data, $key); } /** * Returns a reference to the a Table object, always creating it. * * @param type The table type to instantiate * @param string A prefix for the table class name. Optional. * @param array Configuration array for model. Optional. * @return JTable A database object * @since 1.6 */ public function getTable($type = 'Product', $prefix = 'ZOrderTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } public function getItem($pk = null) { if ($item = parent::getItem($pk)) { $item->articletext = trim($item->fulltext) != '' ? $item->introtext . "<hr id=\"system-readmore\" />" . $item->fulltext : $item->introtext; } return $item; } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return mixed A JForm object on success, false on failure * @since 1.6 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_zorder.product', 'product', array('control' => 'jform', 'load_data' => $loadData)); //var_dump($this); if (empty($form)) { return false; } return $form; } /** * Method to get the script that have to be included on the form * * @return string Script files */ public function getScript() { return 'administrator/components/com_nrmresearch/models/forms/nrmresearch.js'; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 1.6 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_nrmresearch.edit.product.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } }
google-code/bcv-xh
administrator/components/com_zorder/models/product.php
PHP
gpl-2.0
2,754
include ../../../Makefile.inc CLC_ROOT = ../../../inc all: exe_src exe_src_m2s exe_bin amd_compile m2c_compile run_m2s run_native check_result exe_src: @-$(CC) $(CC_FLAG) *src.c -o exe_src $(CC_INC) $(CC_LIB) > fmod_float16float16.exe_src.log 2>&1 exe_src_m2s: @-$(CC) $(CC_FLAG) -m32 *src.c -o exe_src_m2s $(CC_INC) $(M2S_LIB) > fmod_float16float16.exe_src_m2s.log 2>&1 exe_bin: @-$(CC) $(CC_FLAG) *bin.c -o exe_bin $(CC_INC) $(CC_LIB) > fmod_float16float16.exe_bin.log 2>&1 amd_compile: @-$(AMD_CC) --amd --amd-dump-all --amd-device 11 fmod_float16float16.cl > fmod_float16float16.amdcc.log 2>&1 @-rm -rf /tmp/*.clp && rm -rf /tmp/*_amd_files m2c_compile: @-python compile.py run_m2s: @-M2S_OPENCL_BINARY=./fmod_float16float16.opt.bin $(M2S) --si-sim functional ./exe_src_m2s > m2s.log 2>&1 run_native: @-./exe_src > native.log 2>&1 check_result: @-diff exe_src.result exe_src_m2s.result > check.log 2>&1 clean: rm -rf exe_src exe_src_m2s exe_bin *.ll *.log *files *bin *.s *.bc *.result
xianggong/m2c_unit_test
test/math/fmod_float16float16/Makefile
Makefile
gpl-2.0
1,011
/* KeePass Password Safe - The Open-Source Password Manager Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de> 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms; using KeePass.App; using KeePass.Native; using KeePass.Resources; using KeePass.UI; using KeePassLib; using KeePassLib.Collections; using KeePassLib.Utility; namespace KeePass.Forms { /* public sealed class LvfCommand { private readonly string m_strText; public string Text { get { return m_strText; } } private readonly Action<ListView> m_fAction; public Action<ListView> Action { get { return m_fAction; } } public LvfCommand(string strText, Action<ListView> fAction) { if(strText == null) throw new ArgumentNullException("strText"); if(fAction == null) throw new ArgumentNullException("fAction"); m_strText = strText; m_fAction = fAction; } } */ public partial class ListViewForm : Form { private string m_strTitle = string.Empty; private string m_strSubTitle = string.Empty; private string m_strInfo = string.Empty; private Image m_imgIcon = null; private List<object> m_lData = new List<object>(); private ImageList m_ilIcons = null; private Action<ListView> m_fInit = null; private object m_resItem = null; public object ResultItem { get { return m_resItem; } } private object m_resGroup = null; public object ResultGroup { get { return m_resGroup; } } private bool m_bEnsureForeground = false; public bool EnsureForeground { get { return m_bEnsureForeground; } set { m_bEnsureForeground = value; } } public void InitEx(string strTitle, string strSubTitle, string strInfo, Image imgIcon, List<object> lData, ImageList ilIcons, Action<ListView> fInit) { m_strTitle = (strTitle ?? string.Empty); m_strSubTitle = (strSubTitle ?? string.Empty); m_strInfo = (strInfo ?? string.Empty); m_imgIcon = imgIcon; if(lData != null) m_lData = lData; if(ilIcons != null) m_ilIcons = UIUtil.CloneImageList(ilIcons, true); m_fInit = fInit; } public ListViewForm() { InitializeComponent(); Program.Translation.ApplyTo(this); } private void OnFormLoad(object sender, EventArgs e) { GlobalWindowManager.AddWindow(this); this.Text = m_strTitle; this.Icon = AppIcons.Default; BannerFactory.CreateBannerEx(this, m_bannerImage, m_imgIcon, m_strTitle, m_strSubTitle); Debug.Assert(!m_lblInfo.AutoSize); // For RTL support m_lblInfo.Text = m_strInfo; if(m_strInfo.Length == 0) { int yLabel = m_lblInfo.Location.Y; Point ptList = m_lvMain.Location; Size szList = m_lvMain.Size; m_lblInfo.Visible = false; m_lvMain.Location = new Point(ptList.X, yLabel); m_lvMain.Size = new Size(szList.Width, szList.Height + ptList.Y - yLabel); } UIUtil.SetExplorerTheme(m_lvMain, true); if(m_ilIcons != null) m_lvMain.SmallImageList = m_ilIcons; if(m_fInit != null) { try { m_fInit(m_lvMain); } catch(Exception) { Debug.Assert(false); } } m_lvMain.BeginUpdate(); ListViewGroup lvgCur = null; foreach(object o in m_lData) { if(o == null) { Debug.Assert(false); continue; } ListViewItem lvi = (o as ListViewItem); if(lvi != null) { // Caller should not care about associations Debug.Assert(lvi.ListView == null); Debug.Assert(lvi.Group == null); m_lvMain.Items.Add(lvi); if(lvgCur != null) lvgCur.Items.Add(lvi); Debug.Assert(lvi.ListView == m_lvMain); Debug.Assert(lvi.Group == lvgCur); continue; } ListViewGroup lvg = (o as ListViewGroup); if(lvg != null) { // Caller should not care about associations Debug.Assert(lvg.ListView == null); m_lvMain.Groups.Add(lvg); lvgCur = lvg; Debug.Assert(lvg.ListView == m_lvMain); continue; } Debug.Assert(false); // Unknown data type } m_lvMain.EndUpdate(); if(m_bEnsureForeground) { this.BringToFront(); this.Activate(); } } private void CleanUpEx() { if(m_ilIcons != null) { m_lvMain.SmallImageList = null; // Detach event handlers m_ilIcons.Dispose(); m_ilIcons = null; } } private void OnFormClosed(object sender, FormClosedEventArgs e) { CleanUpEx(); GlobalWindowManager.RemoveWindow(this); } private bool CreateResult() { ListView.SelectedListViewItemCollection lvic = m_lvMain.SelectedItems; if(lvic.Count != 1) { Debug.Assert(false); return false; } ListViewItem lvi = lvic[0]; if(lvi == null) { Debug.Assert(false); return false; } m_resItem = lvi.Tag; m_resGroup = ((lvi.Group != null) ? lvi.Group.Tag : null); return true; } private void ProcessItemSelection() { if(this.DialogResult == DialogResult.OK) return; // Already closing if(CreateResult()) this.DialogResult = DialogResult.OK; } private void OnListItemActivate(object sender, EventArgs e) { ProcessItemSelection(); } // The item activation handler has a slight delay when clicking an // item, thus as a performance optimization we additionally handle // item clicks private void OnListClick(object sender, EventArgs e) { ProcessItemSelection(); } } }
joshuadugie/KeePass-2.x
KeePass/Forms/ListViewForm.cs
C#
gpl-2.0
6,300
FROM debian:wheezy MAINTAINER Foo Bar, foo@bar.com ENV ORG foo ENV APP bar ENV INSTALL_DIR /opt/${ORG}/${APP} ENV PACKAGES wget binutils make csh g++ sed gawk perl zlib1g-dev RUN apt-get update -y && apt-get install -y --no-install-recommends ${PACKAGES} ENV SEQTK https://github.com/avilella/seqtk/archive/sgdp.tar.gz ENV THIRDPARTY_DIR ${INSTALL_DIR}/thirdparty RUN mkdir -p ${THIRDPARTY_DIR} RUN cd ${THIRDPARTY_DIR} # SEQTK RUN mkdir -p ${THIRDPARTY_DIR}/seqtk && cd ${THIRDPARTY_DIR}/seqtk &&\ wget --quiet --no-check-certificate ${SEQTK} --output-document - |\ tar xzf - --directory . --strip-components=1 && \ make # COMPILE HELLO_WORLD # ADD src/hello_world.c ${INSTALL_DIR}/hello_world.c ADD src/ ${INSTALL_DIR}/src RUN mkdir ${INSTALL_DIR}/bin &&\ gcc ${INSTALL_DIR}/src/hello_world.c -o ${INSTALL_DIR}/bin/hello_world ADD scripts/ ${INSTALL_DIR}/scripts WORKDIR ${INSTALL_DIR} # ENTRYPOINT ["./hello_world"] ENTRYPOINT ["./scripts/run_binary.pl", "-i", "./bin/hello_world"]
avilella/bioboxes_playground
Dockerfile
Dockerfile
gpl-2.0
1,015
/* This file is part of the dynarmic project. * Copyright (c) 2016 MerryMage * This software may be used and distributed according to the terms of the GNU * General Public License version 2 or any later version. */ #pragma once #include <type_traits> #include <xbyak.h> #include "backend_x64/jitstate.h" #include "common/common_types.h" #include "dynarmic/callbacks.h" namespace Dynarmic { namespace BackendX64 { class BlockOfCode final : public Xbyak::CodeGenerator { public: explicit BlockOfCode(UserCallbacks cb); /// Clears this block of code and resets code pointer to beginning. void ClearCache(); /// Runs emulated code for approximately `cycles_to_run` cycles. size_t RunCode(JitState* jit_state, CodePtr basic_block, size_t cycles_to_run) const; /// Code emitter: Returns to host void ReturnFromRunCode(bool MXCSR_switch = true); /// Code emitter: Makes guest MXCSR the current MXCSR void SwitchMxcsrOnEntry(); /// Code emitter: Makes saved host MXCSR the current MXCSR void SwitchMxcsrOnExit(); /// Code emitter: Calls the function template <typename FunctionPointer> void CallFunction(FunctionPointer fn) { static_assert(std::is_pointer<FunctionPointer>() && std::is_function<std::remove_pointer_t<FunctionPointer>>(), "Supplied type must be a pointer to a function"); const u64 address = reinterpret_cast<u64>(fn); const u64 distance = address - (getCurr<u64>() + 5); if (distance >= 0x0000000080000000ULL && distance < 0xFFFFFFFF80000000ULL) { // Far call mov(rax, address); call(rax); } else { call(fn); } } Xbyak::Address MFloatPositiveZero32() { return xword[rip + consts.FloatPositiveZero32]; } Xbyak::Address MFloatNegativeZero32() { return xword[rip + consts.FloatNegativeZero32]; } Xbyak::Address MFloatNaN32() { return xword[rip + consts.FloatNaN32]; } Xbyak::Address MFloatNonSignMask32() { return xword[rip + consts.FloatNonSignMask32]; } Xbyak::Address MFloatPositiveZero64() { return xword[rip + consts.FloatPositiveZero64]; } Xbyak::Address MFloatNegativeZero64() { return xword[rip + consts.FloatNegativeZero64]; } Xbyak::Address MFloatNaN64() { return xword[rip + consts.FloatNaN64]; } Xbyak::Address MFloatNonSignMask64() { return xword[rip + consts.FloatNonSignMask64]; } Xbyak::Address MFloatPenultimatePositiveDenormal64() { return xword[rip + consts.FloatPenultimatePositiveDenormal64]; } Xbyak::Address MFloatMinS32() { return xword[rip + consts.FloatMinS32]; } Xbyak::Address MFloatMaxS32() { return xword[rip + consts.FloatMaxS32]; } Xbyak::Address MFloatMinU32() { return xword[rip + consts.FloatMinU32]; } Xbyak::Address MFloatMaxU32() { return xword[rip + consts.FloatMaxU32]; } const void* GetReturnFromRunCodeAddress() const { return return_from_run_code; } const void* GetMemoryReadCallback(size_t bit_size) const { switch (bit_size) { case 8: return read_memory_8; case 16: return read_memory_16; case 32: return read_memory_32; case 64: return read_memory_64; default: return nullptr; } } const void* GetMemoryWriteCallback(size_t bit_size) const { switch (bit_size) { case 8: return write_memory_8; case 16: return write_memory_16; case 32: return write_memory_32; case 64: return write_memory_64; default: return nullptr; } } void int3() { db(0xCC); } void nop(size_t size = 1); void SetCodePtr(CodePtr code_ptr); void EnsurePatchLocationSize(CodePtr begin, size_t size); #ifdef _WIN32 Xbyak::Reg64 ABI_RETURN = rax; Xbyak::Reg64 ABI_PARAM1 = rcx; Xbyak::Reg64 ABI_PARAM2 = rdx; Xbyak::Reg64 ABI_PARAM3 = r8; Xbyak::Reg64 ABI_PARAM4 = r9; #else Xbyak::Reg64 ABI_RETURN = rax; Xbyak::Reg64 ABI_PARAM1 = rdi; Xbyak::Reg64 ABI_PARAM2 = rsi; Xbyak::Reg64 ABI_PARAM3 = rdx; Xbyak::Reg64 ABI_PARAM4 = rcx; #endif private: UserCallbacks cb; struct Consts { Xbyak::Label FloatPositiveZero32; Xbyak::Label FloatNegativeZero32; Xbyak::Label FloatNaN32; Xbyak::Label FloatNonSignMask32; Xbyak::Label FloatPositiveZero64; Xbyak::Label FloatNegativeZero64; Xbyak::Label FloatNaN64; Xbyak::Label FloatNonSignMask64; Xbyak::Label FloatPenultimatePositiveDenormal64; Xbyak::Label FloatMinS32; Xbyak::Label FloatMaxS32; Xbyak::Label FloatMinU32; Xbyak::Label FloatMaxU32; } consts; void GenConstants(); using RunCodeFuncType = void(*)(JitState*, CodePtr); RunCodeFuncType run_code = nullptr; void GenRunCode(); const void* return_from_run_code = nullptr; const void* return_from_run_code_without_mxcsr_switch = nullptr; void GenReturnFromRunCode(); const void* read_memory_8 = nullptr; const void* read_memory_16 = nullptr; const void* read_memory_32 = nullptr; const void* read_memory_64 = nullptr; const void* write_memory_8 = nullptr; const void* write_memory_16 = nullptr; const void* write_memory_32 = nullptr; const void* write_memory_64 = nullptr; void GenMemoryAccessors(); }; } // namespace BackendX64 } // namespace Dynarmic
spixi/dynarmic
src/backend_x64/block_of_code.h
C
gpl-2.0
5,678
<?php /* $Id: index.php 6036 2010-10-02 04:10:36Z ajdonnison $ */ /* {{{ Copyright (c) 2003-2005 The dotProject Development Team <core-developers@dotproject.net> This file is part of dotProject. dotProject 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. dotProject 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 dotProject; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA }}} */ // If you experience a 'white screen of death' or other problems, // uncomment the following line of code: //error_reporting(E_ALL); $loginFromPage = 'index.php'; require_once 'base.php'; clearstatcache(); if (is_file(DP_BASE_DIR . '/includes/config.php')) { require_once DP_BASE_DIR . '/includes/config.php'; } else { echo ('<html><head><meta http-equiv="refresh" content="5; URL=' . DP_BASE_URL . '/install/index.php"></head><body>' . 'Fatal Error. You haven\'t created a config file yet.<br/>' . '<a href="./install/index.php">Click Here To Start Installation and Create One!</a>' . ' (forwarded in 5 sec.)</body></html>'); exit(); } if (!(isset($GLOBALS['OS_WIN']))) { $GLOBALS['OS_WIN'] = (mb_stristr(PHP_OS, 'WIN') !== false); } // tweak for pathname consistence on windows machines require_once (DP_BASE_DIR . '/classes/csscolor.class.php'); // Required before main_functions require_once (DP_BASE_DIR . '/includes/main_functions.php'); require_once (DP_BASE_DIR . '/includes/db_adodb.php'); require_once (DP_BASE_DIR . '/includes/db_connect.php'); require_once (DP_BASE_DIR . '/classes/ui.class.php'); require_once (DP_BASE_DIR . '/classes/permissions.class.php'); require_once (DP_BASE_DIR . '/includes/session.php'); // don't output anything. Usefull for fileviewer.php, gantt.php, etc. $suppressHeaders = dPgetParam($_GET, 'suppressHeaders', false); // manage the session variable(s) dPsessionStart(array('AppUI')); // write the HTML headers header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); //Date in the past header ('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); //always modified header ('Cache-Control: no-cache, must-revalidate, no-store, post-check=0, pre-check=0'); //HTTP/1.1 header ('Pragma: no-cache'); // HTTP/1.0 // check if session has previously been initialised if (!(isset($_SESSION['AppUI'])) || isset($_GET['logout'])) { if (isset($_GET['logout']) && isset($_SESSION['AppUI']->user_id)) { $AppUI =& $_SESSION['AppUI']; $AppUI->registerLogout($AppUI->user_id); addHistory('login', $AppUI->user_id, 'logout', ($AppUI->user_first_name . ' ' . $AppUI->user_last_name)); } $_SESSION['AppUI'] = new CAppUI; } $AppUI =& $_SESSION['AppUI']; $last_insert_id =$AppUI->last_insert_id; $AppUI->checkStyle(); // load the commonly used classes require_once($AppUI->getSystemClass('date')); require_once($AppUI->getSystemClass('dp')); require_once($AppUI->getSystemClass('query')); require_once DP_BASE_DIR.'/misc/debug.php'; //Function for update lost action in user_access_log $AppUI->updateLastAction($last_insert_id); // load default preferences if not logged in if ($AppUI->doLogin()) { $AppUI->loadPrefs(0); } // check is the user needs a new password if (dPgetParam($_POST, 'lostpass', 0)) { $uistyle = dPgetConfig('host_style'); $AppUI->setUserLocale(); @include_once (DP_BASE_DIR . '/locales/' . $AppUI->user_locale . '/locales.php'); @include_once (DP_BASE_DIR . '/locales/core.php'); setlocale(LC_TIME, $AppUI->user_lang); if (dPgetParam($_REQUEST, 'sendpass', 0)) { require (DP_BASE_DIR . '/includes/sendpass.php'); sendNewPass(); } else { require (DP_BASE_DIR . '/style/' . $uistyle . '/lostpass.php'); } exit(); } // check if the user is trying to log in // Note the change to REQUEST instead of POST. This is so that we can // support alternative authentication methods such as the PostNuke // and HTTP auth methods now supported. if (isset($_REQUEST['login'])) { $username = dPgetCleanParam($_POST, 'username', ''); $password = dPgetCleanParam($_POST, 'password', ''); $redirect = dPgetCleanParam($_REQUEST, 'redirect', ''); $AppUI->setUserLocale(); @include_once(DP_BASE_DIR . '/locales/' . $AppUI->user_locale . '/locales.php'); @include_once DP_BASE_DIR . '/locales/core.php'; $ok = $AppUI->login($username, $password); if (!$ok) { $AppUI->setMsg('Login Failed'); } else { //Register login in user_acces_log $AppUI->registerLogin(); // get permissions for user $AppUI->getUserPermissions(); } addHistory('login', $AppUI->user_id, 'login', ($AppUI->user_first_name . ' ' . $AppUI->user_last_name)); $AppUI->redirect($redirect); } // supported since PHP 4.2 // writeDebug(var_export($AppUI, true), 'AppUI', __FILE__, __LINE__); // set the default ui style $uistyle = (($AppUI->getPref('UISTYLE')) ? $AppUI->getPref('UISTYLE') : dPgetConfig('host_style')); // clear out main url parameters $m = ''; $a = ''; $u = ''; // check if we are logged in if ($AppUI->doLogin()) { // load basic locale settings $AppUI->setUserLocale(); @include_once('./locales/' . $AppUI->user_locale . '/locales.php'); @include_once('./locales/core.php'); setlocale(LC_TIME, $AppUI->user_lang); $redirect = (($_SERVER['QUERY_STRING']) ? strip_tags($_SERVER['QUERY_STRING']) : ''); if (mb_strpos($redirect, 'logout') !== false) { $redirect = ''; } if (isset($locale_char_set)) { header('Content-type: text/html;charset=' . $locale_char_set); } require (DP_BASE_DIR . '/style/' . $uistyle . '/login.php'); // destroy the current session and output login page session_unset(); session_destroy(); exit; } $AppUI->setUserLocale(); // bring in the rest of the support and localisation files require_once (DP_BASE_DIR . '/includes/permissions.php'); $def_a = 'index'; if (!(isset($_GET['m']) || empty($dPconfig['default_view_m']))) { $m = $dPconfig['default_view_m']; $def_a = ((!empty($dPconfig['default_view_a'])) ? $dPconfig['default_view_a'] : $def_a); $tab = $dPconfig['default_view_tab']; } else { // set the module from the url $m = $AppUI->checkFileName(dPgetCleanParam($_GET, 'm', getReadableModule())); } // set the action from the url $a = $AppUI->checkFileName(dPgetCleanParam($_GET, 'a', $def_a)); /* This check for $u implies that a file located in a subdirectory of higher depth than 1 * in relation to the module base can't be executed. So it would'nt be possible to * run for example the file module/directory1/directory2/file.php * Also it won't be possible to run modules/module/abc.zyz.class.php for that dots are * not allowed in the request parameters. */ $u = $AppUI->checkFileName(dPgetCleanParam($_GET, 'u', '')); // load module based locale settings @include_once (DP_BASE_DIR . '/locales/' . $AppUI->user_locale . '/locales.php'); @include_once (DP_BASE_DIR . '/locales/core.php'); setlocale(LC_TIME, $AppUI->user_lang); $m_config = dPgetConfig($m); @include_once (DP_BASE_DIR.'/functions/' . $m . '_func.php'); // TODO: canRead/Edit assignements should be moved into each file // check overall module permissions // these can be further modified by the included action files $canAccess = getPermission($m, 'access'); $canRead = getPermission($m, 'view'); $canEdit = getPermission($m, 'edit'); $canAuthor = getPermission($m, 'add'); $canDelete = getPermission($m, 'delete'); if (!$suppressHeaders) { // output the character set header if (isset($locale_char_set)) { header('Content-type: text/html;charset='.$locale_char_set); } } // include the module class file - we use file_exists instead of @ so // that any parse errors in the file are reported, rather than errors // further down the track. $modclass = $AppUI->getModuleClass($m); if (file_exists($modclass)) { include_once($modclass); } if ($u && file_exists(DP_BASE_DIR . '/modules/' . $m . '/' . $u . '/' . $u . '.class.php')) { include_once (DP_BASE_DIR . '/modules/' . $m . '/' . $u . '/' . $u . '.class.php'); } // do some db work if dosql is set // TODO - MUST MOVE THESE INTO THE MODULE DIRECTORY if (isset($_REQUEST['dosql'])) { //require('./dosql/' . $_REQUEST['dosql'] . '.php'); require (DP_BASE_DIR . '/modules/' . $m . '/' . ($u ? ($u.'/') : '') . $AppUI->checkFileName($_REQUEST['dosql']) . '.php'); } // start output proper include (DP_BASE_DIR . '/style/' . $uistyle . '/overrides.php'); ob_start(); if (!$suppressHeaders) { require (DP_BASE_DIR . '/style/' . $uistyle . '/header.php'); } if (!(isset($_SESSION['all_tabs'][$m]))) { // For some reason on some systems if you don't set this up // first you get recursive pointers to the all_tabs array, creating // phantom tabs. if (! isset($_SESSION['all_tabs'])) { $_SESSION['all_tabs'] = array(); } $_SESSION['all_tabs'][$m] = array(); $all_tabs =& $_SESSION['all_tabs'][$m]; foreach ($AppUI->getActiveModules() as $dir => $module) { if (!(getPermission($dir, 'access'))) { continue; } $modules_tabs = $AppUI->readFiles((DP_BASE_DIR . '/modules/' . $dir . '/'), ('^' . $m . '_tab.*\.php')); foreach ($modules_tabs as $mod_tab) { // Get the name as the subextension // cut the module_tab. and the .php parts of the filename // (begining and end) $nameparts = explode('.', $mod_tab); $filename = mb_substr($mod_tab, 0, -4); if (count($nameparts) > 3) { $file = $nameparts[1]; if (!(isset($all_tabs[$file]))) { $all_tabs[$file] = array(); } $arr =& $all_tabs[$file]; $name = $nameparts[2]; } else { $arr =& $all_tabs; $name = $nameparts[1]; } $arr[] = array('name' => ucfirst(str_replace('_', ' ', $name)), 'file' => (DP_BASE_DIR . '/modules/' . $dir . '/' . $filename), 'module' => $dir); /* * Don't forget to unset $arr again! $arr is likely to be used in the sequel declaring * any temporary array. This may lead to strange bugs with disappearing tabs(cf. #1767). * @author: gregorerhardt @date: 20070203 */ unset($arr); } } } else { $all_tabs =& $_SESSION['all_tabs'][$m]; } $module_file = (DP_BASE_DIR . '/modules/' . $m . '/' . (($u) ? ($u.'/') : '') . $a . '.php'); if (file_exists($module_file)) { require $module_file; } else { //TODO: make this part of the public module? //TODO: internationalise the string. $titleBlock = new CTitleBlock('Warning', 'log-error.gif'); $titleBlock->show(); echo $AppUI->_('Missing file. Possible Module "' . $m . '" missing!'); } if (!$suppressHeaders) { echo ('<iframe name="thread" src="' . DP_BASE_URL . '/modules/index.html" width="0" height="0" frameborder="0"></iframe>'); require (DP_BASE_DIR . '/style/' . $uistyle . '/footer.php'); } ob_end_flush(); ?>
Fightmander/Hydra
index.php
PHP
gpl-2.0
11,566
#include "QtPObject.h"
stefaandr/qt-accessory
QtP/QtPObject.cpp
C++
gpl-2.0
24
/* * Copyright 2011-2020 Ping Identity Corporation * All Rights Reserved. */ /* * Copyright 2011-2020 Ping Identity Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2011-2020 Ping Identity Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (GPLv2 only) * or the terms of the GNU Lesser General Public License (LGPLv2.1 only) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. */ package com.unboundid.ldap.sdk; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import com.unboundid.asn1.ASN1OctetString; import com.unboundid.util.Mutable; import com.unboundid.util.NotNull; import com.unboundid.util.Nullable; import com.unboundid.util.StaticUtils; import com.unboundid.util.ThreadSafety; import com.unboundid.util.ThreadSafetyLevel; import com.unboundid.util.Validator; /** * This class provides a data structure that may be used to hold a number of * properties that may be used during processing for a SASL GSSAPI bind * operation. */ @Mutable() @ThreadSafety(level=ThreadSafetyLevel.NOT_THREADSAFE) public final class GSSAPIBindRequestProperties implements Serializable { /** * The serial version UID for this serializable class. */ private static final long serialVersionUID = 6872295509330315713L; // The password for the GSSAPI bind request. @Nullable private ASN1OctetString password; // Indicates whether to enable JVM-level debugging for GSSAPI processing. private boolean enableGSSAPIDebugging; // Indicates whether the client should be considered the GSSAPI initiator or // the acceptor. @Nullable private Boolean isInitiator; // Indicates whether to attempt to refresh the configuration before the JAAS // login method is called. private boolean refreshKrb5Config; // Indicates whether to attempt to renew the client's existing ticket-granting // ticket if authentication uses an existing Kerberos session. private boolean renewTGT; // Indicates whether to require that the credentials be obtained from the // ticket cache such that authentication will fail if the client does not have // an existing Kerberos session. private boolean requireCachedCredentials; // Indicates whether to allow the to obtain the credentials to be obtained // from a keytab. private boolean useKeyTab; // Indicates whether to allow the client to use credentials that are outside // of the current subject. private boolean useSubjectCredentialsOnly; // Indicates whether to enable the use of a ticket cache. private boolean useTicketCache; // The SASL quality of protection value(s) allowed for the DIGEST-MD5 bind // request. @NotNull private List<SASLQualityOfProtection> allowedQoP; // The names of any system properties that should not be altered by GSSAPI // processing. @NotNull private Set<String> suppressedSystemProperties; // The authentication ID string for the GSSAPI bind request. @Nullable private String authenticationID; // The authorization ID string for the GSSAPI bind request, if available. @Nullable private String authorizationID; // The path to the JAAS configuration file to use for bind processing. @Nullable private String configFilePath; // The name that will be used to identify this client in the JAAS framework. @NotNull private String jaasClientName; // The KDC address for the GSSAPI bind request, if available. @Nullable private String kdcAddress; // The path to the keytab file to use if useKeyTab is true. @Nullable private String keyTabPath; // The realm for the GSSAPI bind request, if available. @Nullable private String realm; // The server name to use when creating the SASL client. @Nullable private String saslClientServerName; // The protocol that should be used in the Kerberos service principal for // the server system. @NotNull private String servicePrincipalProtocol; // The path to the Kerberos ticket cache to use. @Nullable private String ticketCachePath; /** * Creates a new set of GSSAPI bind request properties with the provided * information. * * @param authenticationID The authentication ID for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. * @param password The password for the GSSAPI bind request. It may * be {@code null} if an existing Kerberos session * should be used. */ public GSSAPIBindRequestProperties(@Nullable final String authenticationID, @Nullable final String password) { this(authenticationID, null, (password == null ? null : new ASN1OctetString(password)), null, null, null); } /** * Creates a new set of GSSAPI bind request properties with the provided * information. * * @param authenticationID The authentication ID for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. * @param password The password for the GSSAPI bind request. It may * be {@code null} if an existing Kerberos session * should be used. */ public GSSAPIBindRequestProperties(@Nullable final String authenticationID, @Nullable final byte[] password) { this(authenticationID, null, (password == null ? null : new ASN1OctetString(password)), null, null, null); } /** * Creates a new set of GSSAPI bind request properties with the provided * information. * * @param authenticationID The authentication ID for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. * @param authorizationID The authorization ID for the GSSAPI bind request. * It may be {@code null} if the authorization ID * should be the same as the authentication ID. * @param password The password for the GSSAPI bind request. It may * be {@code null} if an existing Kerberos session * should be used. * @param realm The realm to use for the authentication. It may * be {@code null} to attempt to use the default * realm from the system configuration. * @param kdcAddress The address of the Kerberos key distribution * center. It may be {@code null} to attempt to use * the default KDC from the system configuration. * @param configFilePath The path to the JAAS configuration file to use * for the authentication processing. It may be * {@code null} to use the default JAAS * configuration. */ GSSAPIBindRequestProperties(@Nullable final String authenticationID, @Nullable final String authorizationID, @Nullable final ASN1OctetString password, @Nullable final String realm, @Nullable final String kdcAddress, @Nullable final String configFilePath) { this.authenticationID = authenticationID; this.authorizationID = authorizationID; this.password = password; this.realm = realm; this.kdcAddress = kdcAddress; this.configFilePath = configFilePath; servicePrincipalProtocol = "ldap"; enableGSSAPIDebugging = false; jaasClientName = "GSSAPIBindRequest"; isInitiator = null; refreshKrb5Config = false; renewTGT = false; useKeyTab = false; useSubjectCredentialsOnly = true; useTicketCache = true; requireCachedCredentials = false; saslClientServerName = null; keyTabPath = null; ticketCachePath = null; suppressedSystemProperties = Collections.emptySet(); allowedQoP = Collections.singletonList(SASLQualityOfProtection.AUTH); } /** * Retrieves the authentication ID for the GSSAPI bind request, if defined. * * @return The authentication ID for the GSSAPI bind request, or {@code null} * if an existing Kerberos session should be used. */ @Nullable() public String getAuthenticationID() { return authenticationID; } /** * Sets the authentication ID for the GSSAPI bind request. * * @param authenticationID The authentication ID for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. */ public void setAuthenticationID(@Nullable final String authenticationID) { this.authenticationID = authenticationID; } /** * Retrieves the authorization ID for the GSSAPI bind request, if defined. * * @return The authorizationID for the GSSAPI bind request, or {@code null} * if the authorization ID should be the same as the authentication * ID. */ @Nullable() public String getAuthorizationID() { return authorizationID; } /** * Specifies the authorization ID for the GSSAPI bind request. * * @param authorizationID The authorization ID for the GSSAPI bind request. * It may be {@code null} if the authorization ID * should be the same as the authentication ID. */ public void setAuthorizationID(@Nullable final String authorizationID) { this.authorizationID = authorizationID; } /** * Retrieves the password that should be used for the GSSAPI bind request, if * defined. * * @return The password that should be used for the GSSAPI bind request, or * {@code null} if an existing Kerberos session should be used. */ @Nullable() public ASN1OctetString getPassword() { return password; } /** * Specifies the password that should be used for the GSSAPI bind request. * * @param password The password that should be used for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. */ public void setPassword(@Nullable final String password) { if (password == null) { this.password = null; } else { this.password = new ASN1OctetString(password); } } /** * Specifies the password that should be used for the GSSAPI bind request. * * @param password The password that should be used for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. */ public void setPassword(@Nullable final byte[] password) { if (password == null) { this.password = null; } else { this.password = new ASN1OctetString(password); } } /** * Specifies the password that should be used for the GSSAPI bind request. * * @param password The password that should be used for the GSSAPI bind * request. It may be {@code null} if an existing * Kerberos session should be used. */ public void setPassword(@Nullable final ASN1OctetString password) { this.password = password; } /** * Retrieves the realm to use for the GSSAPI bind request, if defined. * * @return The realm to use for the GSSAPI bind request, or {@code null} if * the request should attempt to use the default realm from the * system configuration. */ @Nullable() public String getRealm() { return realm; } /** * Specifies the realm to use for the GSSAPI bind request. * * @param realm The realm to use for the GSSAPI bind request. It may be * {@code null} if the request should attempt to use the * default realm from the system configuration. */ public void setRealm(@Nullable final String realm) { this.realm = realm; } /** * Retrieves the list of allowed qualities of protection that may be used for * communication that occurs on the connection after the authentication has * completed, in order from most preferred to least preferred. * * @return The list of allowed qualities of protection that may be used for * communication that occurs on the connection after the * authentication has completed, in order from most preferred to * least preferred. */ @NotNull() public List<SASLQualityOfProtection> getAllowedQoP() { return allowedQoP; } /** * Specifies the list of allowed qualities of protection that may be used for * communication that occurs on the connection after the authentication has * completed, in order from most preferred to least preferred. * * @param allowedQoP The list of allowed qualities of protection that may be * used for communication that occurs on the connection * after the authentication has completed, in order from * most preferred to least preferred. If this is * {@code null} or empty, then a list containing only the * {@link SASLQualityOfProtection#AUTH} quality of * protection value will be used. */ public void setAllowedQoP( @Nullable final List<SASLQualityOfProtection> allowedQoP) { if ((allowedQoP == null) || allowedQoP.isEmpty()) { this.allowedQoP = Collections.singletonList(SASLQualityOfProtection.AUTH); } else { this.allowedQoP = Collections.unmodifiableList(new ArrayList<>(allowedQoP)); } } /** * Specifies the list of allowed qualities of protection that may be used for * communication that occurs on the connection after the authentication has * completed, in order from most preferred to least preferred. * * @param allowedQoP The list of allowed qualities of protection that may be * used for communication that occurs on the connection * after the authentication has completed, in order from * most preferred to least preferred. If this is * {@code null} or empty, then a list containing only the * {@link SASLQualityOfProtection#AUTH} quality of * protection value will be used. */ public void setAllowedQoP( @Nullable final SASLQualityOfProtection... allowedQoP) { setAllowedQoP(StaticUtils.toList(allowedQoP)); } /** * Retrieves the address to use for the Kerberos key distribution center, * if defined. * * @return The address to use for the Kerberos key distribution center, or * {@code null} if request should attempt to determine the KDC * address from the system configuration. */ @Nullable() public String getKDCAddress() { return kdcAddress; } /** * Specifies the address to use for the Kerberos key distribution center. * * @param kdcAddress The address to use for the Kerberos key distribution * center. It may be {@code null} if the request should * attempt to determine the KDC address from the system * configuration. */ public void setKDCAddress(@Nullable final String kdcAddress) { this.kdcAddress = kdcAddress; } /** * Retrieves the name that will be used to identify this client in the JAAS * framework. * * @return The name that will be used to identify this client in the JAAS * framework. */ @NotNull() public String getJAASClientName() { return jaasClientName; } /** * Specifies the name that will be used to identify this client in the JAAS * framework. * * @param jaasClientName The name that will be used to identify this client * in the JAAS framework. It must not be * {@code null} or empty. */ public void setJAASClientName(@NotNull final String jaasClientName) { Validator.ensureNotNull(jaasClientName); this.jaasClientName = jaasClientName; } /** * Retrieves the path to a JAAS configuration file that should be used when * processing the GSSAPI bind request, if defined. * * @return The path to a JAAS configuration file that should be used when * processing the GSSAPI bind request, or {@code null} if a JAAS * configuration file should be automatically constructed for the * bind request. */ @Nullable() public String getConfigFilePath() { return configFilePath; } /** * Specifies the path to a JAAS configuration file that should be used when * processing the GSSAPI bind request. * * @param configFilePath The path to a JAAS configuration file that should * be used when processing the GSSAPI bind request. * It may be {@code null} if a configuration file * should be automatically constructed for the bind * request. */ public void setConfigFilePath(@Nullable final String configFilePath) { this.configFilePath = configFilePath; } /** * Retrieves the server name that should be used when creating the Java * {@code SaslClient}, if one is defined. * * @return The server name that should be used when creating the Java * {@code SaslClient}, or {@code null} if none is defined and the * {@code SaslClient} should use the address specified when * establishing the connection. */ @Nullable() public String getSASLClientServerName() { return saslClientServerName; } /** * Specifies the server name that should be used when creating the Java * {@code SaslClient}. * * @param saslClientServerName The server name that should be used when * creating the Java {@code SaslClient}. It may * be {@code null} to indicate that the * {@code SaslClient} should use the address * specified when establishing the connection. */ public void setSASLClientServerName( @Nullable final String saslClientServerName) { this.saslClientServerName = saslClientServerName; } /** * Retrieves the protocol specified in the service principal that the * directory server uses for its communication with the KDC. The service * principal is usually something like "ldap/directory.example.com", where * "ldap" is the protocol and "directory.example.com" is the fully-qualified * address of the directory server system, but some servers may allow * authentication with a service principal with a protocol other than "ldap". * * @return The protocol specified in the service principal that the directory * server uses for its communication with the KDC. */ @NotNull() public String getServicePrincipalProtocol() { return servicePrincipalProtocol; } /** * Specifies the protocol specified in the service principal that the * directory server uses for its communication with the KDC. This should * generally be "ldap", but some servers may allow a service principal with a * protocol other than "ldap". * * @param servicePrincipalProtocol The protocol specified in the service * principal that the directory server uses * for its communication with the KDC. */ public void setServicePrincipalProtocol( @NotNull final String servicePrincipalProtocol) { Validator.ensureNotNull(servicePrincipalProtocol); this.servicePrincipalProtocol = servicePrincipalProtocol; } /** * Indicates whether to refresh the configuration before the JAAS * {@code login} method is called. * * @return {@code true} if the GSSAPI implementation should refresh the * configuration before the JAAS {@code login} method is called, or * {@code false} if not. */ public boolean refreshKrb5Config() { return refreshKrb5Config; } /** * Specifies whether to refresh the configuration before the JAAS * {@code login} method is called. * * @param refreshKrb5Config Indicates whether to refresh the configuration * before the JAAS {@code login} method is called. */ public void setRefreshKrb5Config(final boolean refreshKrb5Config) { this.refreshKrb5Config = refreshKrb5Config; } /** * Indicates whether to allow the client to use credentials that are outside * of the current subject, obtained via some system-specific mechanism. * * @return {@code true} if the client will only be allowed to use credentials * that are within the current subject, or {@code false} if the * client will be allowed to use credentials outside the current * subject. */ public boolean useSubjectCredentialsOnly() { return useSubjectCredentialsOnly; } /** * Specifies whether to allow the client to use credentials that are outside * the current subject. If this is {@code false}, then a system-specific * mechanism may be used in an attempt to obtain credentials from an * existing session. * * @param useSubjectCredentialsOnly Indicates whether to allow the client to * use credentials that are outside of the * current subject. */ public void setUseSubjectCredentialsOnly( final boolean useSubjectCredentialsOnly) { this.useSubjectCredentialsOnly = useSubjectCredentialsOnly; } /** * Indicates whether to use a keytab to obtain the user credentials. * * @return {@code true} if the GSSAPI login attempt should use a keytab to * obtain the user credentials, or {@code false} if not. */ public boolean useKeyTab() { return useKeyTab; } /** * Specifies whether to use a keytab to obtain the user credentials. * * @param useKeyTab Indicates whether to use a keytab to obtain the user * credentials. */ public void setUseKeyTab(final boolean useKeyTab) { this.useKeyTab = useKeyTab; } /** * Retrieves the path to the keytab file from which to obtain the user * credentials. This will only be used if {@link #useKeyTab} returns * {@code true}. * * @return The path to the keytab file from which to obtain the user * credentials, or {@code null} if the default keytab location should * be used. */ @Nullable() public String getKeyTabPath() { return keyTabPath; } /** * Specifies the path to the keytab file from which to obtain the user * credentials. * * @param keyTabPath The path to the keytab file from which to obtain the * user credentials. It may be {@code null} if the * default keytab location should be used. */ public void setKeyTabPath(@Nullable final String keyTabPath) { this.keyTabPath = keyTabPath; } /** * Indicates whether to enable the use of a ticket cache to to avoid the need * to supply credentials if the client already has an existing Kerberos * session. * * @return {@code true} if a ticket cache may be used to take advantage of an * existing Kerberos session, or {@code false} if Kerberos * credentials should always be provided. */ public boolean useTicketCache() { return useTicketCache; } /** * Specifies whether to enable the use of a ticket cache to to avoid the need * to supply credentials if the client already has an existing Kerberos * session. * * @param useTicketCache Indicates whether to enable the use of a ticket * cache to to avoid the need to supply credentials if * the client already has an existing Kerberos * session. */ public void setUseTicketCache(final boolean useTicketCache) { this.useTicketCache = useTicketCache; } /** * Indicates whether GSSAPI authentication should only occur using an existing * Kerberos session. * * @return {@code true} if GSSAPI authentication should only use an existing * Kerberos session and should fail if the client does not have an * existing session, or {@code false} if the client will be allowed * to create a new session if one does not already exist. */ public boolean requireCachedCredentials() { return requireCachedCredentials; } /** * Specifies whether an GSSAPI authentication should only occur using an * existing Kerberos session. * * @param requireCachedCredentials Indicates whether an existing Kerberos * session will be required for * authentication. If {@code true}, then * authentication will fail if the client * does not already have an existing * Kerberos session. This will be ignored * if {@code useTicketCache} is false. */ public void setRequireCachedCredentials( final boolean requireCachedCredentials) { this.requireCachedCredentials = requireCachedCredentials; } /** * Retrieves the path to the Kerberos ticket cache file that should be used * during authentication, if defined. * * @return The path to the Kerberos ticket cache file that should be used * during authentication, or {@code null} if the default ticket cache * file should be used. */ @Nullable() public String getTicketCachePath() { return ticketCachePath; } /** * Specifies the path to the Kerberos ticket cache file that should be used * during authentication. * * @param ticketCachePath The path to the Kerberos ticket cache file that * should be used during authentication. It may be * {@code null} if the default ticket cache file * should be used. */ public void setTicketCachePath(@Nullable final String ticketCachePath) { this.ticketCachePath = ticketCachePath; } /** * Indicates whether to attempt to renew the client's ticket-granting ticket * (TGT) if an existing Kerberos session is used to authenticate. * * @return {@code true} if the client should attempt to renew its * ticket-granting ticket if the authentication is processed using an * existing Kerberos session, or {@code false} if not. */ public boolean renewTGT() { return renewTGT; } /** * Specifies whether to attempt to renew the client's ticket-granting ticket * (TGT) if an existing Kerberos session is used to authenticate. * * @param renewTGT Indicates whether to attempt to renew the client's * ticket-granting ticket if an existing Kerberos session is * used to authenticate. */ public void setRenewTGT(final boolean renewTGT) { this.renewTGT = renewTGT; } /** * Indicates whether the client should be configured so that it explicitly * indicates whether it is the initiator or the acceptor. * * @return {@code Boolean.TRUE} if the client should explicitly indicate that * it is the GSSAPI initiator, {@code Boolean.FALSE} if the client * should explicitly indicate that it is the GSSAPI acceptor, or * {@code null} if the client should not explicitly indicate either * state (which is the default if the {@link #setIsInitiator} method * has not been called). */ @Nullable() public Boolean getIsInitiator() { return isInitiator; } /** * Specifies whether the client should explicitly indicate whether it is the * GSSAPI initiator or acceptor. * * @param isInitiator Indicates whether the client should be considered the * GSSAPI initiator. A value of {@code Boolean.TRUE} * means the client should explicitly indicate that it is * the GSSAPI initiator. A value of * {@code Boolean.FALSE} means the client should * explicitly indicate that it is the GSSAPI acceptor. A * value of {@code null} means that the client will not * explicitly indicate one way or the other (although * this behavior will only apply to Sun/Oracle-based * implementations; on the IBM implementation, the client * will always be the initiator unless explicitly * configured otherwise). */ public void setIsInitiator(@Nullable final Boolean isInitiator) { this.isInitiator = isInitiator; } /** * Retrieves a set of system properties that will not be altered by GSSAPI * processing. * * @return A set of system properties that will not be altered by GSSAPI * processing. */ @NotNull() public Set<String> getSuppressedSystemProperties() { return suppressedSystemProperties; } /** * Specifies a set of system properties that will not be altered by GSSAPI * processing. This should generally only be used in cases in which the * specified system properties are known to already be set correctly for the * desired authentication processing. * * @param suppressedSystemProperties A set of system properties that will * not be altered by GSSAPI processing. * It may be {@code null} or empty to * indicate that no properties should be * suppressed. */ public void setSuppressedSystemProperties( @Nullable final Collection<String> suppressedSystemProperties) { if (suppressedSystemProperties == null) { this.suppressedSystemProperties = Collections.emptySet(); } else { this.suppressedSystemProperties = Collections.unmodifiableSet( new LinkedHashSet<>(suppressedSystemProperties)); } } /** * Indicates whether JVM-level debugging should be enabled for GSSAPI bind * processing. If this is enabled, then debug information may be written to * standard error when performing GSSAPI processing that could be useful for * debugging authentication problems. * * @return {@code true} if JVM-level debugging should be enabled for GSSAPI * bind processing, or {@code false} if not. */ public boolean enableGSSAPIDebugging() { return enableGSSAPIDebugging; } /** * Specifies whether JVM-level debugging should be enabled for GSSAPI bind * processing. If this is enabled, then debug information may be written to * standard error when performing GSSAPI processing that could be useful for * debugging authentication problems. * * @param enableGSSAPIDebugging Specifies whether JVM-level debugging should * be enabled for GSSAPI bind processing. */ public void setEnableGSSAPIDebugging(final boolean enableGSSAPIDebugging) { this.enableGSSAPIDebugging = enableGSSAPIDebugging; } /** * Retrieves a string representation of the GSSAPI bind request properties. * * @return A string representation of the GSSAPI bind request properties. */ @Override() @NotNull() public String toString() { final StringBuilder buffer = new StringBuilder(); toString(buffer); return buffer.toString(); } /** * Appends a string representation of the GSSAPI bind request properties to * the provided buffer. * * @param buffer The buffer to which the information should be appended. */ public void toString(@NotNull final StringBuilder buffer) { buffer.append("GSSAPIBindRequestProperties("); if (authenticationID != null) { buffer.append("authenticationID='"); buffer.append(authenticationID); buffer.append("', "); } if (authorizationID != null) { buffer.append("authorizationID='"); buffer.append(authorizationID); buffer.append("', "); } if (realm != null) { buffer.append("realm='"); buffer.append(realm); buffer.append("', "); } buffer.append("qop='"); buffer.append(SASLQualityOfProtection.toString(allowedQoP)); buffer.append("', "); if (kdcAddress != null) { buffer.append("kdcAddress='"); buffer.append(kdcAddress); buffer.append("', "); } buffer.append(", refreshKrb5Config="); buffer.append(refreshKrb5Config); buffer.append(", useSubjectCredentialsOnly="); buffer.append(useSubjectCredentialsOnly); buffer.append(", useKeyTab="); buffer.append(useKeyTab); buffer.append(", "); if (keyTabPath != null) { buffer.append("keyTabPath='"); buffer.append(keyTabPath); buffer.append("', "); } if (useTicketCache) { buffer.append("useTicketCache=true, requireCachedCredentials="); buffer.append(requireCachedCredentials); buffer.append(", renewTGT="); buffer.append(renewTGT); buffer.append(", "); if (ticketCachePath != null) { buffer.append("ticketCachePath='"); buffer.append(ticketCachePath); buffer.append("', "); } } else { buffer.append("useTicketCache=false, "); } if (isInitiator != null) { buffer.append("isInitiator="); buffer.append(isInitiator); buffer.append(", "); } buffer.append("jaasClientName='"); buffer.append(jaasClientName); buffer.append("', "); if (configFilePath != null) { buffer.append("configFilePath='"); buffer.append(configFilePath); buffer.append("', "); } if (saslClientServerName != null) { buffer.append("saslClientServerName='"); buffer.append(saslClientServerName); buffer.append("', "); } buffer.append("servicePrincipalProtocol='"); buffer.append(servicePrincipalProtocol); buffer.append("', suppressedSystemProperties={"); final Iterator<String> propIterator = suppressedSystemProperties.iterator(); while (propIterator.hasNext()) { buffer.append('\''); buffer.append(propIterator.next()); buffer.append('\''); if (propIterator.hasNext()) { buffer.append(", "); } } buffer.append("}, enableGSSAPIDebugging="); buffer.append(enableGSSAPIDebugging); buffer.append(')'); } }
UnboundID/ldapsdk
src/com/unboundid/ldap/sdk/GSSAPIBindRequestProperties.java
Java
gpl-2.0
37,081
/** * JBZoo App is universal Joomla CCK, application for YooTheme Zoo component * * @package jbzoo * @version 2.x Pro * @author JBZoo App http://jbzoo.com * @copyright Copyright (C) JBZoo.com, All rights reserved. * @license http://jbzoo.com/license-pro.php JBZoo Licence * @coder Alexander Oganov <t_tapak@yahoo.com> */ ; (function ($, window, document, undefined) { $.fn.Directories = function (options) { var args = arguments, method = args[0] ? args[0] : null, $this = $(this), input = $this; this.options = $.extend({ url : "", title : "Folders", mode : "folder", msgDelete: "Delete" }, method); var finder = $('<div class="finder" />') .insertAfter('body') .finder(this.options) .delegate("a", "click", function (e) { finder.find("li").removeClass("selected"); var li = $(this).parent().addClass("selected"); if (options.mode != "file" || li.hasClass("file")) { $this.focus().val(li.data("path")).blur() } }); var widget = finder.dialog($.extend({ autoOpen : false, resizable: false, open : function () { widget.position({ of: handle, my: "center top", at: "center bottom" }) } }, this.options)).dialog("widget"); var handle = $('<span title="' + options.title + '" class="' + options.mode + 's" />') .insertAfter(input) .bind("click", function () { finder.dialog(finder.dialog("isOpen") ? "close" : "open") } ); $('<span title="' + options.msgDelete + '" class="delete-file" />') .insertAfter(handle) .bind("click", function () { input.val("") } ); $("body").bind("click", function (event) { if (finder.dialog("isOpen") && !handle.is(event.target) && !widget.find(event.target).length) { finder.dialog("close") } }) }; })(jQuery, window, document);
alexmixaylov/real
media/zoo/applications/jbuniversal/cart-elements/email/attach/assets/js/attach.js
JavaScript
gpl-2.0
2,410
#include "platform.h" #include "lolevel.h" //These functions now are part of platform/a495/lib.c /* char *hook_raw_image_addr() { return (char*) 0x10E52420; // Ok, ROM:FFCE9A44 } long hook_raw_size() { return 0xEC04F0; // "CRAW BUFF SIZE" } // Live picture buffer (shoot not pressed) void *vid_get_viewport_live_fb() { return (void*)0; //void **fb=(void **)0x3E80; // ? //unsigned char buff = *((unsigned char*)0x3CF0); // sub_FFC87F0C //if (buff == 0) buff = 2; else buff--; //return fb[buff]; } // OSD buffer void *vid_get_bitmap_fb() { return (void*)0x10361000; // "BmpDDev.c", 0xFFCD1DD4 } // Live picture buffer (shoot half-pressed) void *vid_get_viewport_fb() { return (void*)0x10648CC0; // "VRAM Address" sub_FFCA6830 } void *vid_get_viewport_fb_d() { return (void*)(*(int*)(0x2540+0x54)); // sub_FFC528C0 / sub_FFC53554? } long vid_get_viewport_height() { return 240; } char *camera_jpeg_count_str() { return (char*)0x7486C; // ROM:FFD72194 "9999" } */
boyska/chdkripto
platform/a495/sub/100e/lib.c
C
gpl-2.0
1,010
/* * Copyright (c) 2012-2016 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * 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. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ #ifndef WLAN_QCT_TLI_H #define WLAN_QCT_TLI_H /*=========================================================================== W L A N T R A N S P O R T L A Y E R I N T E R N A L A P I DESCRIPTION This file contains the internal declarations used within wlan transport layer module. ===========================================================================*/ /*=========================================================================== EDIT HISTORY FOR FILE This section contains comments describing changes made to the module. Notice that changes are listed in reverse chronological order. $Header:$ $DateTime: $ $Author: $ when who what, where, why -------- --- ---------------------------------------------------------- 08/19/13 rajekuma Added RMC support in TL 02/19/10 bad Fixed 802.11 to 802.3 ft issues with WAPI 01/14/10 rnair Fixed the byte order for the WAI packet type. 01/08/10 lti Added TL Data Caching 10/09/09 rnair Add support for WAPI 02/02/09 sch Add Handoff support 12/09/08 lti Fixes for AMSS compilation 12/02/08 lti Fix fo trigger frame generation 10/31/08 lti Fix fo TL tx suspend 10/01/08 lti Merged in fixes from reordering 09/05/08 lti Fixes following QOS unit testing 08/06/08 lti Added QOS support 07/18/08 lti Fixes following integration Added frame translation 06/26/08 lti Fixes following unit testing 05/05/08 lti Created module. ===========================================================================*/ /*=========================================================================== INCLUDE FILES FOR MODULE ===========================================================================*/ /*---------------------------------------------------------------------------- * Include Files * -------------------------------------------------------------------------*/ #include "vos_packet.h" #include "vos_api.h" #include "vos_timer.h" #include "vos_mq.h" #include "vos_list.h" #include "wlan_qct_tl.h" #include "pmcApi.h" #include "wlan_qct_hal.h" #define STATIC static /*---------------------------------------------------------------------------- * Preprocessor Definitions and Constants * -------------------------------------------------------------------------*/ /*Maximum number of TIDs */ #define WLAN_MAX_TID 8 /*Offset of the OUI field inside the LLC/SNAP header*/ #define WLANTL_LLC_OUI_OFFSET 3 /*Size of the OUI type field inside the LLC/SNAP header*/ #define WLANTL_LLC_OUI_SIZE 3 /*Offset of the protocol type field inside the LLC/SNAP header*/ #define WLANTL_LLC_PROTO_TYPE_OFFSET (WLANTL_LLC_OUI_OFFSET + WLANTL_LLC_OUI_SIZE) /*Size of the protocol type field inside the LLC/SNAP header*/ #define WLANTL_LLC_PROTO_TYPE_SIZE 2 /*802.1x protocol type */ #define WLANTL_LLC_8021X_TYPE 0x888E /*WAPI protocol type */ #define WLANTL_LLC_WAI_TYPE 0x88b4 #define WLANTL_ETHERTYPE_ARP 0x0806 #ifdef FEATURE_WLAN_TDLS #define WLANTL_LLC_TDLS_TYPE 0x890d #endif /*Length offset inside the AMSDU sub-frame header*/ #define WLANTL_AMSDU_SUBFRAME_LEN_OFFSET 12 /*802.3 header definitions*/ #define WLANTL_802_3_HEADER_LEN 14 /* Offset of DA field in a 802.3 header*/ #define WLANTL_802_3_HEADER_DA_OFFSET 0 /*802.11 header definitions - header len without QOS ctrl field*/ #define WLANTL_802_11_HEADER_LEN 24 /*802.11 header length + QOS ctrl field*/ #define WLANTL_MPDU_HEADER_LEN 32 /*802.11 header definitions*/ #define WLANTL_802_11_MAX_HEADER_LEN 40 /*802.11 header definitions - qos ctrl field len*/ #define WLANTL_802_11_HEADER_QOS_CTL 2 /*802.11 header definitions - ht ctrl field len*/ #define WLANTL_802_11_HEADER_HT_CTL 4 /* Offset of Addr1 field in a 802.11 header*/ #define WLANTL_802_11_HEADER_ADDR1_OFFSET 4 /*802.11 ADDR4 MAC addr field len */ #define WLANTL_802_11_HEADER_ADDR4_LEN VOS_MAC_ADDR_SIZE /* Length of an AMSDU sub-frame */ #define TL_AMSDU_SUBFRM_HEADER_LEN 14 /* Length of the LLC header*/ #define WLANTL_LLC_HEADER_LEN 8 /*As per 802.11 spec */ #define WLANTL_MGMT_FRAME_TYPE 0x00 #define WLANTL_CTRL_FRAME_TYPE 0x10 #define WLANTL_DATA_FRAME_TYPE 0x20 #define WLANTL_MGMT_PROBE_REQ_FRAME_TYPE 0x04 /*Value of the data type field in the 802.11 frame */ #define WLANTL_80211_DATA_TYPE 0x02 #define WLANTL_80211_DATA_QOS_SUBTYPE 0x08 #define WLANTL_80211_NULL_QOS_SUBTYPE 0x0C #define WLANTL_80211_MGMT_ACTION_SUBTYPE 0x0D #define WLANTL_80211_MGMT_ACTION_NO_ACK_SUBTYPE 0x0E /*Defines for internal utility functions */ #define WLANTL_FRAME_TYPE_BCAST 0xff #define WLANTL_FRAME_TYPE_MCAST 0x01 #define WLANTL_FRAME_TYPE_UCAST 0x00 #define WLANTL_FRAME_TYPESUBTYPE_MASK 0x3F #ifdef WLAN_FEATURE_RMC #define WLANTL_RMC_HASH_TABLE_SIZE (32) #endif /*------------------------------------------------------------------------- BT-AMP related definition - !!! should probably be moved to BT-AMP header ---------------------------------------------------------------------------*/ /*------------------------------------------------------------------------- Helper macros ---------------------------------------------------------------------------*/ /*Checks STA index validity*/ #define WLANTL_STA_ID_INVALID( _staid )( _staid >= WLAN_MAX_STA_COUNT ) /*As per Libra behavior */ #define WLANTL_STA_ID_BCAST 0xFF /*Checks TID validity*/ #define WLANTL_TID_INVALID( _tid ) ( _tid >= WLAN_MAX_TID ) /*Checks AC validity*/ #define WLANTL_AC_INVALID( _tid ) ( _tid >= WLANTL_MAX_AC ) /*Determines the addr field offset based on the frame xtl bit*/ #define WLANTL_MAC_ADDR_ALIGN( _dxtl ) \ ( ( 0 == _dxtl ) ? \ WLANTL_802_3_HEADER_DA_OFFSET: WLANTL_802_11_HEADER_ADDR1_OFFSET ) /*Determines the header len based on the disable xtl field*/ #define WLANTL_MAC_HEADER_LEN( _dxtl) \ ( ( 0 == _dxtl )? \ WLANTL_802_3_HEADER_LEN:WLANTL_802_11_HEADER_LEN ) /*Determines the necesary length of the BD header - in case UMA translation is enabled enough room needs to be left in front of the packet for the 802.11 header to be inserted*/ #define WLANTL_BD_HEADER_LEN( _dxtl ) \ ( ( 0 == _dxtl )? \ (WLANHAL_TX_BD_HEADER_SIZE+WLANTL_802_11_MAX_HEADER_LEN): WLANHAL_TX_BD_HEADER_SIZE ) #define WLAN_TL_CEIL( _a, _b) (( 0 != (_a)%(_b))? (_a)/(_b) + 1: (_a)/(_b)) /*get TL control block from vos global context */ #define VOS_GET_TL_CB(_pvosGCtx) \ ((WLANTL_CbType*)vos_get_context( VOS_MODULE_ID_TL, _pvosGCtx)) /* Check whether Rx frame is LS or EAPOL packet (other than data) */ #define WLANTL_BAP_IS_NON_DATA_PKT_TYPE(usType) \ ((WLANTL_BT_AMP_TYPE_AR == usType) || (WLANTL_BT_AMP_TYPE_SEC == usType) || \ (WLANTL_BT_AMP_TYPE_LS_REQ == usType) || (WLANTL_BT_AMP_TYPE_LS_REP == usType)) /*get RSSI0 from a RX BD*/ /* 7 bits in phystats represent -100dBm to +27dBm */ #define WLAN_TL_RSSI_CORRECTION 100 #define WLANTL_GETRSSI0(pBD) (WDA_GETRSSI0(pBD) - WLAN_TL_RSSI_CORRECTION) /*get RSSI1 from a RX BD*/ #define WLANTL_GETRSSI1(pBD) (WDA_GETRSSI1(pBD) - WLAN_TL_RSSI_CORRECTION) #define WLANTL_GETSNR(pBD) WDA_GET_RX_SNR(pBD) /* Check whether Rx frame is LS or EAPOL packet (other than data) */ #define WLANTL_BAP_IS_NON_DATA_PKT_TYPE(usType) \ ((WLANTL_BT_AMP_TYPE_AR == usType) || (WLANTL_BT_AMP_TYPE_SEC == usType) || \ (WLANTL_BT_AMP_TYPE_LS_REQ == usType) || (WLANTL_BT_AMP_TYPE_LS_REP == usType)) #define WLANTL_CACHE_TRACE_WATERMARK 100 /*--------------------------------------------------------------------------- TL signals for TX thread ---------------------------------------------------------------------------*/ typedef enum { /*Suspend signal - following serialization of a HAL suspend request*/ WLANTL_TX_SIG_SUSPEND = 0, /*Res need signal - triggered when all pending TxComp have been received and TL is low on resources*/ WLANTL_TX_RES_NEEDED = 1, /* Forwarding RX cached frames. This is not used anymore as it is replaced by WLANTL_RX_FWD_CACHED in RX thread*/ WLANTL_TX_FWD_CACHED = 2, /* Serialized STAID AC Indication */ WLANTL_TX_STAID_AC_IND = 3, /* Serialzie TX transmit request */ WLANTL_TX_START_XMIT = 4, /* Serialzie Finish UL Authentication request */ WLANTL_FINISH_ULA = 5, /* Serialized Snapshot request indication */ WLANTL_TX_SNAPSHOT = 6, /* Detected a fatal error issue SSR */ WLANTL_TX_FATAL_ERROR = 7, WLANTL_TX_FW_DEBUG = 8, WLANTL_TX_KICKDXE = 9, WLANTL_TX_MAX }WLANTL_TxSignalsType; /*--------------------------------------------------------------------------- TL signals for RX thread ---------------------------------------------------------------------------*/ typedef enum { /* Forwarding RX cached frames */ WLANTL_RX_FWD_CACHED = 0, }WLANTL_RxSignalsType; /*--------------------------------------------------------------------------- STA Event type ---------------------------------------------------------------------------*/ typedef enum { /* Transmit frame event */ WLANTL_TX_EVENT = 0, /* Receive frame event */ WLANTL_RX_EVENT = 1, WLANTL_MAX_EVENT }WLANTL_STAEventType; /*--------------------------------------------------------------------------- DESCRIPTION State machine used by transport layer for receiving or transmitting packets. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's control block can be extracted from its context ucSTAId: identifier of the station being processed vosDataBuff: pointer to the tx/rx vos buffer RETURN VALUE The result code associated with performing the operation ---------------------------------------------------------------------------*/ typedef VOS_STATUS (*WLANTL_STAFuncType)( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /*--------------------------------------------------------------------------- STA FSM Entry type ---------------------------------------------------------------------------*/ typedef struct { WLANTL_STAFuncType pfnSTATbl[WLANTL_MAX_EVENT]; } WLANTL_STAFsmEntryType; /* Receive in connected state - only EAPOL or WAI*/ VOS_STATUS WLANTL_STARxConn( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* Transmit in connected state - only EAPOL or WAI*/ VOS_STATUS WLANTL_STATxConn( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* Receive in authenticated state - all data allowed*/ VOS_STATUS WLANTL_STARxAuth( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* Transmit in authenticated state - all data allowed*/ VOS_STATUS WLANTL_STATxAuth( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* Receive in disconnected state - no data allowed*/ VOS_STATUS WLANTL_STARxDisc( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* Transmit in disconnected state - no data allowed*/ VOS_STATUS WLANTL_STATxDisc( v_PVOID_t pAdapter, v_U8_t ucSTAId, vos_pkt_t** pvosDataBuff, v_BOOL_t bForwardIAPPwithLLC); /* TL State Machine */ STATIC const WLANTL_STAFsmEntryType tlSTAFsm[WLANTL_STA_MAX_STATE] = { /* WLANTL_STA_INIT */ { { NULL, /* WLANTL_TX_EVENT - no packets should get transmitted*/ NULL, /* WLANTL_RX_EVENT - no packets should be received - drop*/ } }, /* WLANTL_STA_CONNECTED */ { { WLANTL_STATxConn, /* WLANTL_TX_EVENT - only EAPoL or WAI frames are allowed*/ WLANTL_STARxConn, /* WLANTL_RX_EVENT - only EAPoL or WAI frames can be rx*/ } }, /* WLANTL_STA_AUTHENTICATED */ { { WLANTL_STATxAuth, /* WLANTL_TX_EVENT - all data frames allowed*/ WLANTL_STARxAuth, /* WLANTL_RX_EVENT - all data frames can be rx */ } }, /* WLANTL_STA_DISCONNECTED */ { { WLANTL_STATxDisc, /* WLANTL_TX_EVENT - do nothing */ WLANTL_STARxDisc, /* WLANTL_RX_EVENT - frames will still be fwd-ed*/ } } }; /*--------------------------------------------------------------------------- Reordering information ---------------------------------------------------------------------------*/ #define WLANTL_MAX_WINSIZE 64 #define WLANTL_MAX_BA_SESSION 40 typedef struct { v_BOOL_t isAvailable; v_U64_t ullReplayCounter[WLANTL_MAX_WINSIZE]; v_PVOID_t arrayBuffer[WLANTL_MAX_WINSIZE]; } WLANTL_REORDER_BUFFER_T; /* To handle Frame Q aging, timer is needed * After timer expired, Qed frames have to be routed to upper layer * WLANTL_TIMER_EXPIER_UDATA_T is user data type for timer callback */ typedef struct { /* Global contect, HAL, HDD need this */ v_PVOID_t pAdapter; /* TL context handle */ v_PVOID_t pTLHandle; /* Current STAID, to know STA context */ v_U32_t STAID; v_U8_t TID; } WLANTL_TIMER_EXPIER_UDATA_T; typedef struct { /*specifies if re-order session exists*/ v_U8_t ucExists; /* Current Index */ v_U32_t ucCIndex; /* Count of the total packets in list*/ v_U16_t usCount; /* vos ttimer to handle Qed frames aging */ vos_timer_t agingTimer; /* Q windoe size */ v_U32_t winSize; /* Available RX frame buffer size */ v_U32_t bufferSize; /* Start Sequence number */ v_U32_t SSN; /* BA session ID, generate by HAL */ v_U32_t sessionID; v_U32_t currentESN; v_U32_t pendingFramesCount; vos_lock_t reorderLock; /* Aging timer callback user data */ WLANTL_TIMER_EXPIER_UDATA_T timerUdata; WLANTL_REORDER_BUFFER_T *reorderBuffer; v_U16_t LastSN; }WLANTL_BAReorderType; /*--------------------------------------------------------------------------- UAPSD information ---------------------------------------------------------------------------*/ typedef struct { /* flag set when a UAPSD session with triggers generated in fw is being set*/ v_U8_t ucSet; }WLANTL_UAPSDInfoType; #ifdef WLAN_FEATURE_RMC struct tTL_RMCList { struct tTL_RMCList *next; v_MACADDR_t rmcAddr; v_U16_t mcSeqCtl; v_U32_t rxMCDupcnt; }; typedef struct tTL_RMCList WLANTL_RMC_SESSION; #endif /*--------------------------------------------------------------------------- per-STA cache info ---------------------------------------------------------------------------*/ typedef struct { v_U16_t cacheSize; v_TIME_t cacheInitTime; v_TIME_t cacheDoneTime; v_TIME_t cacheClearTime; }WLANTL_CacheInfoType; /*--------------------------------------------------------------------------- STA Client type ---------------------------------------------------------------------------*/ typedef struct { /* Flag that keeps track of registration; only one STA with unique ID allowed */ v_U8_t ucExists; /* Function pointer to the receive packet handler from HDD */ WLANTL_STARxCBType pfnSTARx; /* Function pointer to the transmit complete confirmation handler from HDD */ WLANTL_TxCompCBType pfnSTATxComp; /* Function pointer to the packet retrieval routine in HDD */ WLANTL_STAFetchPktCBType pfnSTAFetchPkt; /* Reordering information for the STA */ WLANTL_BAReorderType atlBAReorderInfo[WLAN_MAX_TID]; /* STA Descriptor, contains information related to the new added STA */ WLAN_STADescType wSTADesc; /* Current connectivity state of the STA */ WLANTL_STAStateType tlState; /* Station priority */ WLANTL_STAPriorityType tlPri; /* Value of the averaged RSSI for this station */ v_S7_t rssiAvg; /* Value of the averaged RSSI for this station in BMPS */ v_S7_t rssiAvgBmps; /* Value of the Alpha to calculate RSSI average */ v_S7_t rssiAlpha; /* Value of the averaged RSSI for this station */ v_U32_t uLinkQualityAvg; /* Sum of SNR for snrIdx number of consecutive frames */ v_U32_t snrSum; /* Number of consecutive frames over which snrSum is calculated */ v_S7_t snrIdx; /* Average SNR of previous 20 frames */ v_S7_t prevSnrAvg; /* Average SNR returned by fw */ v_S7_t snrAvgBmps; /* Tx packet count per station per TID */ v_U32_t auTxCount[WLAN_MAX_TID]; /* Rx packet count per station per TID */ v_U32_t auRxCount[WLAN_MAX_TID]; /* Suspend flag */ v_U8_t ucTxSuspended; /* Pointer to the AMSDU chain maintained by the AMSDU de-aggregation completion sub-module */ vos_pkt_t* vosAMSDUChainRoot; /* Pointer to the root of the chain */ vos_pkt_t* vosAMSDUChain; /* Used for saving/restoring frame header for 802.3/11 AMSDU sub-frames */ v_U8_t aucMPDUHeader[WLANTL_MPDU_HEADER_LEN]; /* length of the header */ v_U8_t ucMPDUHeaderLen; /* Enabled ACs currently serviced by TL (automatic setup in TL)*/ v_U8_t aucACMask[WLANTL_NUM_TX_QUEUES]; /* Current AC to be retrieved */ WLANTL_ACEnumType ucCurrentAC; /*Packet pending flag - set if tx is pending for the station*/ v_U8_t ucPktPending; /*EAPOL Packet pending flag - set if EAPOL packet is pending for the station*/ v_U8_t ucEapolPktPending; /*used on tx packet to signal when there is no more data to tx for the moment=> packets can be passed to BAL */ v_U8_t ucNoMoreData; /* Last serviced AC to be retrieved */ WLANTL_ACEnumType ucServicedAC; /* Current weight for the AC */ v_U8_t ucCurrentWeight; /* Info used for UAPSD trigger frame generation */ WLANTL_UAPSDInfoType wUAPSDInfo[WLANTL_MAX_AC]; /* flag to signal if a trigger frames is pending */ v_U8_t ucPendingTrigFrm; WLANTL_TRANSFER_STA_TYPE trafficStatistics; /*Members needed for packet caching in TL*/ /*Begining of the cached packets chain*/ vos_pkt_t* vosBegCachedFrame; /*Begining of the cached packets chain*/ vos_pkt_t* vosEndCachedFrame; WLANTL_CacheInfoType tlCacheInfo; /* LWM related fields */ v_BOOL_t enableCaching; //current station is slow. LWM mode is enabled. v_BOOL_t ucLwmModeEnabled; //LWM events is reported when LWM mode is on. Able to send more traffic //under the constraints of uBuffThresholdMax v_BOOL_t ucLwmEventReported; //v_U8_t uLwmEventReported; /* Flow control fields */ //memory used in previous round v_U8_t bmuMemConsumed; //the number packets injected in this round v_U32_t uIngress_length; //number of packets allowed in current round beforing receiving new FW memory updates v_U32_t uBuffThresholdMax; // v_U32_t uEgress_length; // v_U32_t uIngress_length; // v_U32_t uBuffThresholdMax; // v_U32_t uBuffThresholdUsed; /* Value used to set LWM in FW. Initialized to 1/3* WLAN_STA_BMU_THRESHOLD_MAX In the future, it can be dynamically adjusted if we find the reason to implement such algorithm. */ v_U32_t uLwmThreshold; //tx disable forced by Riva software v_U16_t fcStaTxDisabled; /** HDD buffer status for packet scheduling. Once HDD * stores a new packet in a previously empty queue, it * will call TL interface to set the fields. The fields * will be cleaned by TL when TL can't fetch more packets * from the queue. */ // the fields are ucPktPending and ucACMask; /* Queue to keep unicast station management frame */ vos_list_t pStaManageQ; /* 1 means replay check is needed for the station, * 0 means replay check is not needed for the station*/ v_BOOL_t ucIsReplayCheckValid; /* It contains 48-bit replay counter per TID*/ v_U64_t ullReplayCounter[WLANTL_MAX_TID]; /* It contains no of replay packets found per STA. It is for debugging purpose only.*/ v_U32_t ulTotalReplayPacketsDetected; /* Set when pairwise key is installed, if ptkInstalled is 1 then we have to encrypt the data irrespective of TL state (CONNECTED/AUTHENTICATED) */ v_U8_t ptkInstalled; v_U32_t linkCapacity; #ifdef WLAN_FEATURE_RMC WLANTL_RMC_SESSION *mcastSession[WLANTL_RMC_HASH_TABLE_SIZE]; vos_lock_t mcLock; #endif #ifdef WLAN_FEATURE_LINK_LAYER_STATS /* Value of the averaged Data RSSI for this station */ v_S7_t rssiDataAvg; /* Value of the averaged Data RSSI for this station in BMPS */ v_S7_t rssiDataAvgBmps; /* Value of the Alpha to calculate Data RSSI average */ v_S7_t rssiDataAlpha; WLANTL_InterfaceStatsType interfaceStats; #endif /* BD Rate for transmitting ARP packets */ v_U8_t arpRate; v_BOOL_t arpOnWQ5; }WLANTL_STAClientType; /*--------------------------------------------------------------------------- BAP Client type ---------------------------------------------------------------------------*/ typedef struct { /* flag that keeps track of registration; only one non-data BT-AMP client allowed */ v_U8_t ucExists; /* pointer to the receive processing routine for non-data BT-AMP frames */ WLANTL_BAPRxCBType pfnTlBAPRx; /* pointer to the flush call back complete function */ WLANTL_FlushOpCompCBType pfnFlushOpCompleteCb; /* pointer to the non-data BT-AMP frame pending transmission */ vos_pkt_t* vosPendingDataBuff; /* BAP station ID */ v_U8_t ucBAPSTAId; }WLANTL_BAPClientType; /*--------------------------------------------------------------------------- Management Frame Client type ---------------------------------------------------------------------------*/ typedef struct { /* flag that keeps track of registration; only one management frame client allowed */ v_U8_t ucExists; /* pointer to the receive processing routine for management frames */ WLANTL_MgmtFrmRxCBType pfnTlMgmtFrmRx; /* pointer to the management frame pending transmission */ vos_pkt_t* vosPendingDataBuff; }WLANTL_MgmtFrmClientType; typedef struct { WLANTL_TrafficStatusChangedCBType trafficCB; WLANTL_HO_TRAFFIC_STATUS_TYPE trafficStatus; v_U32_t idleThreshold; v_U32_t measurePeriod; v_U32_t rtRXFrameCount; v_U32_t rtTXFrameCount; v_U32_t nrtRXFrameCount; v_U32_t nrtTXFrameCount; vos_timer_t trafficTimer; v_PVOID_t usrCtxt; } WLANTL_HO_TRAFFIC_STATUS_HANDLE_TYPE; typedef struct { v_S7_t rssiValue; v_U8_t triggerEvent[WLANTL_HS_NUM_CLIENT]; v_PVOID_t usrCtxt[WLANTL_HS_NUM_CLIENT]; v_U8_t whoIsClient[WLANTL_HS_NUM_CLIENT]; WLANTL_RSSICrossThresholdCBType crossCBFunction[WLANTL_HS_NUM_CLIENT]; v_U8_t numClient; } WLANTL_HO_RSSI_INDICATION_TYPE; typedef struct { v_U8_t numThreshold; v_U8_t regionNumber; v_S7_t historyRSSI; v_U8_t alpha; v_U32_t sampleTime; v_U32_t fwNotification; } WLANTL_CURRENT_HO_STATE_TYPE; typedef struct { WLANTL_HO_RSSI_INDICATION_TYPE registeredInd[WLANTL_MAX_AVAIL_THRESHOLD]; WLANTL_CURRENT_HO_STATE_TYPE currentHOState; WLANTL_HO_TRAFFIC_STATUS_HANDLE_TYPE currentTraffic; v_PVOID_t macCtxt; vos_lock_t hosLock; } WLANTL_HO_SUPPORT_TYPE; /*--------------------------------------------------------------------------- TL control block type ---------------------------------------------------------------------------*/ typedef struct { /* TL configuration information */ WLANTL_ConfigInfoType tlConfigInfo; /* list of the active stations */ WLANTL_STAClientType* atlSTAClients[WLAN_MAX_STA_COUNT]; /* information on the management frame client */ WLANTL_MgmtFrmClientType tlMgmtFrmClient; /* information on the BT AMP client */ WLANTL_BAPClientType tlBAPClient; /* number of packets sent to BAL waiting for tx complete confirmation */ v_U16_t usPendingTxCompleteCount; /* global suspend flag */ v_U8_t ucTxSuspended; /* resource flag */ v_U32_t uResCount; /* dummy vos buffer - used for chains */ vos_pkt_t* vosDummyBuf; /* temporary buffer for storing the packet that no longer fits */ vos_pkt_t* vosTempBuf; /* The value of the station id and AC for the cached buffer */ v_U8_t ucCachedSTAId; v_U8_t ucCachedAC; /* Last registered STA - until multiple sta support is added this will be used always for tx */ v_U8_t ucRegisteredStaId; /*Current TL STA used for TX*/ v_U8_t ucCurrentSTA; WLANTL_REORDER_BUFFER_T *reorderBufferPool; /* Allocate memory for [WLANTL_MAX_BA_SESSION] sessions */ WLANTL_HO_SUPPORT_TYPE hoSupport; v_BOOL_t bUrgent; /* resource flag */ v_U32_t bd_pduResCount; /* time interval to evaluate LWM mode*/ //vos_timer_t tThresholdSamplingTimer; #if 0 //information fields for flow control tFcTxParams_type tlFCInfo; #endif vos_pkt_t* vosTxFCBuf; /* LWM mode is enabled or not for each station. Bit-wise operation.32 station maximum. */ // v_U32_t uStaLwmMask; /* LWM event is reported by FW. */ // v_U32_t uStaLwmEventReported; /** Multiple Station Scheduling and TL queue management. 4 HDD BC/MC data packet queue status is specified as Station 0's status. Weights used in WFQ algorith are initialized in WLANTL_OPEN and contained in tlConfigInfo field. Each station has fields of ucPktPending and AC mask to tell whether a AC has traffic or not. Stations are served in a round-robin fashion from highest priority to lowest priority. The number of round-robin times of each prioirty equals to the WFQ weights and differetiates the traffic of different prioirty. As such, stations can not provide low priority packets if high priority packets are all served. */ /* Currently served station id. Reuse ucCurrentSTA field. */ //v_U8_t uCurStaId; /* Current served station ID in round-robin method to traverse all stations.*/ WLANTL_ACEnumType uCurServedAC; WLANTL_SpoofMacAddr spoofMacAddr; /* How many weights have not been served in current AC. */ v_U8_t ucCurLeftWeight; /* BC/MC management queue. Current implementation uses queue size 1. Will check whether size N is supported. */ vos_list_t pMCBCManageQ; v_U32_t sendFCFrame; v_U8_t done_once; v_U8_t uFramesProcThres; #ifdef FEATURE_WLAN_TDLS /*number of total TDLS peers registered to TL Incremented at WLANTL_RegisterSTAClient(staType == WLAN_STA_TDLS) Decremented at WLANTL_ClearSTAClient(staType == WLAN_STA_TDLS) */ v_U8_t ucTdlsPeerCount; #endif /*whether we are in BMPS/UAPSD/WOWL mode, since the latter 2 need to be BMPS first*/ v_BOOL_t isBMPS; /* Whether WDA_DS_TX_START_XMIT msg is pending or not */ v_BOOL_t isTxTranmitMsgPending; #ifdef WLAN_FEATURE_RMC WLANTL_RMC_SESSION *rmcSession[WLANTL_RMC_HASH_TABLE_SIZE]; vos_lock_t rmcLock; v_U8_t multicastDuplicateDetectionEnabled; v_U8_t rmcDataPathEnabled; v_U32_t mcastDupCnt; #endif WLANTL_MonRxCBType pfnMonRx; v_BOOL_t isConversionReq; }WLANTL_CbType; /*========================================================================== FUNCTION WLANTL_GetFrames DESCRIPTION BAL calls this function at the request of the lower bus interface. When this request is being received TL will retrieve packets from HDD in accordance with the priority rules and the count supplied by BAL. DEPENDENCIES HDD must have registered with TL at least one STA before this function can be called. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's or BAL's control block can be extracted from its context uSize: maximum size accepted by the lower layer uFlowMask TX flow control mask. Each bit is defined as WDA_TXFlowEnumType OUT vosDataBuff: it will contain a pointer to the first buffer supplied by TL, if there is more than one packet supplied, TL will chain them through vOSS buffers RETURN VALUE The result code associated with performing the operation 1 or more: number of required resources if there are still frames to fetch For Volans, it's BD/PDU numbers. For Prima, it's free DXE descriptors. 0 : error or HDD queues are drained SIDE EFFECTS ============================================================================*/ v_U32_t WLANTL_GetFrames ( v_PVOID_t pAdapter, vos_pkt_t **ppFrameDataBuff, v_U32_t uSize, v_U8_t uFlowMask, v_BOOL_t* pbUrgent ); /*========================================================================== FUNCTION WLANTL_TxComp DESCRIPTION It is being called by BAL upon asynchronous notification of the packet or packets being sent over the bus. DEPENDENCIES Tx complete cannot be called without a previous transmit. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's or BAL's control block can be extracted from its context vosDataBuff: it will contain a pointer to the first buffer for which the BAL report is being made, if there is more then one packet they will be chained using vOSS buffers. wTxSTAtus: the status of the transmitted packet, see above chapter on HDD interaction for a list of possible values RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_TxComp ( v_PVOID_t pAdapter, vos_pkt_t *pFrameDataBuff, VOS_STATUS wTxStatus ); /*========================================================================== FUNCTION WLANTL_RxFrames DESCRIPTION Callback registered by TL and called by BAL when a packet is received over the bus. Upon the call of this function TL will make the necessary decision with regards to the forwarding or queuing of this packet and the layer it needs to be delivered to. DEPENDENCIES TL must be initiailized before this function gets called. If the frame carried is a data frame then the station for which it is destined to must have been previously registered with TL. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's or BAL's control block can be extracted from its context vosDataBuff: it will contain a pointer to the first buffer received, if there is more then one packet they will be chained using vOSS buffers. RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_RxFrames ( v_PVOID_t pAdapter, vos_pkt_t *pFrameDataBuff ); /*========================================================================== FUNCTION WLANTL_RxCachedFrames DESCRIPTION Utility function used by TL to forward the cached frames to a particular station; DEPENDENCIES TL must be initiailized before this function gets called. If the frame carried is a data frame then the station for which it is destined to must have been previously registered with TL. PARAMETERS IN pTLCb: pointer to TL handle ucSTAId: station for which we need to forward the packets vosDataBuff: it will contain a pointer to the first cached buffer received, if there is more then one packet they will be chained using vOSS buffers. RETURN VALUE The result code associated with performing the operation VOS_STATUS_E_INVAL: Input parameters are invalid VOS_STATUS_E_FAULT: pointer to TL cb is NULL ; access would cause a page fault VOS_STATUS_SUCCESS: Everything is good :) SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_RxCachedFrames ( WLANTL_CbType* pTLCb, v_U8_t ucSTAId, vos_pkt_t* vosDataBuff ); /*========================================================================== FUNCTION WLANTL_ResourceCB DESCRIPTION Called by the TL when it has packets available for transmission. DEPENDENCIES The TL must be registered with BAL before this function can be called. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's or BAL's control block can be extracted from its context uCount: avail resource count obtained from hw RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_ResourceCB ( v_PVOID_t pAdapter, v_U32_t uCount ); /*========================================================================== FUNCTION WLANTL_ProcessMainMessage DESCRIPTION Called by VOSS when a message was serialized for TL through the main thread/task. DEPENDENCIES The TL must be initialized before this function can be called. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's control block can be extracted from its context message: type and content of the message RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_ProcessMainMessage ( v_PVOID_t pAdapter, vos_msg_t* message ); /*========================================================================== FUNCTION WLANTL_ProcessTxMessage DESCRIPTION Called by VOSS when a message was serialized for TL through the tx thread/task. DEPENDENCIES The TL must be initialized before this function can be called. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's control block can be extracted from its context message: type and content of the message RETURN VALUE The result code associated with performing the operation VOS_STATUS_SUCCESS: Everything is good :) SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_ProcessTxMessage ( v_PVOID_t pAdapter, vos_msg_t* message ); /*========================================================================== FUNCTION WLAN_TLGetNextTxIds DESCRIPTION Gets the next station and next AC in the list DEPENDENCIES PARAMETERS OUT pucSTAId: STAtion ID RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLAN_TLGetNextTxIds ( v_PVOID_t pAdapter, v_U8_t* pucSTAId ); /*========================================================================== FUNCTION WLANTL_CleanCb DESCRIPTION Cleans TL control block DEPENDENCIES PARAMETERS IN pTLCb: pointer to TL's control block ucEmpty: set if TL has to clean up the queues and release pedning pkts RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_CleanCB ( WLANTL_CbType* pTLCb, v_U8_t ucEmpty ); /*========================================================================== FUNCTION WLANTL_CleanSTA DESCRIPTION Cleans a station control block. DEPENDENCIES PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's control block can be extracted from its context ucEmpty: if set the queues and pending pkts will be emptyed RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_CleanSTA ( WLANTL_STAClientType* ptlSTAClient, v_U8_t ucEmpty ); /*========================================================================== FUNCTION WLANTL_GetTxResourcesCB DESCRIPTION Processing function for Resource needed signal. A request will be issued to BAL to get mor tx resources. DEPENDENCIES The TL must be initialized before this function can be called. PARAMETERS IN pvosGCtx: pointer to the global vos context; a handle to TL's control block can be extracted from its context RETURN VALUE The result code associated with performing the operation VOS_STATUS_E_FAULT: pointer to TL cb is NULL ; access would cause a page fault VOS_STATUS_SUCCESS: Everything is good :) Other values can be returned as a result of a function call, please check corresponding API for more info. SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_GetTxResourcesCB ( v_PVOID_t pvosGCtx ); /*========================================================================== FUNCTION WLANTL_PrepareBDHeader DESCRIPTION Callback function for serializing Suspend signal through Tx thread DEPENDENCIES Just notify HAL that suspend in TL is complete. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL's control block can be extracted from its context pUserData: user data sent with the callback RETURN VALUE The result code associated with performing the operation SIDE EFFECTS ============================================================================*/ void WLANTL_PrepareBDHeader ( vos_pkt_t* vosDataBuff, v_PVOID_t* ppvBDHeader, v_MACADDR_t* pvDestMacAdddr, v_U8_t ucDisableFrmXtl, VOS_STATUS* pvosSTAtus, v_U16_t* usPktLen, v_U8_t ucQosEnabled, v_U8_t ucWDSEnabled, v_U8_t extraHeadSpace ); /*========================================================================== FUNCTION WLANTL_Translate8023To80211Header DESCRIPTION Inline function for translating and 802.3 header into an 802.11 header. DEPENDENCIES PARAMETERS IN pTLCb: TL control block *pucStaId Station ID. In case of TDLS, this return the actual station index used to transmit. IN/OUT vosDataBuff: vos data buffer, will contain the new header on output OUT pvosStatus: status of the operation RETURN VALUE No return. SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_Translate8023To80211Header ( vos_pkt_t* vosDataBuff, VOS_STATUS* pvosStatus, WLANTL_CbType* pTLCb, v_U8_t *pucStaId, WLANTL_MetaInfoType* pTlMetaInfo, v_U8_t *ucWDSEnabled, v_U8_t *extraHeadSpace ); /*========================================================================== FUNCTION WLANTL_Translate80211To8023Header DESCRIPTION Inline function for translating and 802.11 header into an 802.3 header. DEPENDENCIES PARAMETERS IN pTLCb: TL control block ucStaId: station ID ucHeaderLen: Length of the header from BD ucActualHLen: Length of header including padding or any other trailers IN/OUT vosDataBuff: vos data buffer, will contain the new header on output OUT pvosStatus: status of the operation RETURN VALUE Status of the operation SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_Translate80211To8023Header ( vos_pkt_t* vosDataBuff, VOS_STATUS* pvosStatus, v_U16_t usActualHLen, v_U8_t ucHeaderLen, WLANTL_CbType* pTLCb, v_U8_t ucSTAId, v_BOOL_t bForwardIAPPwithLLC ); VOS_STATUS WLANTL_MonTranslate80211To8023Header ( vos_pkt_t* vosDataBuff, WLANTL_CbType* pTLCb ); /*========================================================================== FUNCTION WLANTL_FindFrameTypeBcMcUc DESCRIPTION Utility function to find whether received frame is broadcast, multicast or unicast. DEPENDENCIES The STA must be registered with TL before this function can be called. PARAMETERS IN pTLCb: pointer to the TL's control block ucSTAId: identifier of the station being processed vosDataBuff: pointer to the vos buffer IN/OUT pucBcMcUc: pointer to buffer, will contain frame type on return RETURN VALUE The result code associated with performing the operation VOS_STATUS_E_INVAL: invalid input parameters VOS_STATUS_E_BADMSG: failed to extract info from data buffer VOS_STATUS_SUCCESS: success SIDE EFFECTS None. ============================================================================*/ VOS_STATUS WLANTL_FindFrameTypeBcMcUc ( WLANTL_CbType *pTLCb, v_U8_t ucSTAId, vos_pkt_t *vosDataBuff, v_U8_t *pucBcMcUc ); /*========================================================================== FUNCTION WLANTL_MgmtFrmRxDefaultCb DESCRIPTION Default Mgmt Frm rx callback: asserts all the time. If this function gets called it means there is no registered rx cb pointer for Mgmt Frm. DEPENDENCIES PARAMETERS Not used. RETURN VALUE Always FAILURE. ============================================================================*/ VOS_STATUS WLANTL_MgmtFrmRxDefaultCb ( v_PVOID_t pAdapter, v_PVOID_t vosBuff ); /*========================================================================== FUNCTION WLANTL_STARxDefaultCb DESCRIPTION Default BAP rx callback: asserts all the time. If this function gets called it means there is no registered rx cb pointer for BAP. DEPENDENCIES PARAMETERS Not used. RETURN VALUE Always FAILURE. ============================================================================*/ VOS_STATUS WLANTL_BAPRxDefaultCb ( v_PVOID_t pAdapter, vos_pkt_t* vosDataBuff, WLANTL_BAPFrameEnumType frameType ); /*========================================================================== FUNCTION WLANTL_STARxDefaultCb DESCRIPTION Default STA rx callback: asserts all the time. If this function gets called it means there is no registered rx cb pointer for station. (Mem corruption most likely, it should never happen) DEPENDENCIES PARAMETERS Not used. RETURN VALUE Always FAILURE. ============================================================================*/ VOS_STATUS WLANTL_STARxDefaultCb ( v_PVOID_t pAdapter, vos_pkt_t* vosDataBuff, v_U8_t ucSTAId, WLANTL_RxMetaInfoType* pRxMetaInfo ); /*========================================================================== FUNCTION WLANTL_STAFetchPktDefaultCb DESCRIPTION Default fetch callback: asserts all the time. If this function gets called it means there is no registered fetch cb pointer for station. (Mem corruption most likely, it should never happen) DEPENDENCIES PARAMETERS Not used. RETURN VALUE Always FAILURE. ============================================================================*/ VOS_STATUS WLANTL_STAFetchPktDefaultCb ( v_PVOID_t pAdapter, v_U8_t* pucSTAId, WLANTL_ACEnumType ucAC, vos_pkt_t** vosDataBuff, WLANTL_MetaInfoType* tlMetaInfo ); /*========================================================================== FUNCTION WLANTL_TxCompDefaultCb DESCRIPTION Default tx complete handler. It will release the completed pkt to prevent memory leaks. PARAMETERS IN pAdapter: pointer to the global adapter context; a handle to TL/HAL/PE/BAP/HDD control block can be extracted from its context vosDataBuff: pointer to the VOSS data buffer that was transmitted wTxSTAtus: status of the transmission RETURN VALUE The result code associated with performing the operation; please check vos_pkt_return_pkt for possible error codes. ============================================================================*/ VOS_STATUS WLANTL_TxCompDefaultCb ( v_PVOID_t pAdapter, vos_pkt_t* vosDataBuff, VOS_STATUS wTxSTAtus ); /*========================================================================== FUNCTION WLANTL_PackUpTriggerFrame DESCRIPTION Packs up a trigger frame and places it in TL's cache for tx and notifies BAL DEPENDENCIES PARAMETERS IN pTLCb: pointer to the TL control block pfnSTATxComp: Tx Complete Cb to be used when frame is received ucSTAId: station id ucAC: access category RETURN VALUE None SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_PackUpTriggerFrame ( WLANTL_CbType* pTLCb, WLANTL_TxCompCBType pfnSTATxComp, v_U8_t ucSTAId, WLANTL_ACEnumType ucAC ); /*========================================================================== FUNCTION WLANTL_TxCompTriggFrameSI DESCRIPTION Tx complete handler for the service interval trigger frame. It will restart the SI timer. PARAMETERS IN pvosGCtx: pointer to the global vos context; a handle to TL/HAL/PE/BAP/HDD control block can be extracted from its context vosDataBuff: pointer to the VOSS data buffer that was transmitted wTxSTAtus: status of the transmission RETURN VALUE The result code associated with performing the operation ============================================================================*/ VOS_STATUS WLANTL_TxCompTriggFrameSI ( v_PVOID_t pvosGCtx, vos_pkt_t* vosDataBuff, VOS_STATUS wTxSTAtus ); /*========================================================================== FUNCTION WLANTL_TxCompTriggFrameSI DESCRIPTION Tx complete handler for the service interval trigger frame. It will restart the SI timer. PARAMETERS IN pvosGCtx: pointer to the global vos context; a handle to TL/HAL/PE/BAP/HDD control block can be extracted from its context vosDataBuff: pointer to the VOSS data buffer that was transmitted wTxSTAtus: status of the transmission RETURN VALUE The result code associated with performing the operation ============================================================================*/ VOS_STATUS WLANTL_TxCompTriggFrameDI ( v_PVOID_t pvosGCtx, vos_pkt_t* vosDataBuff, VOS_STATUS wTxSTAtus ); /*========================================================================== FUNCTION DESCRIPTION Read RSSI value out of a RX BD PARAMETERS: Caller must validate all parameters RETURN VALUE ============================================================================*/ VOS_STATUS WLANTL_ReadRSSI ( v_PVOID_t pAdapter, v_PVOID_t pBDHeader, v_U8_t STAid ); /*========================================================================== FUNCTION DESCRIPTION Read SNR value out of a RX BD PARAMETERS: Caller must validate all parameters RETURN VALUE ============================================================================*/ VOS_STATUS WLANTL_ReadSNR ( v_PVOID_t pAdapter, v_PVOID_t pBDHeader, v_U8_t STAid ); void WLANTL_PowerStateChangedCB ( v_PVOID_t pAdapter, tPmcState newState ); /*========================================================================== FUNCTION WLANTL_FwdPktToHDD DESCRIPTION Determine the Destation Station ID and route the Frame to Upper Layer DEPENDENCIES PARAMETERS IN pvosGCtx: pointer to the global vos context; a handle to TL's control block can be extracted from its context ucSTAId: identifier of the station being processed vosDataBuff: pointer to the rx vos buffer RETURN VALUE The result code associated with performing the operation VOS_STATUS_E_INVAL: invalid input parameters VOS_STATUS_E_FAULT: pointer to TL cb is NULL ; access would cause a page fault VOS_STATUS_SUCCESS: Everything is good :) SIDE EFFECTS ============================================================================*/ VOS_STATUS WLANTL_FwdPktToHDD ( v_PVOID_t pvosGCtx, vos_pkt_t* pvosDataBuff, v_U8_t ucSTAId ); #ifdef WLAN_FEATURE_RMC VOS_STATUS WLANTL_RmcInit ( v_PVOID_t pAdapter ); VOS_STATUS WLANTL_RmcDeInit ( v_PVOID_t pAdapter ); tANI_U8 WLANTL_RmcHashRmcSession ( v_MACADDR_t *pMcastAddr ); WLANTL_RMC_SESSION *WLANTL_RmcLookUpRmcSession ( WLANTL_RMC_SESSION *rmcSession[], v_MACADDR_t *pMcastAddr ); WLANTL_RMC_SESSION *WLANTL_RmcAddRmcSession ( WLANTL_RMC_SESSION *rmcSession[], v_MACADDR_t *pMcastAddr ); tANI_U8 WLANTL_RmcDeleteRmcSession ( WLANTL_RMC_SESSION *rmcSession[], v_MACADDR_t *pMcastAddr ); VOS_STATUS WLANTL_ProcessRmcCommand ( WLANTL_CbType* pTLCb, v_MACADDR_t *pMcastAddr, tANI_U32 command ); /*============================================================================= FUNCTION WLANTL_IsDuplicateMcastFrm DESCRIPTION This function checks for duplicast multicast frames and drops them. DEPENDENCIES PARAMETERS IN pClientSTA : Pointer to WLANTL_STAClientType aucBDHeader : Pointer to BD header RETURN VALUE VOS_FALSE: This frame is not a duplicate VOS_TRUE: This frame is a duplicate ==============================================================================*/ v_U8_t WLANTL_IsDuplicateMcastFrm ( WLANTL_STAClientType *pClientSTA, vos_pkt_t* vosDataBuff ); /*============================================================================= FUNCTION WLANTL_McastDeleteAllEntries DESCRIPTION This function removes all multicast entries used for duplicate detection DEPENDENCIES PARAMETERS IN pClientSTA : Pointer to WLANTL_STAClientType RETURN VALUE None ==============================================================================*/ void WLANTL_McastDeleteAllEntries(WLANTL_STAClientType * pClientSTA); #endif /*WLAN_FEATURE_RMC*/ #endif /* #ifndef WLAN_QCT_TLI_H */
fedosis/android_kernel_xiaomi_msm8937
drivers/staging/prima/CORE/TL/src/wlan_qct_tli.h
C
gpl-2.0
54,832
<!DOCTYPE html> <html lang="en" itemscope itemtype="http://schema.org/WebPage"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <title>Overview of all pages with the tag #India - Sudev Ambadi</title> <meta property="og:title" content="Overview of all pages with the tag #India" /> <meta name="twitter:title" content="Overview of all pages with the tag #India" /> <meta name="description" content="Overview of all pages with the tag #India, such as: Ponmudi"> <meta property="og:description" content="Overview of all pages with the tag #India, such as: Ponmudi"> <meta name="twitter:description" content="Overview of all pages with the tag #India, such as: Ponmudi"> <meta name="author" content="Sudev Ambadi"/><script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "name": "Sudev Ambadi", "url": "https:\/\/sudev.dev\/" } </script><script type="application/ld+json"> { "@context": "http://schema.org", "@type": "Organization", "name": "", "url": "https:\/\/sudev.dev\/" } </script> <meta property="og:title" content="India" /> <meta property="og:image" content="https://sudev.dev/images/avatar.jpeg" /> <meta property="og:url" content="https://sudev.dev/tags/india/" /> <meta property="og:type" content="website" /> <meta property="og:site_name" content="Sudev Ambadi" /> <meta name="twitter:title" content="India" /> <meta name="twitter:image" content="https://sudev.dev/images/avatar.jpeg" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@sudev" /> <meta name="twitter:creator" content="@sudev" /> <link href='https://sudev.dev/img/favicon.ico' rel='icon' type='image/x-icon'/> <meta property="og:image" content="https://sudev.dev/images/avatar.jpeg" /> <meta name="twitter:image" content="https://sudev.dev/images/avatar.jpeg" /> <meta name="twitter:card" content="summary" /> <meta name="twitter:site" content="@sudev" /> <meta name="twitter:creator" content="@sudev" /> <meta property="og:url" content="https://sudev.dev/tags/india/" /> <meta property="og:type" content="website" /> <meta property="og:site_name" content="Sudev Ambadi" /> <meta name="generator" content="Hugo 0.55.0" /> <link rel="alternate" href="https://sudev.dev/index.xml" type="application/rss+xml" title="Sudev Ambadi"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css" integrity="sha384-9eLZqc9ds8eNjO3TmqPeYcDj8n+Qfa4nuSiGYa6DjLNcv9BtN69ZIulL9+8CqC9Y" crossorigin="anonymous"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"><link rel="stylesheet" href="https://sudev.dev/css/main.css" /><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" /> <link rel="stylesheet" href="https://sudev.dev/css/highlight.min.css" /><link rel="stylesheet" href="https://sudev.dev/css/codeblock.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.css" integrity="sha384-h/L2W9KefUClHWaty3SLE5F/qvc4djlyR4qY3NUV5HGQBBW7stbcfff1+I/vmsHh" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.min.css" integrity="sha384-iD0dNku6PYSIQLyfTOpB06F2KCZJAKLOThS5HRe8b3ibhdEQ6eKsFf/EeFxdOt5R" crossorigin="anonymous"> <script type="application/javascript"> var doNotTrack = false; if (!doNotTrack) { window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', 'UA-39443594-1', 'auto'); ga('send', 'pageview'); } </script> <script async src='https://www.google-analytics.com/analytics.js'></script> </head> <body> <nav class="navbar navbar-default navbar-fixed-top navbar-custom"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="https://sudev.dev/">Sudev Ambadi</a> </div> <div class="collapse navbar-collapse" id="main-navbar"> <ul class="nav navbar-nav navbar-right"> <li> <a title="Blog" href="/">Blog</a> </li> <li> <a title="About" href="/page/about/">About</a> </li> <li> <a title="Tags" href="/tags">Tags</a> </li> </ul> </div> <div class="avatar-container"> <div class="avatar-img-border"> <a title="Sudev Ambadi" href="https://sudev.dev/"> <img class="avatar-img" src="https://sudev.dev/images/avatar.jpeg" alt="Sudev Ambadi" /> </a> </div> </div> </div> </nav> <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true"> <div class="pswp__bg"></div> <div class="pswp__scroll-wrap"> <div class="pswp__container"> <div class="pswp__item"></div> <div class="pswp__item"></div> <div class="pswp__item"></div> </div> <div class="pswp__ui pswp__ui--hidden"> <div class="pswp__top-bar"> <div class="pswp__counter"></div> <button class="pswp__button pswp__button--close" title="Close (Esc)"></button> <button class="pswp__button pswp__button--share" title="Share"></button> <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button> <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button> <div class="pswp__preloader"> <div class="pswp__preloader__icn"> <div class="pswp__preloader__cut"> <div class="pswp__preloader__donut"></div> </div> </div> </div> </div> <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"> <div class="pswp__share-tooltip"></div> </div> <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"> </button> <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"> </button> <div class="pswp__caption"> <div class="pswp__caption__center"></div> </div> </div> </div> </div> <header class="header-section "> <div class="intro-header no-img"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="tags-heading"> <h1>India</h1> <hr class="small"> </div> </div> </div> </div> </div> </header> <div class="container" role="main"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="posts-list"> <article class="post-preview"> <a href="https://sudev.dev/post/2014-11-09-ponmudi/"> <h2 class="post-title">Ponmudi</h2> </a> <p class="post-meta"> <span class="post-meta"> <i class="fas fa-calendar"></i>&nbsp;Posted on November 9, 2014 &nbsp;|&nbsp;<i class="fas fa-clock"></i>&nbsp;1&nbsp;minutes &nbsp;|&nbsp;<i class="fas fa-user"></i>&nbsp;Sudev Ambadi </span> </p> <div class="post-entry"> Mountain top and the fog ! View this post on Instagram Ponmudi top. #hairpins #ride #ponmudi #re A post shared by Sudev Ambadi (@sudev_ambadi) on Nov 8, 2014 at 7:14am PST The peak View this post on Instagram I&#39;m coming to you peak. #RE #hillstation #ride A post shared by Sudev Ambadi (@sudev_ambadi) on Dec 7, 2014 at 1:05am PST <a href="https://sudev.dev/post/2014-11-09-ponmudi/" class="post-read-more">[Read More]</a> </div> <div class="blog-tags"> <a href="https://sudev.dev//tags/royal-enfield/">Royal Enfield</a>&nbsp; <a href="https://sudev.dev//tags/classic/">Classic</a>&nbsp; <a href="https://sudev.dev//tags/travel/">Travel</a>&nbsp; <a href="https://sudev.dev//tags/india/">India</a>&nbsp; <a href="https://sudev.dev//tags/ponmudi/">Ponmudi</a>&nbsp; <a href="https://sudev.dev//tags/ride/">Ride</a>&nbsp; <a href="https://sudev.dev//tags/kerala/">Kerala</a>&nbsp; <a href="https://sudev.dev//tags/hill-station/">Hill Station</a>&nbsp; </div> </article> </div> </div> </div> </div> <footer> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <ul class="list-inline text-center footer-links"> <li> <a href="https://github.com/sudev" title="GitHub"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://twitter.com/sudev" title="Twitter"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-twitter fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="https://www.instagram.com/sudev_ambadi" title="Instagram"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-instagram fa-stack-1x fa-inverse"></i> </span> </a> </li> <li> <a href="/tags/india/index.xml" title="RSS"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fas fa-rss fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> <p class="credits copyright text-muted"> <a href="sudev.dev">Sudev Ambadi</a> &nbsp;&bull;&nbsp;&copy; 2016 &nbsp;&bull;&nbsp; <a href="https://sudev.dev/">Sudev Ambadi</a> </p> <p class="credits theme-by text-muted"> <a href="http://gohugo.io">Hugo v0.55.0</a> powered &nbsp;&bull;&nbsp; Theme by <a href="http://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a> adapted to <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a> </p> </div> </div> </div> </footer><script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.js" integrity="sha384-K3vbOmF2BtaVai+Qk37uypf7VrgBubhQreNQe9aGsz9lB63dIFiQVlJbr92dw2Lx" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/contrib/auto-render.min.js" integrity="sha384-kmZOZB5ObwgQnS/DuDg6TScgOiWWBiVt0plIRkZCmE6rDZGrEOQeHM5PcHi+nyqe" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="https://sudev.dev/js/main.js"></script> <script src="https://sudev.dev/js/highlight.min.js"></script> <script> hljs.initHighlightingOnLoad(); </script> <script> $(document).ready(function() {$("pre.chroma").css("padding","0");}); </script><script> renderMathInElement(document.body); </script><script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.js" integrity="sha384-QELNnmcmU8IR9ZAykt67vGr9/rZJdHbiWi64V88fCPaOohUlHCqUD/unNN0BXSqy" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.min.js" integrity="sha384-m67o7SkQ1ALzKZIFh4CiTA8tmadaujiTa9Vu+nqPSwDOqHrDmxLezTdFln8077+q" crossorigin="anonymous"></script><script src="https://sudev.dev/js/load-photoswipe.js"></script> </body> </html>
sudev/sudev.github.com
tags/india/index.html
HTML
gpl-2.0
13,872
#!/usr/bin/env python import sys import json from elasticsearch1 import Elasticsearch def init_es(es_host, es_index): es = Elasticsearch([ es_host ]) es.indices.delete( es_index, ignore=[400, 404] ) es.indices.create( es_index, ignore=400 ) # create mappings with open('pcawg_summary.mapping.json', 'r') as m: es_mapping = m.read() es.indices.put_mapping(index=es_index, doc_type='donor', body=es_mapping) return es def main(argv=None): if argv is None: argv = sys.argv else: sys.argv.extend(argv) es_host = 'localhost:9200' es_index = 'pcawg_summary' es = init_es(es_host, es_index) with open('pcawg_summary.jsonl', 'r') as t: for entity in t: doc = json.loads(entity) es.index(index=es_index, doc_type='donor', id=doc['donor_unique_id'], \ body=doc, timeout=90 ) if __name__ == "__main__": sys.exit(main())
ICGC-TCGA-PanCancer/pcawg-central-index
pcawg_metadata_parser/pcawg_summary.loader.py
Python
gpl-2.0
955
/******************************************************************************* * This file is part of openWNS (open Wireless Network Simulator) * _____________________________________________________________________________ * * Copyright (C) 2004-2009 * Chair of Communication Networks (ComNets) * Kopernikusstr. 5, D-52074 Aachen, Germany * phone: ++49-241-80-27910, * fax: ++49-241-80-22242 * email: info@openwns.org * www: http://www.openwns.org * _____________________________________________________________________________ * * openWNS is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 2 as published by the * Free Software Foundation; * * openWNS 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 program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include <COPPER/Transceiver.hpp> #include <COPPER/Wire.hpp> #include <COPPER/Transmission.hpp> #include <COPPER/Transmitter.hpp> #include <COPPER/Receiver.hpp> #include <WNS/node/Node.hpp> using namespace copper; STATIC_FACTORY_REGISTER_WITH_CREATOR( Transceiver, wns::node::component::Interface, "copper.Transceiver", wns::node::component::ConfigCreator ); Transceiver::Transceiver( wns::node::Interface* node, const wns::pyconfig::View& pyco) : wns::node::component::Component(node, pyco), transmitter(NULL), receiver(NULL), logger(pyco.get<wns::pyconfig::View>("logger")) { } void Transceiver::doStartup() { wns::pyconfig::View pyco = this->getConfig(); // No need to store this here, the Broker keeps the instances ... WireInterface* wire = Transceiver::getWireBroker().procure(pyco.get("wire")); this->transmitter = new Transmitter(pyco.get("transmitter"), wire); this->receiver = new Receiver(pyco.get("receiver"), wire); this->addService(pyco.get<std::string>("dataTransmission"), transmitter); this->addService(pyco.get<std::string>("dataTransmissionFeedback"), transmitter); this->addService(pyco.get<std::string>("notification"), receiver); } Transceiver::~Transceiver() { if (this->transmitter != NULL) { delete this->transmitter; } if (this->receiver != NULL) { delete this->receiver; } } void Transceiver::onNodeCreated() { } void Transceiver::onWorldCreated() { } void Transceiver::onShutdown() { } copper::WireBroker& Transceiver::getWireBroker() { static WireBroker b; return b; }
creasyw/IMTAphy
modules/phy/copper/src/Transceiver.cpp
C++
gpl-2.0
2,772
<?php namespace Openstore\Stdlib\Hydrator\Strategy; use DoctrineModule\Stdlib\Hydrator\Strategy\AllowRemoveByValue; use Doctrine\Common\Collections\Collection; //class MultiSelectStrategy extends AllowRemoveByValue class NestedExtractor extends AllowRemoveByValue { public function extract($value) { if ($value instanceof Collection) { $return = []; foreach ($value as $entity) { $return[] = $entity->getId(); } return $return; } if (is_object($value)) { return $value->getId(); } return $value; } }
belgattitude/openstore
module/Openstore/src/Openstore/Stdlib/Hydrator/Strategy/NestedExtractor.php
PHP
gpl-2.0
633
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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/>. """ import re import urllib import urlparse import kodi import log_utils # @UnusedImport import dom_parser import json from salts_lib import scraper_utils from salts_lib.constants import FORCE_NO_MATCH from salts_lib.constants import VIDEO_TYPES from salts_lib.constants import XHR from salts_lib.utils2 import i18n import scraper BASE_URL = 'http://www.snagfilms.com' SOURCE_BASE_URL = 'http://mp4.snagfilms.com' SEARCH_URL = '/apis/search.json' SEARCH_TYPES = {VIDEO_TYPES.MOVIE: 'film', VIDEO_TYPES.TVSHOW: 'show'} class Scraper(scraper.Scraper): base_url = BASE_URL def __init__(self, timeout=scraper.DEFAULT_TIMEOUT): self.timeout = timeout self.base_url = kodi.get_setting('%s-base_url' % (self.get_name())) self.username = kodi.get_setting('%s-username' % (self.get_name())) self.password = kodi.get_setting('%s-password' % (self.get_name())) @classmethod def provides(cls): return frozenset([VIDEO_TYPES.MOVIE, VIDEO_TYPES.TVSHOW, VIDEO_TYPES.EPISODE]) @classmethod def get_name(cls): return 'SnagFilms' def get_sources(self, video): source_url = self.get_url(video) hosters = [] if source_url and source_url != FORCE_NO_MATCH: page_url = urlparse.urljoin(self.base_url, source_url) html = self._http_get(page_url, cache_limit=.5) fragment = dom_parser.parse_dom(html, 'div', {'class': 'film-container'}) if fragment: iframe_url = dom_parser.parse_dom(fragment[0], 'iframe', ret='src') if iframe_url: iframe_url = urlparse.urljoin(self.base_url, iframe_url[0]) headers = {'Referer': page_url} html = self._http_get(iframe_url, headers=headers, cache_limit=.5) sources = self._parse_sources_list(html) for source in sources: quality = sources[source]['quality'] host = self._get_direct_hostname(source) stream_url = source + scraper_utils.append_headers({'User-Agent': scraper_utils.get_ua(), 'Referer': iframe_url}) hoster = {'multi-part': False, 'host': host, 'class': self, 'quality': quality, 'views': None, 'rating': None, 'url': stream_url, 'direct': True} match = re.search('(\d+[a-z]bps)', source) if match: hoster['extra'] = match.group(1) hosters.append(hoster) hosters.sort(key=lambda x: x.get('extra', ''), reverse=True) return hosters def _get_episode_url(self, season_url, video): episode_pattern = 'data-title\s*=\s*"Season\s+0*%s\s+Episode\s+0*%s[^>]*data-permalink\s*=\s*"([^"]+)' % (video.season, video.episode) title_pattern = 'data-title\s*=\s*"Season\s+\d+\s+Episode\s+\d+\s*(?P<title>[^"]+)[^>]+data-permalink\s*=\s*"(?P<url>[^"]+)' return self._default_get_episode_url(season_url, video, episode_pattern, title_pattern) def search(self, video_type, title, year, season=''): # @UnusedVariable results = [] search_url = urlparse.urljoin(self.base_url, SEARCH_URL) referer = urlparse.urljoin(self.base_url, '/search/?q=%s') referer = referer % (urllib.quote_plus(title)) headers = {'Referer': referer} headers.update(XHR) params = {'searchTerm': title, 'type': SEARCH_TYPES[video_type], 'limit': 500} html = self._http_get(search_url, params=params, headers=headers, auth=False, cache_limit=2) js_data = scraper_utils.parse_json(html, search_url) if 'results' in js_data: for result in js_data['results']: match_year = str(result.get('year', '')) match_url = result.get('permalink', '') match_title = result.get('title', '') if not year or not match_year or year == match_year: result = {'title': scraper_utils.cleanse_title(match_title), 'year': match_year, 'url': scraper_utils.pathify_url(match_url)} results.append(result) return results @classmethod def get_settings(cls): settings = super(cls, cls).get_settings() name = cls.get_name() settings.append(' <setting id="%s-username" type="text" label=" %s" default="" visible="eq(-4,true)"/>' % (name, i18n('username'))) settings.append(' <setting id="%s-password" type="text" label=" %s" option="hidden" default="" visible="eq(-5,true)"/>' % (name, i18n('password'))) return settings def _http_get(self, url, params=None, data=None, headers=None, auth=True, method=None, cache_limit=8): # return all uncached blank pages if no user or pass if not self.username or not self.password: return '' html = super(self.__class__, self)._http_get(url, params=params, data=data, headers=headers, method=method, cache_limit=cache_limit) if auth and not dom_parser.parse_dom(html, 'span', {'class': 'user-name'}): log_utils.log('Logging in for url (%s)' % (url), log_utils.LOGDEBUG) self.__login() html = super(self.__class__, self)._http_get(url, params=params, data=data, headers=headers, method=method, cache_limit=0) return html def __login(self): url = urlparse.urljoin(self.base_url, '/apis/v2/user/login.json') data = {'email': self.username, 'password': self.password, 'rememberMe': True} referer = urlparse.urljoin(self.base_url, '/login') headers = {'Content-Type': 'application/json', 'Referer': referer} headers.update(XHR) html = super(self.__class__, self)._http_get(url, data=json.dumps(data), headers=headers, cache_limit=0) js_data = scraper_utils.parse_json(html, url) return js_data.get('status') == 'success'
JamesLinEngineer/RKMC
addons/plugin.video.salts/scrapers/snagfilms_scraper.py
Python
gpl-2.0
6,712
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Mobissime Liberta source code Documentation</title> <link rel="stylesheet" href="resources/bootstrap.min.css?973e37a8502921d56bc02bb55321f45b072b6f71"> <link rel="stylesheet" href="resources/style.css?a2b5efb503881470385230f40f9bcc3c94d665e7"> </head> <body> <nav id="navigation" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <a href="index.html" class="navbar-brand">Liberta Doc</a> </div> <div class="collapse navbar-collapse"> <form id="search" class="navbar-form navbar-left" role="search"> <input type="hidden" name="cx" value=""> <input type="hidden" name="ie" value="UTF-8"> <div class="form-group"> <input type="text" name="q" class="search-query form-control" placeholder="Search"> </div> </form> <ul class="nav navbar-nav"> <li> <a href="namespace-App.Lib.html" title="Summary of App\Lib"><span>Namespace</span></a> </li> <li class="active"> <span>Class</span> </li> </ul> </div> </div> </nav> <div id="left"> <div id="menu"> <div id="groups"> <h3>Namespaces</h3> <ul> <li class="active"> <a href="namespace-App.html"> App<span></span> </a> <ul> <li> <a href="namespace-App.Controller.html"> Controller </a> </li> <li> <a href="namespace-App.Engine.html"> Engine </a> </li> <li> <a href="namespace-App.Entities.html"> Entities </a> </li> <li class="active"> <a href="namespace-App.Lib.html"> Lib<span></span> </a> <ul> <li> <a href="namespace-App.Lib.Crud.html"> Crud </a> </li> <li> <a href="namespace-App.Lib.Entities.html"> Entities </a> </li> <li> <a href="namespace-App.Lib.Module.html"> Module </a> </li> </ul></li> <li> <a href="namespace-App.Listeners.html"> Listeners </a> </li> <li> <a href="namespace-App.Model.html"> Model </a> </li> <li> <a href="namespace-App.Objects.html"> Objects </a> </li> <li> <a href="namespace-App.Repositories.html"> Repositories </a> </li> <li> <a href="namespace-App.Services.html"> Services </a> </li> </ul></li> <li> <a href="namespace-None.html"> None </a> </li> </ul> </div> <div id="elements"> <h3>Classes</h3> <ul> <li><a href="class-App.Lib.EntitiesUtils.html">EntitiesUtils</a></li> <li><a href="class-App.Lib.Login.html">Login</a></li> <li><a href="class-App.Lib.ModuleUtils.html">ModuleUtils</a></li> <li class="active"><a href="class-App.Lib.ObjectSerializer.html">ObjectSerializer</a></li> <li><a href="class-App.Lib.TwigController.html">TwigController</a></li> </ul> </div> </div> </div> <div id="splitter"></div> <div id="right"> <div id="rightInner"> <div id="content" class="class"> <h1>Class ObjectSerializer</h1> <div class="description"> <p>XML Object serializer</p> <p>For the full copyright and license information, please view the file LICENSE that was distributed with this source code.</p> </div> <div class="alert alert-info"> <b>Namespace:</b> <a href="namespace-App.html">App</a>\<a href="namespace-App.Lib.html">Lib</a><br> <b>Copyright:</b> 2015 Paul Coiffier | Mobissime - <a href="http://www.mobissime.com">http://www.mobissime.com</a><br> <b>Author:</b> Paul Coiffier <a href="&#109;&#x61;&#x69;&#108;&#116;&#x6f;&#58;&#99;&#x6f;&#105;&#102;&#x66;i&#101;&#x72;&#x2e;&#112;&#x61;&#x75;&#108;&#64;&#x67;&#109;&#97;&#x69;l&#46;&#x63;&#x6f;&#109;">&#99;&#x6f;&#105;&#102;&#x66;i&#101;&#x72;&#x2e;&#112;&#x61;&#x75;&#108;&#64;&#x67;&#109;&#97;&#x69;l&#46;&#x63;&#x6f;&#109;</a><br> <b>Located at</b> <a href="source-class-App.Lib.ObjectSerializer.html#18-84" title="Go to source code">Lib/ObjectSerializer.php</a> <br> </div> <div class="panel panel-default"> <div class="panel-heading"><h2>Methods summary</h2></div> <table class="summary table table-bordered table-striped methods" id="methods"> <tr data-order="serializeFile" id="_serializeFile"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_serializeFile">#</a> <code><a href="source-class-App.Lib.ObjectSerializer.html#30-50" title="Go to source code">serializeFile</a>( <span> <var>$file</var></span>, <span> <var>$format</var></span>, <span> <var>$content</var></span> )</code> <div class="description short"> <p>Serialize to file</p> </div> <div class="description detailed hidden"> <p>Serialize to file</p> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$file</var></dt> <dd>Filename</dd> <dt><var>$format</var></dt> <dd>(xml, etc)</dd> <dt><var>$content</var></dt> <dd>to serialize</dd> </dl></div> </div> </div></td> </tr> <tr data-order="serializeEntity" id="_serializeEntity"> <td class="attributes"><code> public </code> </td> <td class="name"><div> <a class="anchor" href="#_serializeEntity">#</a> <code><a href="source-class-App.Lib.ObjectSerializer.html#52-66" title="Go to source code">serializeEntity</a>( <span> <var>$entity_name</var></span>, <span> <var>$format</var></span>, <span> <var>$content</var></span> )</code> <div class="description short"> <p>Serialize a doctrine entity</p> </div> <div class="description detailed hidden"> <p>Serialize a doctrine entity</p> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$entity_name</var></dt> <dd>name</dd> <dt><var>$format</var></dt> <dd>(xml, etc)</dd> <dt><var>$content</var></dt> <dd>to serialize</dd> </dl></div> </div> </div></td> </tr> <tr data-order="find_xml_entity" id="_find_xml_entity"> <td class="attributes"><code> public <code><a href="class-App.Objects.Entity.html">App\Objects\Entity</a></code> </code> </td> <td class="name"><div> <a class="anchor" href="#_find_xml_entity">#</a> <code><a href="source-class-App.Lib.ObjectSerializer.html#68-82" title="Go to source code">find_xml_entity</a>( <span> <var>$entity_name</var></span> )</code> <div class="description short"> <p>Find and return an xml entity</p> </div> <div class="description detailed hidden"> <p>Find and return an xml entity</p> <h4>Parameters</h4> <div class="list"><dl> <dt><var>$entity_name</var></dt> <dd>to find</dd> </dl></div> <h4>Returns</h4> <div class="list"> <code><a href="class-App.Objects.Entity.html">App\Objects\Entity</a></code><br>Entity object </div> </div> </div></td> </tr> </table> </div> </div> </div> <div id="footer"> API documentation generated by <a href="https://github.com/paulcoiffier/Liberta-PhpApiGen">Liberta PhpApiGen plugin</a> </div> </div> <script src="resources/combined.js"></script> <script src="elementlist.js"></script> </body> </html>
paulcoiffier/Mobissime-Liberta
doc/php/framework/class-App.Lib.ObjectSerializer.html
HTML
gpl-2.0
7,475
#!/bin/sh # Copyright (C) 1999-2005 ImageMagick Studio LLC # # This program is covered by multiple licenses, which are described in # LICENSE. You should have received a copy of LICENSE with this # package; otherwise see http://www.imagemagick.org/script/license.php. . ${srcdir}/tests/common.shi ${RUNENV} ${MEMCHECK} ./rwblob ${SRCDIR}/input_truecolor.miff MIFF
atmark-techno/atmark-dist
user/imagemagick/tests/rwblob_MIFF_truecolor.sh
Shell
gpl-2.0
365
//Author: Tushar Jaiswal //Creation Date: 03/24/2018 /*Implement int sqrt(int x). Compute and return the square root of x. x is guaranteed to be a non-negative integer. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.*/ public class Solution { public int MySqrt(int x) { if(x == 0) { return 0; } if(x == 1) { return 1; } int left = 1, right = x / 2; while(left <= right) { int mid = left + (right - left) / 2; if(mid <= x / mid && (mid + 1) > x / (mid + 1)) { return mid; } if(mid > x / mid) { right = mid - 1; } else { left = mid + 1; } } return -1; } }
tushar-jaiswal/LeetCode
Algorithms/69. Sqrt(x)/Sqrt(x)-Optimized2.cs
C#
gpl-2.0
903
#ifndef __NET_CFG80211_H #define __NET_CFG80211_H #include <linux/netdevice.h> #include <linux/debugfs.h> #include <linux/list.h> #include <linux/netlink.h> #include <linux/skbuff.h> #include <linux/nl80211.h> #include <linux/if_ether.h> #include <linux/ieee80211.h> #include <net/regulatory.h> /* remove once we remove the wext stuff */ #include <net/iw_handler.h> #include <linux/wireless.h> enum ieee80211_band { IEEE80211_BAND_2GHZ = NL80211_BAND_2GHZ, IEEE80211_BAND_5GHZ = NL80211_BAND_5GHZ, /* keep last */ IEEE80211_NUM_BANDS }; enum ieee80211_channel_flags { IEEE80211_CHAN_DISABLED = 1<<0, IEEE80211_CHAN_PASSIVE_SCAN = 1<<1, IEEE80211_CHAN_NO_IBSS = 1<<2, IEEE80211_CHAN_RADAR = 1<<3, IEEE80211_CHAN_NO_HT40PLUS = 1<<4, IEEE80211_CHAN_NO_HT40MINUS = 1<<5, }; #define IEEE80211_CHAN_NO_HT40 \ (IEEE80211_CHAN_NO_HT40PLUS | IEEE80211_CHAN_NO_HT40MINUS) struct ieee80211_channel { enum ieee80211_band band; u16 center_freq; u16 hw_value; u32 flags; int max_antenna_gain; int max_power; bool beacon_found; u32 orig_flags; int orig_mag, orig_mpwr; }; enum ieee80211_rate_flags { IEEE80211_RATE_SHORT_PREAMBLE = 1<<0, IEEE80211_RATE_MANDATORY_A = 1<<1, IEEE80211_RATE_MANDATORY_B = 1<<2, IEEE80211_RATE_MANDATORY_G = 1<<3, IEEE80211_RATE_ERP_G = 1<<4, }; struct ieee80211_rate { u32 flags; u16 bitrate; u16 hw_value, hw_value_short; }; struct ieee80211_sta_ht_cap { u16 cap; /* use IEEE80211_HT_CAP_ */ bool ht_supported; u8 ampdu_factor; u8 ampdu_density; struct ieee80211_mcs_info mcs; }; struct ieee80211_supported_band { struct ieee80211_channel *channels; struct ieee80211_rate *bitrates; enum ieee80211_band band; int n_channels; int n_bitrates; struct ieee80211_sta_ht_cap ht_cap; }; struct vif_params { u8 *mesh_id; int mesh_id_len; int use_4addr; }; struct key_params { u8 *key; u8 *seq; int key_len; int seq_len; u32 cipher; }; enum survey_info_flags { SURVEY_INFO_NOISE_DBM = 1<<0, }; struct survey_info { struct ieee80211_channel *channel; u32 filled; s8 noise; }; struct beacon_parameters { u8 *head, *tail; int interval, dtim_period; int head_len, tail_len; }; enum plink_actions { PLINK_ACTION_INVALID, PLINK_ACTION_OPEN, PLINK_ACTION_BLOCK, }; struct station_parameters { u8 *supported_rates; struct net_device *vlan; u32 sta_flags_mask, sta_flags_set; int listen_interval; u16 aid; u8 supported_rates_len; u8 plink_action; struct ieee80211_ht_cap *ht_capa; }; enum station_info_flags { STATION_INFO_INACTIVE_TIME = 1<<0, STATION_INFO_RX_BYTES = 1<<1, STATION_INFO_TX_BYTES = 1<<2, STATION_INFO_LLID = 1<<3, STATION_INFO_PLID = 1<<4, STATION_INFO_PLINK_STATE = 1<<5, STATION_INFO_SIGNAL = 1<<6, STATION_INFO_TX_BITRATE = 1<<7, STATION_INFO_RX_PACKETS = 1<<8, STATION_INFO_TX_PACKETS = 1<<9, }; enum rate_info_flags { RATE_INFO_FLAGS_MCS = 1<<0, RATE_INFO_FLAGS_40_MHZ_WIDTH = 1<<1, RATE_INFO_FLAGS_SHORT_GI = 1<<2, }; struct rate_info { u8 flags; u8 mcs; u16 legacy; }; struct station_info { u32 filled; u32 inactive_time; u32 rx_bytes; u32 tx_bytes; u16 llid; u16 plid; u8 plink_state; s8 signal; struct rate_info txrate; u32 rx_packets; u32 tx_packets; int generation; }; enum monitor_flags { MONITOR_FLAG_FCSFAIL = 1<<NL80211_MNTR_FLAG_FCSFAIL, MONITOR_FLAG_PLCPFAIL = 1<<NL80211_MNTR_FLAG_PLCPFAIL, MONITOR_FLAG_CONTROL = 1<<NL80211_MNTR_FLAG_CONTROL, MONITOR_FLAG_OTHER_BSS = 1<<NL80211_MNTR_FLAG_OTHER_BSS, MONITOR_FLAG_COOK_FRAMES = 1<<NL80211_MNTR_FLAG_COOK_FRAMES, }; enum mpath_info_flags { MPATH_INFO_FRAME_QLEN = BIT(0), MPATH_INFO_SN = BIT(1), MPATH_INFO_METRIC = BIT(2), MPATH_INFO_EXPTIME = BIT(3), MPATH_INFO_DISCOVERY_TIMEOUT = BIT(4), MPATH_INFO_DISCOVERY_RETRIES = BIT(5), MPATH_INFO_FLAGS = BIT(6), }; struct mpath_info { u32 filled; u32 frame_qlen; u32 sn; u32 metric; u32 exptime; u32 discovery_timeout; u8 discovery_retries; u8 flags; int generation; }; struct bss_parameters { int use_cts_prot; int use_short_preamble; int use_short_slot_time; u8 *basic_rates; u8 basic_rates_len; int ap_isolate; }; struct mesh_config { /* Timeouts in ms */ /* Mesh plink management parameters */ u16 dot11MeshRetryTimeout; u16 dot11MeshConfirmTimeout; u16 dot11MeshHoldingTimeout; u16 dot11MeshMaxPeerLinks; u8 dot11MeshMaxRetries; u8 dot11MeshTTL; bool auto_open_plinks; /* HWMP parameters */ u8 dot11MeshHWMPmaxPREQretries; u32 path_refresh_time; u16 min_discovery_timeout; u32 dot11MeshHWMPactivePathTimeout; u16 dot11MeshHWMPpreqMinInterval; u16 dot11MeshHWMPnetDiameterTraversalTime; u8 dot11MeshHWMPRootMode; }; struct ieee80211_txq_params { enum nl80211_txq_q queue; u16 txop; u16 cwmin; u16 cwmax; u8 aifs; }; /* from net/wireless.h */ struct wiphy; /* from net/ieee80211.h */ struct ieee80211_channel; struct cfg80211_ssid { u8 ssid[IEEE80211_MAX_SSID_LEN]; u8 ssid_len; }; struct cfg80211_scan_request { struct cfg80211_ssid *ssids; int n_ssids; u32 n_channels; const u8 *ie; size_t ie_len; /* internal */ struct wiphy *wiphy; struct net_device *dev; bool aborted; /* keep last */ struct ieee80211_channel *channels[0]; }; enum cfg80211_signal_type { CFG80211_SIGNAL_TYPE_NONE, CFG80211_SIGNAL_TYPE_MBM, CFG80211_SIGNAL_TYPE_UNSPEC, }; struct cfg80211_bss { struct ieee80211_channel *channel; u8 bssid[ETH_ALEN]; u64 tsf; u16 beacon_interval; u16 capability; u8 *information_elements; size_t len_information_elements; u8 *beacon_ies; size_t len_beacon_ies; u8 *proberesp_ies; size_t len_proberesp_ies; s32 signal; void (*free_priv)(struct cfg80211_bss *bss); u8 priv[0] __attribute__((__aligned__(sizeof(void *)))); }; const u8 *ieee80211_bss_get_ie(struct cfg80211_bss *bss, u8 ie); struct cfg80211_crypto_settings { u32 wpa_versions; u32 cipher_group; int n_ciphers_pairwise; u32 ciphers_pairwise[NL80211_MAX_NR_CIPHER_SUITES]; int n_akm_suites; u32 akm_suites[NL80211_MAX_NR_AKM_SUITES]; bool control_port; }; struct cfg80211_auth_request { struct cfg80211_bss *bss; const u8 *ie; size_t ie_len; enum nl80211_auth_type auth_type; const u8 *key; u8 key_len, key_idx; bool local_state_change; }; struct cfg80211_assoc_request { struct cfg80211_bss *bss; const u8 *ie, *prev_bssid; size_t ie_len; struct cfg80211_crypto_settings crypto; bool use_mfp; }; struct cfg80211_deauth_request { struct cfg80211_bss *bss; const u8 *ie; size_t ie_len; u16 reason_code; bool local_state_change; }; struct cfg80211_disassoc_request { struct cfg80211_bss *bss; const u8 *ie; size_t ie_len; u16 reason_code; bool local_state_change; }; struct cfg80211_ibss_params { u8 *ssid; u8 *bssid; struct ieee80211_channel *channel; u8 *ie; u8 ssid_len, ie_len; u16 beacon_interval; bool channel_fixed; bool privacy; }; struct cfg80211_connect_params { struct ieee80211_channel *channel; u8 *bssid; u8 *ssid; size_t ssid_len; enum nl80211_auth_type auth_type; u8 *ie; size_t ie_len; bool privacy; struct cfg80211_crypto_settings crypto; const u8 *key; u8 key_len, key_idx; }; enum wiphy_params_flags { WIPHY_PARAM_RETRY_SHORT = 1 << 0, WIPHY_PARAM_RETRY_LONG = 1 << 1, WIPHY_PARAM_FRAG_THRESHOLD = 1 << 2, WIPHY_PARAM_RTS_THRESHOLD = 1 << 3, WIPHY_PARAM_COVERAGE_CLASS = 1 << 4, }; enum tx_power_setting { TX_POWER_AUTOMATIC, TX_POWER_LIMITED, TX_POWER_FIXED, }; struct cfg80211_bitrate_mask { struct { u32 legacy; /* TODO: add support for masking MCS rates; e.g.: */ /* u8 mcs[IEEE80211_HT_MCS_MASK_LEN]; */ } control[IEEE80211_NUM_BANDS]; }; struct cfg80211_pmksa { u8 *bssid; u8 *pmkid; }; struct cfg80211_ops { int (*suspend)(struct wiphy *wiphy); int (*resume)(struct wiphy *wiphy); int (*add_virtual_intf)(struct wiphy *wiphy, char *name, enum nl80211_iftype type, u32 *flags, struct vif_params *params); int (*del_virtual_intf)(struct wiphy *wiphy, struct net_device *dev); int (*change_virtual_intf)(struct wiphy *wiphy, struct net_device *dev, enum nl80211_iftype type, u32 *flags, struct vif_params *params); int (*add_key)(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, const u8 *mac_addr, struct key_params *params); int (*get_key)(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, const u8 *mac_addr, void *cookie, void (*callback)(void *cookie, struct key_params*)); int (*del_key)(struct wiphy *wiphy, struct net_device *netdev, u8 key_index, const u8 *mac_addr); int (*set_default_key)(struct wiphy *wiphy, struct net_device *netdev, u8 key_index); int (*set_default_mgmt_key)(struct wiphy *wiphy, struct net_device *netdev, u8 key_index); int (*add_beacon)(struct wiphy *wiphy, struct net_device *dev, struct beacon_parameters *info); int (*set_beacon)(struct wiphy *wiphy, struct net_device *dev, struct beacon_parameters *info); int (*del_beacon)(struct wiphy *wiphy, struct net_device *dev); int (*add_station)(struct wiphy *wiphy, struct net_device *dev, u8 *mac, struct station_parameters *params); int (*del_station)(struct wiphy *wiphy, struct net_device *dev, u8 *mac); int (*change_station)(struct wiphy *wiphy, struct net_device *dev, u8 *mac, struct station_parameters *params); int (*get_station)(struct wiphy *wiphy, struct net_device *dev, u8 *mac, struct station_info *sinfo); int (*dump_station)(struct wiphy *wiphy, struct net_device *dev, int idx, u8 *mac, struct station_info *sinfo); int (*add_mpath)(struct wiphy *wiphy, struct net_device *dev, u8 *dst, u8 *next_hop); int (*del_mpath)(struct wiphy *wiphy, struct net_device *dev, u8 *dst); int (*change_mpath)(struct wiphy *wiphy, struct net_device *dev, u8 *dst, u8 *next_hop); int (*get_mpath)(struct wiphy *wiphy, struct net_device *dev, u8 *dst, u8 *next_hop, struct mpath_info *pinfo); int (*dump_mpath)(struct wiphy *wiphy, struct net_device *dev, int idx, u8 *dst, u8 *next_hop, struct mpath_info *pinfo); int (*get_mesh_params)(struct wiphy *wiphy, struct net_device *dev, struct mesh_config *conf); int (*set_mesh_params)(struct wiphy *wiphy, struct net_device *dev, const struct mesh_config *nconf, u32 mask); int (*change_bss)(struct wiphy *wiphy, struct net_device *dev, struct bss_parameters *params); int (*set_txq_params)(struct wiphy *wiphy, struct ieee80211_txq_params *params); int (*set_channel)(struct wiphy *wiphy, struct net_device *dev, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type); int (*scan)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_scan_request *request); int (*auth)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_auth_request *req); int (*assoc)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_assoc_request *req); int (*deauth)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_deauth_request *req, void *cookie); int (*disassoc)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_disassoc_request *req, void *cookie); int (*connect)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_connect_params *sme); int (*disconnect)(struct wiphy *wiphy, struct net_device *dev, u16 reason_code); int (*join_ibss)(struct wiphy *wiphy, struct net_device *dev, struct cfg80211_ibss_params *params); int (*leave_ibss)(struct wiphy *wiphy, struct net_device *dev); int (*set_wiphy_params)(struct wiphy *wiphy, u32 changed); int (*set_tx_power)(struct wiphy *wiphy, enum tx_power_setting type, int dbm); int (*get_tx_power)(struct wiphy *wiphy, int *dbm); int (*set_wds_peer)(struct wiphy *wiphy, struct net_device *dev, u8 *addr); void (*rfkill_poll)(struct wiphy *wiphy); #ifdef CONFIG_NL80211_TESTMODE int (*testmode_cmd)(struct wiphy *wiphy, void *data, int len); #endif int (*set_bitrate_mask)(struct wiphy *wiphy, struct net_device *dev, const u8 *peer, const struct cfg80211_bitrate_mask *mask); int (*dump_survey)(struct wiphy *wiphy, struct net_device *netdev, int idx, struct survey_info *info); int (*set_pmksa)(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa); int (*del_pmksa)(struct wiphy *wiphy, struct net_device *netdev, struct cfg80211_pmksa *pmksa); int (*flush_pmksa)(struct wiphy *wiphy, struct net_device *netdev); int (*remain_on_channel)(struct wiphy *wiphy, struct net_device *dev, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type, unsigned int duration, u64 *cookie); int (*cancel_remain_on_channel)(struct wiphy *wiphy, struct net_device *dev, u64 cookie); int (*action)(struct wiphy *wiphy, struct net_device *dev, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type, const u8 *buf, size_t len, u64 *cookie); int (*set_power_mgmt)(struct wiphy *wiphy, struct net_device *dev, bool enabled, int timeout); int (*set_cqm_rssi_config)(struct wiphy *wiphy, struct net_device *dev, s32 rssi_thold, u32 rssi_hyst); }; enum wiphy_flags { WIPHY_FLAG_CUSTOM_REGULATORY = BIT(0), WIPHY_FLAG_STRICT_REGULATORY = BIT(1), WIPHY_FLAG_DISABLE_BEACON_HINTS = BIT(2), WIPHY_FLAG_NETNS_OK = BIT(3), WIPHY_FLAG_PS_ON_BY_DEFAULT = BIT(4), WIPHY_FLAG_4ADDR_AP = BIT(5), WIPHY_FLAG_4ADDR_STATION = BIT(6), }; struct mac_address { u8 addr[ETH_ALEN]; }; struct wiphy { /* assign these fields before you register the wiphy */ /* permanent MAC address(es) */ u8 perm_addr[ETH_ALEN]; u8 addr_mask[ETH_ALEN]; u16 n_addresses; struct mac_address *addresses; /* Supported interface modes, OR together BIT(NL80211_IFTYPE_...) */ u16 interface_modes; u32 flags; enum cfg80211_signal_type signal_type; int bss_priv_size; u8 max_scan_ssids; u16 max_scan_ie_len; int n_cipher_suites; const u32 *cipher_suites; u8 retry_short; u8 retry_long; u32 frag_threshold; u32 rts_threshold; u8 coverage_class; char fw_version[ETHTOOL_BUSINFO_LEN]; u32 hw_version; u8 max_num_pmkids; /* If multiple wiphys are registered and you're handed e.g. * a regular netdev with assigned ieee80211_ptr, you won't * know whether it points to a wiphy your driver has registered * or not. Assign this to something global to your driver to * help determine whether you own this wiphy or not. */ const void *privid; struct ieee80211_supported_band *bands[IEEE80211_NUM_BANDS]; /* Lets us get back the wiphy on the callback */ int (*reg_notifier)(struct wiphy *wiphy, struct regulatory_request *request); /* fields below are read-only, assigned by cfg80211 */ const struct ieee80211_regdomain *regd; /* the item in /sys/class/ieee80211/ points to this, * you need use set_wiphy_dev() (see below) */ struct device dev; /* dir in debugfs: ieee80211/<wiphyname> */ struct dentry *debugfsdir; #ifdef CONFIG_NET_NS /* the network namespace this phy lives in currently */ struct net *_net; #endif #ifdef CONFIG_CFG80211_WEXT const struct iw_handler_def *wext; #endif char priv[0] __attribute__((__aligned__(NETDEV_ALIGN))); }; #ifdef CONFIG_NET_NS static inline struct net *wiphy_net(struct wiphy *wiphy) { return wiphy->_net; } static inline void wiphy_net_set(struct wiphy *wiphy, struct net *net) { wiphy->_net = net; } #else static inline struct net *wiphy_net(struct wiphy *wiphy) { return &init_net; } static inline void wiphy_net_set(struct wiphy *wiphy, struct net *net) { } #endif static inline void *wiphy_priv(struct wiphy *wiphy) { BUG_ON(!wiphy); return &wiphy->priv; } static inline struct wiphy *priv_to_wiphy(void *priv) { BUG_ON(!priv); return container_of(priv, struct wiphy, priv); } static inline void set_wiphy_dev(struct wiphy *wiphy, struct device *dev) { wiphy->dev.parent = dev; } static inline struct device *wiphy_dev(struct wiphy *wiphy) { return wiphy->dev.parent; } static inline const char *wiphy_name(struct wiphy *wiphy) { return dev_name(&wiphy->dev); } struct wiphy *wiphy_new(const struct cfg80211_ops *ops, int sizeof_priv); extern int wiphy_register(struct wiphy *wiphy); extern void wiphy_unregister(struct wiphy *wiphy); extern void wiphy_free(struct wiphy *wiphy); /* internal structs */ struct cfg80211_conn; struct cfg80211_internal_bss; struct cfg80211_cached_keys; #define MAX_AUTH_BSSES 4 struct wireless_dev { struct wiphy *wiphy; enum nl80211_iftype iftype; /* the remainder of this struct should be private to cfg80211 */ struct list_head list; struct net_device *netdev; struct list_head action_registrations; spinlock_t action_registrations_lock; struct mutex mtx; struct work_struct cleanup_work; bool use_4addr; /* currently used for IBSS and SME - might be rearranged later */ u8 ssid[IEEE80211_MAX_SSID_LEN]; u8 ssid_len; enum { CFG80211_SME_IDLE, CFG80211_SME_CONNECTING, CFG80211_SME_CONNECTED, } sme_state; struct cfg80211_conn *conn; struct cfg80211_cached_keys *connect_keys; struct list_head event_list; spinlock_t event_lock; struct cfg80211_internal_bss *authtry_bsses[MAX_AUTH_BSSES]; struct cfg80211_internal_bss *auth_bsses[MAX_AUTH_BSSES]; struct cfg80211_internal_bss *current_bss; /* associated / joined */ struct ieee80211_channel *channel; bool ps; int ps_timeout; #ifdef CONFIG_CFG80211_WEXT /* wext data */ struct { struct cfg80211_ibss_params ibss; struct cfg80211_connect_params connect; struct cfg80211_cached_keys *keys; u8 *ie; size_t ie_len; u8 bssid[ETH_ALEN], prev_bssid[ETH_ALEN]; u8 ssid[IEEE80211_MAX_SSID_LEN]; s8 default_key, default_mgmt_key; bool prev_bssid_valid; } wext; #endif }; static inline void *wdev_priv(struct wireless_dev *wdev) { BUG_ON(!wdev); return wiphy_priv(wdev->wiphy); } extern int ieee80211_channel_to_frequency(int chan); extern int ieee80211_frequency_to_channel(int freq); extern struct ieee80211_channel *__ieee80211_get_channel(struct wiphy *wiphy, int freq); static inline struct ieee80211_channel * ieee80211_get_channel(struct wiphy *wiphy, int freq) { return __ieee80211_get_channel(wiphy, freq); } struct ieee80211_rate * ieee80211_get_response_rate(struct ieee80211_supported_band *sband, u32 basic_rates, int bitrate); struct radiotap_align_size { uint8_t align:4, size:4; }; struct ieee80211_radiotap_namespace { const struct radiotap_align_size *align_size; int n_bits; uint32_t oui; uint8_t subns; }; struct ieee80211_radiotap_vendor_namespaces { const struct ieee80211_radiotap_namespace *ns; int n_ns; }; struct ieee80211_radiotap_iterator { struct ieee80211_radiotap_header *_rtheader; const struct ieee80211_radiotap_vendor_namespaces *_vns; const struct ieee80211_radiotap_namespace *current_namespace; unsigned char *_arg, *_next_ns_data; __le32 *_next_bitmap; unsigned char *this_arg; int this_arg_index; int this_arg_size; int is_radiotap_ns; int _max_length; int _arg_index; uint32_t _bitmap_shifter; int _reset_on_ext; }; extern int ieee80211_radiotap_iterator_init( struct ieee80211_radiotap_iterator *iterator, struct ieee80211_radiotap_header *radiotap_header, int max_length, const struct ieee80211_radiotap_vendor_namespaces *vns); extern int ieee80211_radiotap_iterator_next( struct ieee80211_radiotap_iterator *iterator); extern const unsigned char rfc1042_header[6]; extern const unsigned char bridge_tunnel_header[6]; unsigned int ieee80211_get_hdrlen_from_skb(const struct sk_buff *skb); unsigned int ieee80211_hdrlen(__le16 fc); int ieee80211_data_to_8023(struct sk_buff *skb, const u8 *addr, enum nl80211_iftype iftype); int ieee80211_data_from_8023(struct sk_buff *skb, const u8 *addr, enum nl80211_iftype iftype, u8 *bssid, bool qos); void ieee80211_amsdu_to_8023s(struct sk_buff *skb, struct sk_buff_head *list, const u8 *addr, enum nl80211_iftype iftype, const unsigned int extra_headroom); unsigned int cfg80211_classify8021d(struct sk_buff *skb); const u8 *cfg80211_find_ie(u8 eid, const u8 *ies, int len); extern int regulatory_hint(struct wiphy *wiphy, const char *alpha2); extern void wiphy_apply_custom_regulatory( struct wiphy *wiphy, const struct ieee80211_regdomain *regd); extern int freq_reg_info(struct wiphy *wiphy, u32 center_freq, u32 desired_bw_khz, const struct ieee80211_reg_rule **reg_rule); int cfg80211_wext_giwname(struct net_device *dev, struct iw_request_info *info, char *name, char *extra); int cfg80211_wext_siwmode(struct net_device *dev, struct iw_request_info *info, u32 *mode, char *extra); int cfg80211_wext_giwmode(struct net_device *dev, struct iw_request_info *info, u32 *mode, char *extra); int cfg80211_wext_siwscan(struct net_device *dev, struct iw_request_info *info, union iwreq_data *wrqu, char *extra); int cfg80211_wext_giwscan(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra); int cfg80211_wext_siwmlme(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra); int cfg80211_wext_giwrange(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra); int cfg80211_wext_siwgenie(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *extra); int cfg80211_wext_siwauth(struct net_device *dev, struct iw_request_info *info, struct iw_param *data, char *extra); int cfg80211_wext_giwauth(struct net_device *dev, struct iw_request_info *info, struct iw_param *data, char *extra); int cfg80211_wext_siwfreq(struct net_device *dev, struct iw_request_info *info, struct iw_freq *freq, char *extra); int cfg80211_wext_giwfreq(struct net_device *dev, struct iw_request_info *info, struct iw_freq *freq, char *extra); int cfg80211_wext_siwessid(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *ssid); int cfg80211_wext_giwessid(struct net_device *dev, struct iw_request_info *info, struct iw_point *data, char *ssid); int cfg80211_wext_siwrate(struct net_device *dev, struct iw_request_info *info, struct iw_param *rate, char *extra); int cfg80211_wext_giwrate(struct net_device *dev, struct iw_request_info *info, struct iw_param *rate, char *extra); int cfg80211_wext_siwrts(struct net_device *dev, struct iw_request_info *info, struct iw_param *rts, char *extra); int cfg80211_wext_giwrts(struct net_device *dev, struct iw_request_info *info, struct iw_param *rts, char *extra); int cfg80211_wext_siwfrag(struct net_device *dev, struct iw_request_info *info, struct iw_param *frag, char *extra); int cfg80211_wext_giwfrag(struct net_device *dev, struct iw_request_info *info, struct iw_param *frag, char *extra); int cfg80211_wext_siwretry(struct net_device *dev, struct iw_request_info *info, struct iw_param *retry, char *extra); int cfg80211_wext_giwretry(struct net_device *dev, struct iw_request_info *info, struct iw_param *retry, char *extra); int cfg80211_wext_siwencodeext(struct net_device *dev, struct iw_request_info *info, struct iw_point *erq, char *extra); int cfg80211_wext_siwencode(struct net_device *dev, struct iw_request_info *info, struct iw_point *erq, char *keybuf); int cfg80211_wext_giwencode(struct net_device *dev, struct iw_request_info *info, struct iw_point *erq, char *keybuf); int cfg80211_wext_siwtxpower(struct net_device *dev, struct iw_request_info *info, union iwreq_data *data, char *keybuf); int cfg80211_wext_giwtxpower(struct net_device *dev, struct iw_request_info *info, union iwreq_data *data, char *keybuf); struct iw_statistics *cfg80211_wireless_stats(struct net_device *dev); int cfg80211_wext_siwpower(struct net_device *dev, struct iw_request_info *info, struct iw_param *wrq, char *extra); int cfg80211_wext_giwpower(struct net_device *dev, struct iw_request_info *info, struct iw_param *wrq, char *extra); int cfg80211_wext_siwap(struct net_device *dev, struct iw_request_info *info, struct sockaddr *ap_addr, char *extra); int cfg80211_wext_giwap(struct net_device *dev, struct iw_request_info *info, struct sockaddr *ap_addr, char *extra); void cfg80211_scan_done(struct cfg80211_scan_request *request, bool aborted); struct cfg80211_bss* cfg80211_inform_bss_frame(struct wiphy *wiphy, struct ieee80211_channel *channel, struct ieee80211_mgmt *mgmt, size_t len, s32 signal, gfp_t gfp); struct cfg80211_bss* cfg80211_inform_bss(struct wiphy *wiphy, struct ieee80211_channel *channel, const u8 *bssid, u64 timestamp, u16 capability, u16 beacon_interval, const u8 *ie, size_t ielen, s32 signal, gfp_t gfp); struct cfg80211_bss *cfg80211_get_bss(struct wiphy *wiphy, struct ieee80211_channel *channel, const u8 *bssid, const u8 *ssid, size_t ssid_len, u16 capa_mask, u16 capa_val); static inline struct cfg80211_bss * cfg80211_get_ibss(struct wiphy *wiphy, struct ieee80211_channel *channel, const u8 *ssid, size_t ssid_len) { return cfg80211_get_bss(wiphy, channel, NULL, ssid, ssid_len, WLAN_CAPABILITY_IBSS, WLAN_CAPABILITY_IBSS); } struct cfg80211_bss *cfg80211_get_mesh(struct wiphy *wiphy, struct ieee80211_channel *channel, const u8 *meshid, size_t meshidlen, const u8 *meshcfg); void cfg80211_put_bss(struct cfg80211_bss *bss); void cfg80211_unlink_bss(struct wiphy *wiphy, struct cfg80211_bss *bss); void cfg80211_send_rx_auth(struct net_device *dev, const u8 *buf, size_t len); void cfg80211_send_auth_timeout(struct net_device *dev, const u8 *addr); void __cfg80211_auth_canceled(struct net_device *dev, const u8 *addr); void cfg80211_send_rx_assoc(struct net_device *dev, const u8 *buf, size_t len); void cfg80211_send_assoc_timeout(struct net_device *dev, const u8 *addr); void cfg80211_send_deauth(struct net_device *dev, const u8 *buf, size_t len); void __cfg80211_send_deauth(struct net_device *dev, const u8 *buf, size_t len); void cfg80211_send_disassoc(struct net_device *dev, const u8 *buf, size_t len); void __cfg80211_send_disassoc(struct net_device *dev, const u8 *buf, size_t len); void cfg80211_michael_mic_failure(struct net_device *dev, const u8 *addr, enum nl80211_key_type key_type, int key_id, const u8 *tsc, gfp_t gfp); void cfg80211_ibss_joined(struct net_device *dev, const u8 *bssid, gfp_t gfp); void wiphy_rfkill_set_hw_state(struct wiphy *wiphy, bool blocked); void wiphy_rfkill_start_polling(struct wiphy *wiphy); void wiphy_rfkill_stop_polling(struct wiphy *wiphy); #ifdef CONFIG_NL80211_TESTMODE struct sk_buff *cfg80211_testmode_alloc_reply_skb(struct wiphy *wiphy, int approxlen); int cfg80211_testmode_reply(struct sk_buff *skb); struct sk_buff *cfg80211_testmode_alloc_event_skb(struct wiphy *wiphy, int approxlen, gfp_t gfp); void cfg80211_testmode_event(struct sk_buff *skb, gfp_t gfp); #define CFG80211_TESTMODE_CMD(cmd) .testmode_cmd = (cmd), #else #define CFG80211_TESTMODE_CMD(cmd) #endif void cfg80211_connect_result(struct net_device *dev, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, u16 status, gfp_t gfp); void cfg80211_roamed(struct net_device *dev, const u8 *bssid, const u8 *req_ie, size_t req_ie_len, const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp); void cfg80211_disconnected(struct net_device *dev, u16 reason, u8 *ie, size_t ie_len, gfp_t gfp); void cfg80211_ready_on_channel(struct net_device *dev, u64 cookie, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type, unsigned int duration, gfp_t gfp); void cfg80211_remain_on_channel_expired(struct net_device *dev, u64 cookie, struct ieee80211_channel *chan, enum nl80211_channel_type channel_type, gfp_t gfp); void cfg80211_new_sta(struct net_device *dev, const u8 *mac_addr, struct station_info *sinfo, gfp_t gfp); bool cfg80211_rx_action(struct net_device *dev, int freq, const u8 *buf, size_t len, gfp_t gfp); void cfg80211_action_tx_status(struct net_device *dev, u64 cookie, const u8 *buf, size_t len, bool ack, gfp_t gfp); void cfg80211_cqm_rssi_notify(struct net_device *dev, enum nl80211_cqm_rssi_threshold_event rssi_event, gfp_t gfp); #endif /* __NET_CFG80211_H */
luckasfb/OT_903D-kernel-2.6.35.7
kernel/include/net/cfg80211.h
C
gpl-2.0
28,919
<?php /******************************************************************************* Copyright 2013 Whole Foods Community Co-op This file is part of CORE-POS. CORE-POS 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. CORE-POS 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 in the file license.txt along with IT CORE; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *********************************************************************************/ require(dirname(__FILE__) . '/../config.php'); if (!class_exists('FannieAPI')) { include($FANNIE_ROOT.'classlib2.0/FannieAPI.php'); } class EditItemsFromSearch extends FannieRESTfulPage { protected $header = 'Edit Search Results'; protected $title = 'Edit Search Results'; public $description = '[Edit Search Results] takes a set of advanced search items and allows editing some fields on all items simultaneously. Must be accessed via Advanced Search.'; public $themed = true; private $upcs = array(); private $save_results = array(); function preprocess() { $this->__routes[] = 'post<u>'; $this->__routes[] = 'post<save>'; return parent::preprocess(); } function post_save_handler() { global $FANNIE_OP_DB; $upcs = FormLib::get('upc', array()); if (!is_array($upcs) || empty($upcs)) { echo 'Error: invalid data'; return false; } $dept = FormLib::get('dept'); $tax = FormLib::get('tax'); $local = FormLib::get('local'); $brand = FormLib::get('brand'); $vendor = FormLib::get('vendor'); $discount = FormLib::get('discount'); $dbc = FannieDB::get($FANNIE_OP_DB); $vlookup = new VendorsModel($dbc); $model = new StoresModel($dbc); $model->hasOwnItems(1); $stores = $model->find(); $model = new ProductsModel($dbc); $extra = new ProdExtraModel($dbc); for ($i=0; $i<count($upcs); $i++) { $upc = BarcodeLib::padUPC($upcs[$i]); $model->upc($upc); $model = $this->setArrayValue($model, 'department', $dept, $i); $model = $this->setArrayValue($model, 'tax', $tax, $i); $model = $this->setArrayValue($model, 'local', $local, $i); $model = $this->setArrayValue($model, 'brand', $brand, $i); if (isset($vendor[$i])) { $model = $this->setVendorByName($model, $vlookup, $vendor[$i]); } $model = $this->setDiscounts($model, $discount, $i); $model = $this->setBinaryFlag($model, $upc, 'fs', 'foodstamp'); $model = $this->setBinaryFlag($model, $upc, 'scale', 'scale'); $model = $this->setBinaryFlag($model, $upc, 'inUse', 'inUse'); $model->modified(date('Y-m-d H:i:s')); if ($this->config->get('STORE_MODE') == 'HQ') { foreach ($stores as $store) { $model->store_id($store->storeID()); $try = $model->save(); } } else { $try = $model->save(); } if ($try && count($upcs) <= 10) { $model->pushToLanes(); } elseif (!$try) { $this->save_results[] = 'Error saving item '.$upc; } if ((isset($vendor[$i]) && $vendor[$i] != '') || (isset($brand[$i]) && $brand[$i] != '')) { $this->updateProdExtra($extra, $upc, isset($brand[$i]) ? $brand[$i] : '', isset($vendor[$i]) ? $vendor[$i] : ''); } $this->upcs[] = $upc; } return true; } private function setDiscounts($pmodel, $arr, $index) { if (!isset($arr[$index])) { return $pmodel; } if ($arr[$index] == 1 || $arr[$index] == 2) { $pmodel->discount(1); } else { $pmodel->discount(0); } if ($arr[$index] == 1 || $arr[$index] == 3) { $pmodel->line_item_discountable(1); } else { $pmodel->line_item_discountable(0); } return $pmodel; } private $vcache = array(); private function setVendorByName($pmodel, $vmodel, $name) { if (isset($this->vcache[$name])) { $pmodel->default_vendor_id($this->vcache[$name]); } else { $vmodel->reset(); $vmodel->vendorName($name); foreach ($vmodel->find('vendorID') as $obj) { $pmodel->default_vendor_id($obj->vendorID()); $this->vcache[$name] = $obj->vendorID(); break; } } return $pmodel; } private function setArrayValue($model, $column, $arr, $index) { if (isset($arr[$index])) { $model->$column($arr[$index]); } return $model; } private function setBinaryFlag($model, $upc, $field, $column) { if (in_array($upc, FormLib::get($field, array()))) { $model->$column(1); } else { $model->$column(0); } return $model; } private function updateProdExtra($extra, $upc, $brand, $vendor) { $extra->upc($upc); $extra->distributor($vendor); $extra->manufacturer($brand); $extra->save(); } function post_save_view() { $ret = ''; if (!empty($this->save_results)) { $ret .= '<ul style="color:red;">'; foreach($this->save_results as $msg) { $ret .= '<li>' . $msg . '</li>'; } $ret .= '</ul>'; } else { $ret .= '<ul style="color:green;"><li>Saved!</li></ul>'; } return $ret . $this->post_u_view(); } function post_u_handler() { if (!is_array($this->u)) { $this->u = array($this->u); } foreach($this->u as $postdata) { if (is_numeric($postdata)) { $this->upcs[] = BarcodeLib::padUPC($postdata); } } if (empty($this->upcs)) { echo 'Error: no valid data'; return false; } else { return true; } } private function getTaxes($dbc) { $taxes = array(0 => 'NoTax'); $taxerates = $dbc->query('SELECT id, description FROM taxrates'); while($row = $dbc->fetch_row($taxerates)) { $taxes[$row['id']] = $row['description']; } return $taxes; } private function getDepts($dbc) { $depts = array(); $deptlist = $dbc->query('SELECT dept_no, dept_name FROM departments ORDER BY dept_no'); while($row = $dbc->fetch_row($deptlist)) { $depts[$row['dept_no']] = $row['dept_name']; } return $depts; } private function getBrandOpts($dbc) { $ret = '<option value=""></option>'; $brands = $dbc->query(' SELECT brand FROM vendorItems WHERE brand IS NOT NULL AND brand <> \'\' GROUP BY brand UNION SELECT brand FROM products WHERE brand IS NOT NULL AND brand <> \'\' GROUP BY brand ORDER BY brand'); while($row = $dbc->fetch_row($brands)) { $ret .= '<option>' . $row['brand'] . '</option>'; } return $ret; } private function arrayToOpts($arr, $selected=-999, $id_label=false) { $opts = ''; foreach ($arr as $num => $name) { if ($id_label === true) { $name = $num . ' ' . $name; } $opts .= sprintf('<option %s value="%d">%s</option>', ($num == $selected ? 'selected' : ''), $num, $name); } return $opts; } function post_u_view() { global $FANNIE_OP_DB, $FANNIE_URL; $ret = ''; $dbc = FannieDB::get($FANNIE_OP_DB); $locales = array(0 => 'No'); $origin = new OriginsModel($dbc); $locales = array_merge($locales, $origin->getLocalOrigins()); $taxes = $this->getTaxes($dbc); $depts = $this->getDepts($dbc); $ret .= '<form action="EditItemsFromSearch.php" method="post">'; $ret .= '<table class="table small">'; $ret .= '<tr> <th>UPC</th> <th>Description</th> <th>Brand</th> <th>Vendor</th> <th>Department</th> <th>Tax</th> <th>FS</th> <th>Scale</th> <th>%Disc</th> <th>Local</th> <th>InUse</th> </tr>'; $ret .= '<tr><th colspan="2">Change All &nbsp;&nbsp;&nbsp;<button type="reset" class="btn btn-default">Reset</button></th>'; /** List known brands from vendorItems as a drop down selection rather than free text entry. prodExtra remains an imperfect solution but this can at least start normalizing that data */ $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.brandField\');">'; $ret .= $this->getBrandOpts($dbc); $ret .= '</select></td>'; /** See brand above */ $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.vendorField\');">'; $ret .= '<option value=""></option><option>DIRECT</option>'; $res = $dbc->query('SELECT vendorName FROM vendors ORDER BY vendorName'); while ($row = $dbc->fetchRow($res)) { $ret .= '<option>' . $row['vendorName'] . '</option>'; } $ret .= '</select></td>'; $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.deptSelect\');">'; $ret .= $this->arrayToOpts($depts, -999, true); $ret .= '</select></td>'; $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.taxSelect\');">'; $ret .= $this->arrayToOpts($taxes); $ret .= '</select></td>'; $ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.fsCheckBox\');" /></td>'; $ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.scaleCheckBox\');" /></td>'; $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.discSelect\');">'; $ret .= $this->discountOpts(0, 0); $ret .= '</select></td>'; $ret .= '<td><select class="form-control input-sm" onchange="updateAll(this.value, \'.localSelect\');">'; $ret .= $this->arrayToOpts($locales); $ret .= '</select></td>'; $ret .= '<td><input type="checkbox" onchange="toggleAll(this, \'.inUseCheckBox\');" /></td>'; $ret .= '</tr>'; list($in_sql, $args) = $dbc->safeInClause($this->upcs); $query = 'SELECT p.upc, p.description, p.department, d.dept_name, p.tax, p.foodstamp, p.discount, p.scale, p.local, x.manufacturer, x.distributor, p.line_item_discountable, p.inUse FROM products AS p LEFT JOIN departments AS d ON p.department=d.dept_no LEFT JOIN prodExtra AS x ON p.upc=x.upc WHERE p.upc IN (' . $in_sql . ') ORDER BY p.upc'; $prep = $dbc->prepare($query); $result = $dbc->execute($prep, $args); while ($row = $dbc->fetch_row($result)) { $deptOpts = $this->arrayToOpts($depts, $row['department'], true); $taxOpts = $this->arrayToOpts($taxes, $row['tax']); $localOpts = $this->arrayToOpts($locales, $row['local']); $ret .= sprintf('<tr> <td> <a href="ItemEditorPage.php?searchupc=%s" target="_edit%s">%s</a> <input type="hidden" class="upcInput" name="upc[]" value="%s" /> </td> <td>%s</td> <td><input type="text" name="brand[]" class="brandField form-control input-sm" value="%s" /></td> <td><input type="text" name="vendor[]" class="vendorField form-control input-sm" value="%s" /></td> <td><select name="dept[]" class="deptSelect form-control input-sm">%s</select></td> <td><select name="tax[]" class="taxSelect form-control input-sm">%s</select></td> <td><input type="checkbox" name="fs[]" class="fsCheckBox" value="%s" %s /></td> <td><input type="checkbox" name="scale[]" class="scaleCheckBox" value="%s" %s /></td> <td><select class="form-control input-sm discSelect" name="discount[]">%s</select></td> <td><select name="local[]" class="localSelect form-control input-sm">%s</select></td> <td><input type="checkbox" name="inUse[]" class="inUseCheckBox" value="%s" %s /></td> </tr>', $row['upc'], $row['upc'], $row['upc'], $row['upc'], $row['description'], $row['manufacturer'], $row['distributor'], $deptOpts, $taxOpts, $row['upc'], ($row['foodstamp'] == 1 ? 'checked' : ''), $row['upc'], ($row['scale'] == 1 ? 'checked' : ''), $this->discountOpts($row['discount'], $row['line_item_discountable']), $localOpts, $row['upc'], ($row['inUse'] == 1 ? 'checked' : '') ); } $ret .= '</table>'; $ret .= '<p>'; $ret .= '<button type="submit" name="save" class="btn btn-default" value="1">Save Changes</button>'; $ret .= '</form>'; return $ret; } private function discountOpts($reg, $line) { $opts = array('No', 'Yes', 'Trans Only', 'Line Only'); $index = 0; if ($reg == 1 && $line == 1) { $index = 1; } elseif ($reg == 1 && $line == 0) { $index = 2; } elseif ($reg == 0 && $line == 1) { $index = 3; } $ret = ''; foreach ($opts as $key => $val) { $ret .= sprintf('<option %s value="%d">%s</option>', ($index == $key ? 'selected' : ''), $key, $val); } return $ret; } function javascript_content() { ob_start(); ?> function toggleAll(elem, selector) { if (elem.checked) { $(selector).prop('checked', true); } else { $(selector).prop('checked', false); } } function updateAll(val, selector) { $(selector).val(val); } <?php return ob_get_clean(); } public function helpContent() { return '<p> This tool edits some attributes of several products at once. The set of products must be built first using advanced search. </p> <p> Editing the top row will apply the change to all products in the list. Editing individual rows will only change the product. Changes are not instantaneous. Clicking the save button when finished is required. </p>'; } public function unitTest($phpunit) { $phpunit->assertNotEquals(0, strlen($this->javascript_content())); $this->u = 'foo'; $phpunit->assertEquals(false, $this->post_u_handler()); $this->u = '4011'; $phpunit->assertEquals(true, $this->post_u_handler()); $phpunit->assertNotEquals(0, strlen($this->post_u_view())); $phpunit->assertNotEquals(0, strlen($this->post_save_view())); } } FannieDispatch::conditionalExec();
FranklinCoop/IS4C
fannie/item/EditItemsFromSearch.php
PHP
gpl-2.0
16,817
<html> <head> <title>RunUO Documentation - Class Overview - OrigamiPaper</title> </head> <body bgcolor="white" style="font-family: Courier New" text="#000000" link="#000000" vlink="#000000" alink="#808080"> <h4><a href="../namespaces/Server.Items.html">Back to Server.Items</a></h4> <h2>OrigamiPaper : <!-- DBG-1 --><a href="Item.html">Item</a>, <!-- DBG-2.2 --><a href="IHued.html">IHued</a>, <!-- DBG-2.1 --><font color="blue">IComparable</font>&lt;<a href="Item.html">Item</a>&gt;, <!-- DBG-2.2 --><a href="ISerializable.html">ISerializable</a>, <!-- DBG-2.2 --><a href="ISpawnable.html">ISpawnable</a>, <!-- DBG-2.2 --><a href="IEntity.html">IEntity</a>, <!-- DBG-2.2 --><a href="IPoint3D.html">IPoint3D</a>, <!-- DBG-2.2 --><a href="IPoint2D.html">IPoint2D</a>, <!-- DBG-2.1 --><font color="blue">IComparable</font>, <!-- DBG-2.1 --><font color="blue">IComparable</font>&lt;<a href="IEntity.html">IEntity</a>&gt;</h2> (<font color="blue">ctor</font>) OrigamiPaper()<br> (<font color="blue">ctor</font>) OrigamiPaper( <!-- DBG-0 --><a href="Serial.html">Serial</a> serial )<br> <font color="blue">int</font> LabelNumber( <font color="blue">get</font>; )<br> <font color="blue">virtual</font> <font color="blue">void</font> Deserialize( <!-- DBG-0 --><a href="GenericReader.html">GenericReader</a> reader )<br> <font color="blue">virtual</font> <font color="blue">void</font> OnDoubleClick( <!-- DBG-0 --><a href="Mobile.html">Mobile</a> from )<br> <font color="blue">virtual</font> <font color="blue">void</font> Serialize( <!-- DBG-0 --><a href="GenericWriter.html">GenericWriter</a> writer )<br> </body> </html>
alucardxlx/matts-uo-server
docs/types/OrigamiPaper.html
HTML
gpl-2.0
1,699
<?php /* -------------------------------------------------------------- wcp_pbx.lang.inc.php 2015-01-05 gm Gambio GmbH http://www.gambio.de Copyright (c) 2015 Gambio GmbH Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- */ $t_language_text_section_content_array = array ( 'MODULE_PAYMENT_WCP_PBX_TEXT_DESCRIPTION' => 'You will be redirected to the Wirecard CEE payment page when you place an order.', 'MODULE_PAYMENT_WCP_PBX_TEXT_TITLE' => 'Mobile Phone Invoicing', 'MODULE_PAYMENT_WCP_PBX_TEXT_INFO' => '', 'MODULE_PAYMENT_WCP_PBX_STATUS_TITLE' => 'Active', 'MODULE_PAYMENT_WCP_PBX_STATUS_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_PRESHARED_KEY_TITLE' => 'Secret', 'MODULE_PAYMENT_WCP_PBX_PRESHARED_KEY_DESC' => 'Preshared secret key', 'MODULE_PAYMENT_WCP_PBX_CUSTOMER_ID_TITLE' => 'Customer ID', 'MODULE_PAYMENT_WCP_PBX_CUSTOMER_ID_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_LOGO_INCLUDE_TITLE' => 'Include Shop-Logo?', 'MODULE_PAYMENT_WCP_PBX_LOGO_INCLUDE_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_SHOP_ID_TITLE' => 'Shop ID', 'MODULE_PAYMENT_WCP_PBX_SHOP_ID_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_SERVICE_URL_TITLE' => 'Service URL', 'MODULE_PAYMENT_WCP_PBX_SERVICE_URL_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_DUPLICATE_REQUEST_CHECK_TITLE' => 'Activate Duplicate-Request-Check', 'MODULE_PAYMENT_WCP_PBX_DUPLICATE_REQUEST_CHECK_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_STATEMENT_TITLE' => 'Customer Statement prefix', 'MODULE_PAYMENT_WCP_PBX_STATEMENT_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_DISPLAY_TEXT_TITLE' => 'Display Text', 'MODULE_PAYMENT_WCP_PBX_DISPLAY_TEXT_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_ORDER_DESCRIPTION_TITLE' => 'Order Description prefix', 'MODULE_PAYMENT_WCP_PBX_ORDER_DESCRIPTION_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_USE_IFRAME_TITLE' => 'use iFrame?', 'MODULE_PAYMENT_WCP_PBX_USE_IFRAME_DESC' => '', 'MODULE_PAYMENT_WCP_PBX_SORT_ORDER_TITLE' => 'Sort order of display', 'MODULE_PAYMENT_WCP_PBX_SORT_ORDER_DESC' => 'Lowest is displayed first', 'MODULE_PAYMENT_WCP_PBX_ALLOWED_TITLE' => 'Allowed Zones', 'MODULE_PAYMENT_WCP_PBX_ALLOWED_DESC' => 'Insert Allowed Zones (e.g. AT,DE)', 'MODULE_PAYMENT_WCP_PBX_CHECKOUT_TITLE' => 'Payment process', 'MODULE_PAYMENT_WCP_PBX_CHECKOUT_HEADER' => '', 'MODULE_PAYMENT_WCP_PBX_CHECKOUT_CONTENT' => '<center>You will be redirected. Press "continue" if not!</center>', 'MODULE_PAYMENT_WCP_PBX_REDIRECT_TIMEOUT_SECOUNDS' => '2' );
carlosway89/testshop
lang/english/original_sections/modules/payment/wcp_pbx.lang.inc.php
PHP
gpl-2.0
2,522
#ifndef __ASM_IRQ_H #define __ASM_IRQ_H #include <asm-generic/irq.h> extern void (*handle_arch_irq)(struct pt_regs *); extern void migrate_irqs(void); extern void set_handle_irq(void (*handle_irq)(struct pt_regs *)); /* void arch_trigger_all_cpu_backtrace(void); #define arch_trigger_all_cpu_backtrace arch_trigger_all_cpu_backtrace */ #endif
Honor8Dev/android_kernel_huawei_FRD-L04
arch/arm64/include/asm/irq.h
C
gpl-2.0
347
/* * * (C) COPYRIGHT 2015 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the * GNU General Public License version 2 as published by the Free Software * Foundation, and any use by you of this program is subject to the terms * of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifdef CONFIG_ARM64 #include <mali_kbase.h> #include <mali_kbase_smc.h> #include <linux/compiler.h> static noinline u64 invoke_smc_fid(u64 _function_id, u64 _arg0, u64 _arg1, u64 _arg2) { register u64 function_id asm("x0") = _function_id; register u64 arg0 asm("x1") = _arg0; register u64 arg1 asm("x2") = _arg1; register u64 arg2 asm("x3") = _arg2; asm volatile( __asmeq("%0", "x0") __asmeq("%1", "x1") __asmeq("%2", "x2") __asmeq("%3", "x3") "smc #0\n" : "+r" (function_id) : "r" (arg0), "r" (arg1), "r" (arg2)); return function_id; } u64 kbase_invoke_smc_fid(u32 fid, u64 arg0, u64 arg1, u64 arg2) { /* Is fast call (bit 31 set) */ KBASE_DEBUG_ASSERT(fid & ~SMC_FAST_CALL); /* bits 16-23 must be zero for fast calls */ KBASE_DEBUG_ASSERT((fid & (0xFF << 16)) == 0); return invoke_smc_fid(fid, arg0, arg1, arg2); } u64 kbase_invoke_smc(u32 oen, u16 function_number, bool smc64, u64 arg0, u64 arg1, u64 arg2) { u32 fid = 0; /* Only the six bits allowed should be used. */ KBASE_DEBUG_ASSERT((oen & ~SMC_OEN_MASK) == 0); fid |= SMC_FAST_CALL; /* Bit 31: Fast call */ if (smc64) fid |= SMC_64; /* Bit 30: 1=SMC64, 0=SMC32 */ fid |= oen; /* Bit 29:24: OEN */ /* Bit 23:16: Must be zero for fast calls */ fid |= (function_number); /* Bit 15:0: function number */ return kbase_invoke_smc_fid(fid, arg0, arg1, arg2); } #endif /* CONFIG_ARM64 */
alesaiko/UK-PRO5
drivers/gpu-r7p0/arm/t7xx/r7p0/mali_kbase_smc.c
C
gpl-2.0
1,912
#ifndef FILTERTREE_H #define FILTERTREE_H #include "carddatabase.h" #include "cardfilter.h" #include <QList> #include <QMap> #include <QObject> #include <utility> class FilterTreeNode { private: bool enabled; public: FilterTreeNode() : enabled(true) { } virtual bool isEnabled() const { return enabled; } virtual void enable() { enabled = true; nodeChanged(); } virtual void disable() { enabled = false; nodeChanged(); } virtual FilterTreeNode *parent() const { return nullptr; } virtual FilterTreeNode *nodeAt(int /* i */) const { return nullptr; } virtual void deleteAt(int /* i */) { } virtual int childCount() const { return 0; } virtual int childIndex(const FilterTreeNode * /* node */) const { return -1; } virtual int index() const { return (parent() != nullptr) ? parent()->childIndex(this) : -1; } virtual const QString text() const { return QString(""); } virtual bool isLeaf() const { return false; } virtual void nodeChanged() const { if (parent() != nullptr) parent()->nodeChanged(); } virtual void preInsertChild(const FilterTreeNode *p, int i) const { if (parent() != nullptr) parent()->preInsertChild(p, i); } virtual void postInsertChild(const FilterTreeNode *p, int i) const { if (parent() != nullptr) parent()->postInsertChild(p, i); } virtual void preRemoveChild(const FilterTreeNode *p, int i) const { if (parent() != nullptr) parent()->preRemoveChild(p, i); } virtual void postRemoveChild(const FilterTreeNode *p, int i) const { if (parent() != nullptr) parent()->postRemoveChild(p, i); } }; template <class T> class FilterTreeBranch : public FilterTreeNode { protected: QList<T> childNodes; public: virtual ~FilterTreeBranch(); FilterTreeNode *nodeAt(int i) const override; void deleteAt(int i) override; int childCount() const override { return childNodes.size(); } int childIndex(const FilterTreeNode *node) const override; }; class FilterItemList; class FilterTree; class LogicMap : public FilterTreeBranch<FilterItemList *> { private: FilterTree *const p; public: const CardFilter::Attr attr; LogicMap(CardFilter::Attr a, FilterTree *parent) : p(parent), attr(a) { } const FilterItemList *findTypeList(CardFilter::Type type) const; FilterItemList *typeList(CardFilter::Type type); FilterTreeNode *parent() const override; const QString text() const override { return CardFilter::attrName(attr); } }; class FilterItem; class FilterItemList : public FilterTreeBranch<FilterItem *> { private: LogicMap *const p; public: const CardFilter::Type type; FilterItemList(CardFilter::Type t, LogicMap *parent) : p(parent), type(t) { } CardFilter::Attr attr() const { return p->attr; } FilterTreeNode *parent() const override { return p; } int termIndex(const QString &term) const; FilterTreeNode *termNode(const QString &term); const QString text() const override { return CardFilter::typeName(type); } bool testTypeAnd(CardInfoPtr info, CardFilter::Attr attr) const; bool testTypeAndNot(CardInfoPtr info, CardFilter::Attr attr) const; bool testTypeOr(CardInfoPtr info, CardFilter::Attr attr) const; bool testTypeOrNot(CardInfoPtr info, CardFilter::Attr attr) const; }; class FilterItem : public FilterTreeNode { private: FilterItemList *const p; public: const QString term; FilterItem(QString trm, FilterItemList *parent) : p(parent), term(std::move(trm)) { } virtual ~FilterItem() = default; CardFilter::Attr attr() const { return p->attr(); } CardFilter::Type type() const { return p->type; } FilterTreeNode *parent() const override { return p; } const QString text() const override { return term; } bool isLeaf() const override { return true; } bool acceptName(CardInfoPtr info) const; bool acceptType(CardInfoPtr info) const; bool acceptColor(CardInfoPtr info) const; bool acceptText(CardInfoPtr info) const; bool acceptSet(CardInfoPtr info) const; bool acceptManaCost(CardInfoPtr info) const; bool acceptCmc(CardInfoPtr info) const; bool acceptPowerToughness(CardInfoPtr info, CardFilter::Attr attr) const; bool acceptLoyalty(CardInfoPtr info) const; bool acceptRarity(CardInfoPtr info) const; bool acceptCardAttr(CardInfoPtr info, CardFilter::Attr attr) const; bool relationCheck(int cardInfo) const; }; class FilterTree : public QObject, public FilterTreeBranch<LogicMap *> { Q_OBJECT signals: void preInsertRow(const FilterTreeNode *parent, int i) const; void postInsertRow(const FilterTreeNode *parent, int i) const; void preRemoveRow(const FilterTreeNode *parent, int i) const; void postRemoveRow(const FilterTreeNode *parent, int i) const; void changed() const; private: LogicMap *attrLogicMap(CardFilter::Attr attr); FilterItemList *attrTypeList(CardFilter::Attr attr, CardFilter::Type type); bool testAttr(CardInfoPtr info, const LogicMap *lm) const; void nodeChanged() const override { emit changed(); } void preInsertChild(const FilterTreeNode *p, int i) const override { emit preInsertRow(p, i); } void postInsertChild(const FilterTreeNode *p, int i) const override { emit postInsertRow(p, i); } void preRemoveChild(const FilterTreeNode *p, int i) const override { emit preRemoveRow(p, i); } void postRemoveChild(const FilterTreeNode *p, int i) const override { emit postRemoveRow(p, i); } public: FilterTree(); ~FilterTree() override; int findTermIndex(CardFilter::Attr attr, CardFilter::Type type, const QString &term); int findTermIndex(const CardFilter *f); FilterTreeNode *termNode(CardFilter::Attr attr, CardFilter::Type type, const QString &term); FilterTreeNode *termNode(const CardFilter *f); FilterTreeNode *attrTypeNode(CardFilter::Attr attr, CardFilter::Type type); const QString text() const override { return QString("root"); } int index() const override { return 0; } bool acceptsCard(CardInfoPtr info) const; void clear(); }; #endif
marcofernandezheras/Cockatrice
cockatrice/src/filtertree.h
C
gpl-2.0
6,694
#ifndef ASM_KVM_CACHE_REGS_H #define ASM_KVM_CACHE_REGS_H #define KVM_POSSIBLE_CR0_GUEST_BITS X86_CR0_TS #define KVM_POSSIBLE_CR4_GUEST_BITS \ (X86_CR4_PVI | X86_CR4_DE | X86_CR4_PCE | X86_CR4_OSFXSR \ | X86_CR4_OSXMMEXCPT | X86_CR4_PGE) static inline unsigned long kvm_register_read(struct kvm_vcpu *vcpu, enum kvm_reg reg) { if (!test_bit(reg, (unsigned long *)&vcpu->arch.regs_avail)) kvm_x86_ops->cache_reg(vcpu, reg); return vcpu->arch.regs[reg]; } static inline void kvm_register_write(struct kvm_vcpu *vcpu, enum kvm_reg reg, unsigned long val) { vcpu->arch.regs[reg] = val; __set_bit(reg, (unsigned long *)&vcpu->arch.regs_dirty); __set_bit(reg, (unsigned long *)&vcpu->arch.regs_avail); } static inline unsigned long kvm_rip_read(struct kvm_vcpu *vcpu) { return kvm_register_read(vcpu, VCPU_REGS_RIP); } static inline void kvm_rip_write(struct kvm_vcpu *vcpu, unsigned long val) { kvm_register_write(vcpu, VCPU_REGS_RIP, val); } static inline u64 kvm_pdptr_read(struct kvm_vcpu *vcpu, int index) { if (!test_bit(VCPU_EXREG_PDPTR, (unsigned long *)&vcpu->arch.regs_avail)) kvm_x86_ops->cache_reg(vcpu, VCPU_EXREG_PDPTR); return vcpu->arch.pdptrs[index]; } static inline ulong kvm_read_cr0_bits(struct kvm_vcpu *vcpu, ulong mask) { ulong tmask = mask & KVM_POSSIBLE_CR0_GUEST_BITS; if (tmask & vcpu->arch.cr0_guest_owned_bits) kvm_x86_ops->decache_cr0_guest_bits(vcpu); return vcpu->arch.cr0 & mask; } static inline ulong kvm_read_cr0(struct kvm_vcpu *vcpu) { return kvm_read_cr0_bits(vcpu, ~0UL); } static inline ulong kvm_read_cr4_bits(struct kvm_vcpu *vcpu, ulong mask) { ulong tmask = mask & KVM_POSSIBLE_CR4_GUEST_BITS; if (tmask & vcpu->arch.cr4_guest_owned_bits) kvm_x86_ops->decache_cr4_guest_bits(vcpu); return vcpu->arch.cr4 & mask; } static inline ulong kvm_read_cr4(struct kvm_vcpu *vcpu) { return kvm_read_cr4_bits(vcpu, ~0UL); } #endif
luckasfb/OT_903D-kernel-2.6.35.7
kernel/arch/x86/kvm/kvm_cache_regs.h
C
gpl-2.0
1,944
/** ****************************************************************************** * @file stm32f7xx_hal_adc_ex.c * @author MCD Application Team * @version V1.0.3 * @date 13-November-2015 * @brief This file provides firmware functions to manage the following * functionalities of the ADC extension peripheral: * + Extended features functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit(): (##) Enable the ADC interface clock using __HAL_RCC_ADC_CLK_ENABLE() (##) ADC pins configuration (+++) Enable the clock for the ADC GPIOs using the following function: __HAL_RCC_GPIOx_CLK_ENABLE() (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init() (##) In case of using interrupts (e.g. HAL_ADC_Start_IT()) (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority() (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ() (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler() (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA()) (+++) Enable the DMAx interface clock using __HAL_RCC_DMAx_CLK_ENABLE() (+++) Configure and enable two DMA streams stream for managing data transfer from peripheral to memory (output stream) (+++) Associate the initialized DMA handle to the ADC DMA handle using __HAL_LINKDMA() (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the two DMA Streams. The output stream should have higher priority than the input stream. (#) Configure the ADC Prescaler, conversion resolution and data alignment using the HAL_ADC_Init() function. (#) Configure the ADC Injected channels group features, use HAL_ADC_Init() and HAL_ADC_ConfigChannel() functions. (#) Three operation modes are available within this driver : *** Polling mode IO operation *** ================================= [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart() (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage user can specify the value of timeout according to his end application (+) To read the ADC converted values, use the HAL_ADCEx_InjectedGetValue() function. (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop() *** Interrupt mode IO operation *** =================================== [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_IT() (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine (+) At ADC end of conversion HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback (+) In case of ADC Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_IT() *** DMA mode IO operation *** ============================== [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_DMA(), at this stage the user specify the length of data to be transferred at each end of conversion (+) At The end of data transfer ba HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback (+) In case of transfer Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_DMA() *** Multi mode ADCs Regular channels configuration *** ====================================================== [..] (+) Select the Multi mode ADC regular channels features (dual or triple mode) and configure the DMA mode using HAL_ADCEx_MultiModeConfigChannel() functions. (+) Start the ADC peripheral using HAL_ADCEx_MultiModeStart_DMA(), at this stage the user specify the length of data to be transferred at each end of conversion (+) Read the ADCs converted values using the HAL_ADCEx_MultiModeGetValue() function. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics 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 HOLDER 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f7xx_hal.h" /** @addtogroup STM32F7xx_HAL_Driver * @{ */ /** @defgroup ADCEx ADCEx * @brief ADC Extended driver modules * @{ */ #ifdef HAL_ADC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /** @addtogroup ADCEx_Private_Functions * @{ */ /* Private function prototypes -----------------------------------------------*/ static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma); static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma); static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma); /** * @} */ /* Exported functions --------------------------------------------------------*/ /** @defgroup ADCEx_Exported_Functions ADC Exported Functions * @{ */ /** @defgroup ADCEx_Exported_Functions_Group1 Extended features functions * @brief Extended features functions * @verbatim =============================================================================== ##### Extended features functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Start conversion of injected channel. (+) Stop conversion of injected channel. (+) Start multimode and enable DMA transfer. (+) Stop multimode and disable DMA transfer. (+) Get result of injected channel conversion. (+) Get result of multimode conversion. (+) Configure injected channels. (+) Configure multimode. @endverbatim * @{ */ /** * @brief Enables the selected ADC software start conversion of the injected channels. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc) { __IO uint32_t counter = 0; uint32_t tmp1 = 0, tmp2 = 0; /* Process locked */ __HAL_LOCK(hadc); /* Enable the ADC peripheral */ /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay for ADC stabilization time */ /* Compute number of CPU cycles to wait for */ counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000)); while(counter != 0) { counter--; } } /* Start conversion if ADC is effectively enabled */ if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Set ADC state */ /* - Clear state bitfield related to injected group conversion results */ /* - Set state bitfield related to injected operation */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY); /* Check if a regular conversion is ongoing */ /* Note: On this device, there is no ADC error code fields related to */ /* conversions on group injected only. In case of conversion on */ /* going on group regular, no error code is reset. */ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) { /* Reset ADC all error code fields */ ADC_CLEAR_ERRORCODE(hadc); } /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Clear injected group conversion flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); /* Check if Multimode enabled */ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if(tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } else { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if((hadc->Instance == ADC1) && tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } } /* Return function status */ return HAL_OK; } /** * @brief Enables the interrupt and starts ADC conversion of injected channels. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc) { __IO uint32_t counter = 0; uint32_t tmp1 = 0, tmp2 = 0; /* Process locked */ __HAL_LOCK(hadc); /* Enable the ADC peripheral */ /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay for ADC stabilization time */ /* Compute number of CPU cycles to wait for */ counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000)); while(counter != 0) { counter--; } } /* Start conversion if ADC is effectively enabled */ if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Set ADC state */ /* - Clear state bitfield related to injected group conversion results */ /* - Set state bitfield related to injected operation */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY); /* Check if a regular conversion is ongoing */ /* Note: On this device, there is no ADC error code fields related to */ /* conversions on group injected only. In case of conversion on */ /* going on group regular, no error code is reset. */ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) { /* Reset ADC all error code fields */ ADC_CLEAR_ERRORCODE(hadc); } /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Clear injected group conversion flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); /* Enable end of conversion interrupt for injected channels */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC); /* Check if Multimode enabled */ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if(tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } else { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if((hadc->Instance == ADC1) && tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } } /* Return function status */ return HAL_OK; } /** * @brief Stop conversion of injected channels. Disable ADC peripheral if * no regular conversion is on going. * @note If ADC must be disabled and if conversion is on going on * regular group, function HAL_ADC_Stop must be used to stop both * injected and regular groups, and disable the ADC. * @note If injected group mode auto-injection is enabled, * function HAL_ADC_Stop must be used. * @note In case of auto-injection mode, HAL_ADC_Stop must be used. * @param hadc: ADC handle * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* Stop potential conversion and disable ADC peripheral */ /* Conditioned to: */ /* - No conversion on the other group (regular group) is intended to */ /* continue (injected and regular groups stop conversion and ADC disable */ /* are common) */ /* - In case of auto-injection mode, HAL_ADC_Stop must be used. */ if(((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) && HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) ) { /* Stop potential conversion on going, on regular and injected groups */ /* Disable ADC peripheral */ __HAL_ADC_DISABLE(hadc); /* Check if ADC is effectively disabled */ if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } else { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); tmp_hal_status = HAL_ERROR; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Poll for injected conversion complete * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param Timeout: Timeout value in millisecond. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); /* Check End of conversion flag */ while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC))) { /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hadc->State= HAL_ADC_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_TIMEOUT; } } } /* Clear injected group conversion flag */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JSTRT | ADC_FLAG_JEOC); /* Update ADC state machine */ SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC); /* Determine whether any further conversion upcoming on group injected */ /* by external trigger, continuous mode or scan sequence on going. */ /* Note: On STM32F7, there is no independent flag of end of sequence. */ /* The test of scan sequence on going is done either with scan */ /* sequence disabled or with end of conversion flag set to */ /* of end of sequence. */ if(ADC_IS_SOFTWARE_START_INJECTED(hadc) && (HAL_IS_BIT_CLR(hadc->Instance->JSQR, ADC_JSQR_JL) || HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS) ) && (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) && (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE) ) ) ) { /* Set ADC state */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY); if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) { SET_BIT(hadc->State, HAL_ADC_STATE_READY); } } /* Return ADC state */ return HAL_OK; } /** * @brief Stop conversion of injected channels, disable interruption of * end-of-conversion. Disable ADC peripheral if no regular conversion * is on going. * @note If ADC must be disabled and if conversion is on going on * regular group, function HAL_ADC_Stop must be used to stop both * injected and regular groups, and disable the ADC. * @note If injected group mode auto-injection is enabled, * function HAL_ADC_Stop must be used. * @param hadc: ADC handle * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* Stop potential conversion and disable ADC peripheral */ /* Conditioned to: */ /* - No conversion on the other group (regular group) is intended to */ /* continue (injected and regular groups stop conversion and ADC disable */ /* are common) */ /* - In case of auto-injection mode, HAL_ADC_Stop must be used. */ if(((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) && HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) ) { /* Stop potential conversion on going, on regular and injected groups */ /* Disable ADC peripheral */ __HAL_ADC_DISABLE(hadc); /* Check if ADC is effectively disabled */ if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Disable ADC end of conversion interrupt for injected channels */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC); /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } } else { /* Update ADC state machine to error */ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG); tmp_hal_status = HAL_ERROR; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Gets the converted value from data register of injected channel. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param InjectedRank: the ADC injected rank. * This parameter can be one of the following values: * @arg ADC_INJECTED_RANK_1: Injected Channel1 selected * @arg ADC_INJECTED_RANK_2: Injected Channel2 selected * @arg ADC_INJECTED_RANK_3: Injected Channel3 selected * @arg ADC_INJECTED_RANK_4: Injected Channel4 selected * @retval None */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank) { __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_ADC_INJECTED_RANK(InjectedRank)); /* Clear injected group conversion flag to have similar behaviour as */ /* regular group: reading data register also clears end of conversion flag. */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC); /* Return the selected ADC converted value */ switch(InjectedRank) { case ADC_INJECTED_RANK_4: { tmp = hadc->Instance->JDR4; } break; case ADC_INJECTED_RANK_3: { tmp = hadc->Instance->JDR3; } break; case ADC_INJECTED_RANK_2: { tmp = hadc->Instance->JDR2; } break; case ADC_INJECTED_RANK_1: { tmp = hadc->Instance->JDR1; } break; default: break; } return tmp; } /** * @brief Enables ADC DMA request after last transfer (Multi-ADC mode) and enables ADC peripheral * * @note Caution: This function must be used only with the ADC master. * * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param pData: Pointer to buffer in which transferred from ADC peripheral to memory will be stored. * @param Length: The length of data to be transferred from ADC peripheral to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) { __IO uint32_t counter = 0; /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); /* Process locked */ __HAL_LOCK(hadc); /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay for temperature sensor stabilization time */ /* Compute number of CPU cycles to wait for */ counter = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000)); while(counter != 0) { counter--; } } /* Start conversion if ADC is effectively enabled */ if(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Set ADC state */ /* - Clear state bitfield related to regular group conversion results */ /* - Set state bitfield related to regular group operation */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR, HAL_ADC_STATE_REG_BUSY); /* If conversions on group regular are also triggering group injected, */ /* update ADC state. */ if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET) { ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY); } /* State machine update: Check if an injected conversion is ongoing */ if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY)) { /* Reset ADC error code fields related to conversions on group regular */ CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA)); } else { /* Reset ADC all error code fields */ ADC_CLEAR_ERRORCODE(hadc); } /* Process unlocked */ /* Unlock before starting ADC conversions: in case of potential */ /* interruption, to let the process to ADC IRQ Handler. */ __HAL_UNLOCK(hadc); /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_MultiModeDMAConvCplt; /* Set the DMA half transfer complete callback */ hadc->DMA_Handle->XferHalfCpltCallback = ADC_MultiModeDMAHalfConvCplt; /* Set the DMA error callback */ hadc->DMA_Handle->XferErrorCallback = ADC_MultiModeDMAError ; /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ /* start (in case of SW start): */ /* Clear regular group conversion flag and overrun flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC); /* Enable ADC overrun interrupt */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); if (hadc->Init.DMAContinuousRequests != DISABLE) { /* Enable the selected ADC DMA request after last transfer */ ADC->CCR |= ADC_CCR_DDS; } else { /* Disable the selected ADC EOC rising on each regular channel conversion */ ADC->CCR &= ~ADC_CCR_DDS; } /* Enable the DMA Stream */ HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&ADC->CDR, (uint32_t)pData, Length); /* if no external trigger present enable software conversion of regular channels */ if((hadc->Instance->CR2 & ADC_CR2_EXTEN) == RESET) { /* Enable the selected ADC software conversion for regular group */ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART; } } /* Return function status */ return HAL_OK; } /** * @brief Disables ADC DMA (multi-ADC mode) and disables ADC peripheral * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) { HAL_StatusTypeDef tmp_hal_status = HAL_OK; /* Check the parameters */ assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); /* Process locked */ __HAL_LOCK(hadc); /* Stop potential conversion on going, on regular and injected groups */ /* Disable ADC peripheral */ __HAL_ADC_DISABLE(hadc); /* Check if ADC is effectively disabled */ if(HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_ADON)) { /* Disable the selected ADC DMA mode for multimode */ ADC->CCR &= ~ADC_CCR_DDS; /* Disable the DMA channel (in case of DMA in circular mode or stop while */ /* DMA transfer is on going) */ tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle); /* Disable ADC overrun interrupt */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); /* Set ADC state */ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY); } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return tmp_hal_status; } /** * @brief Returns the last ADC1, ADC2 and ADC3 regular conversions results * data in the selected multi mode. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval The converted data value. */ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc) { /* Return the multi mode conversion value */ return ADC->CDR; } /** * @brief Injected conversion complete callback in non blocking mode * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval None */ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc) { /* Prevent unused argument(s) compilation warning */ UNUSED(hadc); /* NOTE : This function Should not be modified, when the callback is needed, the HAL_ADC_InjectedConvCpltCallback could be implemented in the user file */ } /** * @brief Configures for the selected ADC injected channel its corresponding * rank in the sequencer and its sample time. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param sConfigInjected: ADC configuration structure for injected channel. * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected) { #ifdef USE_FULL_ASSERT uint32_t tmp = 0; #endif /* USE_FULL_ASSERT */ /* Check the parameters */ assert_param(IS_ADC_CHANNEL(sConfigInjected->InjectedChannel)); assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank)); assert_param(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime)); assert_param(IS_ADC_EXT_INJEC_TRIG(sConfigInjected->ExternalTrigInjecConv)); assert_param(IS_ADC_INJECTED_LENGTH(sConfigInjected->InjectedNbrOfConversion)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode)); #ifdef USE_FULL_ASSERT tmp = ADC_GET_RESOLUTION(hadc); assert_param(IS_ADC_RANGE(tmp, sConfigInjected->InjectedOffset)); #endif /* USE_FULL_ASSERT */ if(sConfigInjected->ExternalTrigInjecConvEdge != ADC_INJECTED_SOFTWARE_START) { assert_param(IS_ADC_EXT_INJEC_TRIG_EDGE(sConfigInjected->ExternalTrigInjecConvEdge)); } /* Process locked */ __HAL_LOCK(hadc); /* if ADC_Channel_10 ... ADC_Channel_18 is selected */ if (sConfigInjected->InjectedChannel > ADC_CHANNEL_9) { /* Clear the old sample time */ hadc->Instance->SMPR1 &= ~ADC_SMPR1(ADC_SMPR1_SMP10, sConfigInjected->InjectedChannel); /* Set the new sample time */ hadc->Instance->SMPR1 |= ADC_SMPR1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); } else /* ADC_Channel include in ADC_Channel_[0..9] */ { /* Clear the old sample time */ hadc->Instance->SMPR2 &= ~ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel); /* Set the new sample time */ hadc->Instance->SMPR2 |= ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); } /*---------------------------- ADCx JSQR Configuration -----------------*/ hadc->Instance->JSQR &= ~(ADC_JSQR_JL); hadc->Instance->JSQR |= ADC_SQR1(sConfigInjected->InjectedNbrOfConversion); /* Rank configuration */ /* Clear the old SQx bits for the selected rank */ hadc->Instance->JSQR &= ~ADC_JSQR(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); /* Set the SQx bits for the selected rank */ hadc->Instance->JSQR |= ADC_JSQR(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); /* Enable external trigger if trigger selection is different of software */ /* start. */ /* Note: This configuration keeps the hardware feature of parameter */ /* ExternalTrigConvEdge "trigger edge none" equivalent to */ /* software start. */ if(sConfigInjected->ExternalTrigInjecConv != ADC_INJECTED_SOFTWARE_START) { /* Select external trigger to start conversion */ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTSEL); hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConv; /* Select external trigger polarity */ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTEN); hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConvEdge; } else { /* Reset the external trigger */ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTSEL); hadc->Instance->CR2 &= ~(ADC_CR2_JEXTEN); } if (sConfigInjected->AutoInjectedConv != DISABLE) { /* Enable the selected ADC automatic injected group conversion */ hadc->Instance->CR1 |= ADC_CR1_JAUTO; } else { /* Disable the selected ADC automatic injected group conversion */ hadc->Instance->CR1 &= ~(ADC_CR1_JAUTO); } if (sConfigInjected->InjectedDiscontinuousConvMode != DISABLE) { /* Enable the selected ADC injected discontinuous mode */ hadc->Instance->CR1 |= ADC_CR1_JDISCEN; } else { /* Disable the selected ADC injected discontinuous mode */ hadc->Instance->CR1 &= ~(ADC_CR1_JDISCEN); } switch(sConfigInjected->InjectedRank) { case 1: /* Set injected channel 1 offset */ hadc->Instance->JOFR1 &= ~(ADC_JOFR1_JOFFSET1); hadc->Instance->JOFR1 |= sConfigInjected->InjectedOffset; break; case 2: /* Set injected channel 2 offset */ hadc->Instance->JOFR2 &= ~(ADC_JOFR2_JOFFSET2); hadc->Instance->JOFR2 |= sConfigInjected->InjectedOffset; break; case 3: /* Set injected channel 3 offset */ hadc->Instance->JOFR3 &= ~(ADC_JOFR3_JOFFSET3); hadc->Instance->JOFR3 |= sConfigInjected->InjectedOffset; break; default: /* Set injected channel 4 offset */ hadc->Instance->JOFR4 &= ~(ADC_JOFR4_JOFFSET4); hadc->Instance->JOFR4 |= sConfigInjected->InjectedOffset; break; } /* if ADC1 Channel_18 is selected enable VBAT Channel */ if ((hadc->Instance == ADC1) && (sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT)) { /* Enable the VBAT channel*/ ADC->CCR |= ADC_CCR_VBATE; } /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */ if ((hadc->Instance == ADC1) && ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT))) { /* Enable the TSVREFE channel*/ ADC->CCR |= ADC_CCR_TSVREFE; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Configures the ADC multi-mode * @param hadc : pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param multimode : pointer to an ADC_MultiModeTypeDef structure that contains * the configuration information for multimode. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode) { /* Check the parameters */ assert_param(IS_ADC_MODE(multimode->Mode)); assert_param(IS_ADC_DMA_ACCESS_MODE(multimode->DMAAccessMode)); assert_param(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay)); /* Process locked */ __HAL_LOCK(hadc); /* Set ADC mode */ ADC->CCR &= ~(ADC_CCR_MULTI); ADC->CCR |= multimode->Mode; /* Set the ADC DMA access mode */ ADC->CCR &= ~(ADC_CCR_DMA); ADC->CCR |= multimode->DMAAccessMode; /* Set delay between two sampling phases */ ADC->CCR &= ~(ADC_CCR_DELAY); ADC->CCR |= multimode->TwoSamplingDelay; /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @} */ /** * @brief DMA transfer complete callback. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma) { /* Retrieve ADC handle corresponding to current DMA handle */ ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* Update state machine on conversion status if not in error state */ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) { /* Update ADC state machine */ SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC); /* Determine whether any further conversion upcoming on group regular */ /* by external trigger, continuous mode or scan sequence on going. */ /* Note: On STM32F7, there is no independent flag of end of sequence. */ /* The test of scan sequence on going is done either with scan */ /* sequence disabled or with end of conversion flag set to */ /* of end of sequence. */ if(ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE) && (HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L) || HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_EOCS) ) ) { /* Disable ADC end of single conversion interrupt on group regular */ /* Note: Overrun interrupt was enabled with EOC interrupt in */ /* HAL_ADC_Start_IT(), but is not disabled here because can be used */ /* by overrun IRQ process below. */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); /* Set ADC state */ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY); if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY)) { SET_BIT(hadc->State, HAL_ADC_STATE_READY); } } /* Conversion complete callback */ HAL_ADC_ConvCpltCallback(hadc); } else { /* Call DMA error callback */ hadc->DMA_Handle->XferErrorCallback(hdma); } } /** * @brief DMA half transfer complete callback. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma) { ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* Conversion complete callback */ HAL_ADC_ConvHalfCpltCallback(hadc); } /** * @brief DMA error callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma) { ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; hadc->State= HAL_ADC_STATE_ERROR_DMA; /* Set ADC error code to DMA error */ hadc->ErrorCode |= HAL_ADC_ERROR_DMA; HAL_ADC_ErrorCallback(hadc); } /** * @} */ #endif /* HAL_ADC_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
frzolp/StatusDisplay
StatusDisplay/HAL_Driver/Src/stm32f7xx_hal_adc_ex.c
C
gpl-2.0
41,635
#ifndef _INPUT_H #define _INPUT_H /* * Copyright (c) 1999-2002 Vojtech Pavlik * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published by * the Free Software Foundation. */ #ifdef __KERNEL__ #include <linux/time.h> #include <linux/list.h> #else #include <sys/time.h> #include <sys/ioctl.h> #include <sys/types.h> #include <linux/types.h> #endif /* * The event structure itself */ struct input_event { struct timeval time; __u16 type; __u16 code; __s32 value; }; /* * Protocol version. */ #define EV_VERSION 0x010001 /* * IOCTLs (0x00 - 0x7f) */ struct input_id { __u16 bustype; __u16 vendor; __u16 product; __u16 version; }; /** * struct input_absinfo - used by EVIOCGABS/EVIOCSABS ioctls * @value: latest reported value for the axis. * @minimum: specifies minimum value for the axis. * @maximum: specifies maximum value for the axis. * @fuzz: specifies fuzz value that is used to filter noise from * the event stream. * @flat: values that are within this value will be discarded by * joydev interface and reported as 0 instead. * @resolution: specifies resolution for the values reported for * the axis. * * Note that input core does not clamp reported values to the * [minimum, maximum] limits, such task is left to userspace. * * Resolution for main axes (ABS_X, ABS_Y, ABS_Z) is reported in * units per millimeter (units/mm), resolution for rotational axes * (ABS_RX, ABS_RY, ABS_RZ) is reported in units per radian. */ struct input_absinfo { __s32 value; __s32 minimum; __s32 maximum; __s32 fuzz; __s32 flat; __s32 resolution; }; /** * struct input_keymap_entry - used by EVIOCGKEYCODE/EVIOCSKEYCODE ioctls * @scancode: scancode represented in machine-endian form. * @len: length of the scancode that resides in @scancode buffer. * @index: index in the keymap, may be used instead of scancode * @flags: allows to specify how kernel should handle the request. For * example, setting INPUT_KEYMAP_BY_INDEX flag indicates that kernel * should perform lookup in keymap by @index instead of @scancode * @keycode: key code assigned to this scancode * * The structure is used to retrieve and modify keymap data. Users have * option of performing lookup either by @scancode itself or by @index * in keymap entry. EVIOCGKEYCODE will also return scancode or index * (depending on which element was used to perform lookup). */ struct input_keymap_entry { #define INPUT_KEYMAP_BY_INDEX (1 << 0) __u8 flags; __u8 len; __u16 index; __u32 keycode; __u8 scancode[32]; }; #define EVIOCGVERSION _IOR('E', 0x01, int) /* get driver version */ #define EVIOCGID _IOR('E', 0x02, struct input_id) /* get device ID */ #define EVIOCGREP _IOR('E', 0x03, unsigned int[2]) /* get repeat settings */ #define EVIOCSREP _IOW('E', 0x03, unsigned int[2]) /* set repeat settings */ #define EVIOCGKEYCODE _IOR('E', 0x04, unsigned int[2]) /* get keycode */ #define EVIOCGKEYCODE_V2 _IOR('E', 0x04, struct input_keymap_entry) #define EVIOCSKEYCODE _IOW('E', 0x04, unsigned int[2]) /* set keycode */ #define EVIOCSKEYCODE_V2 _IOW('E', 0x04, struct input_keymap_entry) #define EVIOCGNAME(len) _IOC(_IOC_READ, 'E', 0x06, len) /* get device name */ #define EVIOCGPHYS(len) _IOC(_IOC_READ, 'E', 0x07, len) /* get physical location */ #define EVIOCGUNIQ(len) _IOC(_IOC_READ, 'E', 0x08, len) /* get unique identifier */ #define EVIOCGPROP(len) _IOC(_IOC_READ, 'E', 0x09, len) /* get device properties */ /** * EVIOCGMTSLOTS(len) - get MT slot values * * The ioctl buffer argument should be binary equivalent to * * struct input_mt_request_layout { * __u32 code; * __s32 values[num_slots]; * }; * * where num_slots is the (arbitrary) number of MT slots to extract. * * The ioctl size argument (len) is the size of the buffer, which * should satisfy len = (num_slots + 1) * sizeof(__s32). If len is * too small to fit all available slots, the first num_slots are * returned. * * Before the call, code is set to the wanted ABS_MT event type. On * return, values[] is filled with the slot values for the specified * ABS_MT code. * * If the request code is not an ABS_MT value, -EINVAL is returned. */ #define EVIOCGMTSLOTS(len) _IOC(_IOC_READ, 'E', 0x0a, len) #define EVIOCGKEY(len) _IOC(_IOC_READ, 'E', 0x18, len) /* get global key state */ #define EVIOCGLED(len) _IOC(_IOC_READ, 'E', 0x19, len) /* get all LEDs */ #define EVIOCGSND(len) _IOC(_IOC_READ, 'E', 0x1a, len) /* get all sounds status */ #define EVIOCGSW(len) _IOC(_IOC_READ, 'E', 0x1b, len) /* get all switch states */ #define EVIOCGBIT(ev,len) _IOC(_IOC_READ, 'E', 0x20 + (ev), len) /* get event bits */ #define EVIOCGABS(abs) _IOR('E', 0x40 + (abs), struct input_absinfo) /* get abs value/limits */ #define EVIOCSABS(abs) _IOW('E', 0xc0 + (abs), struct input_absinfo) /* set abs value/limits */ #define EVIOCSFF _IOC(_IOC_WRITE, 'E', 0x80, sizeof(struct ff_effect)) /* send a force effect to a force feedback device */ #define EVIOCRMFF _IOW('E', 0x81, int) /* Erase a force effect */ #define EVIOCGEFFECTS _IOR('E', 0x84, int) /* Report number of effects playable at the same time */ #define EVIOCGRAB _IOW('E', 0x90, int) /* Grab/Release device */ #define EVIOCGSUSPENDBLOCK _IOR('E', 0x91, int) /* get suspend block enable */ #define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int) /* set suspend block enable */ #define EVIOCSCLOCKID _IOW('E', 0xa0, int) /* Set clockid to be used for timestamps */ /* * Device properties and quirks */ #define INPUT_PROP_POINTER 0x00 /* needs a pointer */ #define INPUT_PROP_DIRECT 0x01 /* direct input devices */ #define INPUT_PROP_BUTTONPAD 0x02 /* has button(s) under pad */ #define INPUT_PROP_SEMI_MT 0x03 /* touch rectangle only */ #define INPUT_PROP_NO_DUMMY_RELEASE 0x04 /* no dummy event */ #define INPUT_PROP_MAX 0x1f #define INPUT_PROP_CNT (INPUT_PROP_MAX + 1) /* * Event types */ #define EV_SYN 0x00 #define EV_KEY 0x01 #define EV_REL 0x02 #define EV_ABS 0x03 #define EV_MSC 0x04 #define EV_SW 0x05 #define EV_LED 0x11 #define EV_SND 0x12 #define EV_REP 0x14 #define EV_FF 0x15 #define EV_PWR 0x16 #define EV_FF_STATUS 0x17 #define EV_MAX 0x1f #define EV_CNT (EV_MAX+1) /* * Synchronization events. */ #define SYN_REPORT 0 #define SYN_CONFIG 1 #define SYN_MT_REPORT 2 #define SYN_DROPPED 3 #define SYN_TIME_SEC 4 #define SYN_TIME_NSEC 5 /* * Keys and buttons * * Most of the keys/buttons are modeled after USB HUT 1.12 * (see http://www.usb.org/developers/hidpage). * Abbreviations in the comments: * AC - Application Control * AL - Application Launch Button * SC - System Control */ #define KEY_RESERVED 0 #define KEY_ESC 1 #define KEY_1 2 #define KEY_2 3 #define KEY_3 4 #define KEY_4 5 #define KEY_5 6 #define KEY_6 7 #define KEY_7 8 #define KEY_8 9 #define KEY_9 10 #define KEY_0 11 #define KEY_MINUS 12 #define KEY_EQUAL 13 #define KEY_BACKSPACE 14 #define KEY_TAB 15 #define KEY_Q 16 #define KEY_W 17 #define KEY_E 18 #define KEY_R 19 #define KEY_T 20 #define KEY_Y 21 #define KEY_U 22 #define KEY_I 23 #define KEY_O 24 #define KEY_P 25 #define KEY_LEFTBRACE 26 #define KEY_RIGHTBRACE 27 #define KEY_ENTER 28 #define KEY_LEFTCTRL 29 #define KEY_A 30 #define KEY_S 31 #define KEY_D 32 #define KEY_F 33 #define KEY_G 34 #define KEY_H 35 #define KEY_J 36 #define KEY_K 37 #define KEY_L 38 #define KEY_SEMICOLON 39 #define KEY_APOSTROPHE 40 #define KEY_GRAVE 41 #define KEY_LEFTSHIFT 42 #define KEY_BACKSLASH 43 #define KEY_Z 44 #define KEY_X 45 #define KEY_C 46 #define KEY_V 47 #define KEY_B 48 #define KEY_N 49 #define KEY_M 50 #define KEY_COMMA 51 #define KEY_DOT 52 #define KEY_SLASH 53 #define KEY_RIGHTSHIFT 54 #define KEY_KPASTERISK 55 #define KEY_LEFTALT 56 #define KEY_SPACE 57 #define KEY_CAPSLOCK 58 #define KEY_F1 59 #define KEY_F2 60 #define KEY_F3 61 #define KEY_F4 62 #define KEY_F5 63 #define KEY_F6 64 #define KEY_F7 65 #define KEY_F8 66 #define KEY_F9 67 #define KEY_F10 68 #define KEY_NUMLOCK 69 #define KEY_SCROLLLOCK 70 #define KEY_KP7 71 #define KEY_KP8 72 #define KEY_KP9 73 #define KEY_KPMINUS 74 #define KEY_KP4 75 #define KEY_KP5 76 #define KEY_KP6 77 #define KEY_KPPLUS 78 #define KEY_KP1 79 #define KEY_KP2 80 #define KEY_KP3 81 #define KEY_KP0 82 #define KEY_KPDOT 83 #define KEY_ZENKAKUHANKAKU 85 #define KEY_102ND 86 #define KEY_F11 87 #define KEY_F12 88 #define KEY_RO 89 #define KEY_KATAKANA 90 #define KEY_HIRAGANA 91 #define KEY_HENKAN 92 #define KEY_KATAKANAHIRAGANA 93 #define KEY_MUHENKAN 94 #define KEY_KPJPCOMMA 95 #define KEY_KPENTER 96 #define KEY_RIGHTCTRL 97 #define KEY_KPSLASH 98 #define KEY_SYSRQ 99 #define KEY_RIGHTALT 100 #define KEY_LINEFEED 101 #define KEY_HOME 102 #define KEY_UP 103 #define KEY_PAGEUP 104 #define KEY_LEFT 105 #define KEY_RIGHT 106 #define KEY_END 107 #define KEY_DOWN 108 #define KEY_PAGEDOWN 109 #define KEY_INSERT 110 #define KEY_DELETE 111 #define KEY_MACRO 112 #define KEY_MUTE 113 #define KEY_VOLUMEDOWN 114 #define KEY_VOLUMEUP 115 #define KEY_POWER 116 /* SC System Power Down */ #define KEY_KPEQUAL 117 #define KEY_KPPLUSMINUS 118 #define KEY_PAUSE 119 #define KEY_SCALE 120 /* AL Compiz Scale (Expose) */ #define KEY_KPCOMMA 121 #define KEY_HANGEUL 122 #define KEY_HANGUEL KEY_HANGEUL #define KEY_HANJA 123 #define KEY_YEN 124 #define KEY_LEFTMETA 125 #define KEY_RIGHTMETA 126 #define KEY_COMPOSE 127 #define KEY_STOP 128 /* AC Stop */ #define KEY_AGAIN 129 #define KEY_PROPS 130 /* AC Properties */ #define KEY_UNDO 131 /* AC Undo */ #define KEY_FRONT 132 #define KEY_COPY 133 /* AC Copy */ #define KEY_OPEN 134 /* AC Open */ #define KEY_PASTE 135 /* AC Paste */ #define KEY_FIND 136 /* AC Search */ #define KEY_CUT 137 /* AC Cut */ #define KEY_HELP 138 /* AL Integrated Help Center */ #define KEY_MENU 139 /* Menu (show menu) */ #define KEY_CALC 140 /* AL Calculator */ #define KEY_SETUP 141 #define KEY_SLEEP 142 /* SC System Sleep */ #define KEY_WAKEUP 143 /* System Wake Up */ #define KEY_FILE 144 /* AL Local Machine Browser */ #define KEY_SENDFILE 145 #define KEY_DELETEFILE 146 #define KEY_XFER 147 #define KEY_PROG1 148 #define KEY_PROG2 149 #define KEY_WWW 150 /* AL Internet Browser */ #define KEY_MSDOS 151 #define KEY_COFFEE 152 /* AL Terminal Lock/Screensaver */ #define KEY_SCREENLOCK KEY_COFFEE #define KEY_DIRECTION 153 #define KEY_CYCLEWINDOWS 154 #define KEY_MAIL 155 #define KEY_BOOKMARKS 156 /* AC Bookmarks */ #define KEY_COMPUTER 157 #define KEY_BACK 158 /* AC Back */ #define KEY_FORWARD 159 /* AC Forward */ #define KEY_CLOSECD 160 #define KEY_EJECTCD 161 #define KEY_EJECTCLOSECD 162 #define KEY_NEXTSONG 163 #define KEY_PLAYPAUSE 164 #define KEY_PREVIOUSSONG 165 #define KEY_STOPCD 166 #define KEY_RECORD 167 #define KEY_REWIND 168 #define KEY_PHONE 169 /* Media Select Telephone */ #define KEY_ISO 170 #define KEY_CONFIG 171 /* AL Consumer Control Configuration */ #define KEY_HOMEPAGE 172 /* AC Home */ #define KEY_REFRESH 173 /* AC Refresh */ #define KEY_EXIT 174 /* AC Exit */ #define KEY_MOVE 175 #define KEY_EDIT 176 #define KEY_SCROLLUP 177 #define KEY_SCROLLDOWN 178 #define KEY_KPLEFTPAREN 179 #define KEY_KPRIGHTPAREN 180 #define KEY_NEW 181 /* AC New */ #define KEY_REDO 182 /* AC Redo/Repeat */ #define KEY_F13 183 #define KEY_F14 184 #define KEY_F15 185 #define KEY_F16 186 #define KEY_F17 187 #define KEY_F18 188 #define KEY_F19 189 #define KEY_F20 190 #define KEY_F21 191 #define KEY_F22 192 #define KEY_F23 193 #define KEY_F24 194 #define KEY_PLAYCD 200 #define KEY_PAUSECD 201 #define KEY_PROG3 202 #define KEY_PROG4 203 #define KEY_DASHBOARD 204 /* AL Dashboard */ #define KEY_SUSPEND 205 #define KEY_CLOSE 206 /* AC Close */ #define KEY_PLAY 207 #define KEY_FASTFORWARD 208 #define KEY_BASSBOOST 209 #define KEY_PRINT 210 /* AC Print */ #define KEY_HP 211 #define KEY_CAMERA 212 #define KEY_SOUND 213 #define KEY_QUESTION 214 #define KEY_EMAIL 215 #define KEY_CHAT 216 #define KEY_SEARCH 217 #define KEY_CONNECT 218 #define KEY_FINANCE 219 /* AL Checkbook/Finance */ #define KEY_SPORT 220 #define KEY_SHOP 221 #define KEY_ALTERASE 222 #define KEY_CANCEL 223 /* AC Cancel */ #define KEY_BRIGHTNESSDOWN 224 #define KEY_BRIGHTNESSUP 225 #define KEY_MEDIA 226 #define KEY_SWITCHVIDEOMODE 227 /* Cycle between available video outputs (Monitor/LCD/TV-out/etc) */ #define KEY_KBDILLUMTOGGLE 228 #define KEY_KBDILLUMDOWN 229 #define KEY_KBDILLUMUP 230 #define KEY_SEND 231 /* AC Send */ #define KEY_REPLY 232 /* AC Reply */ #define KEY_FORWARDMAIL 233 /* AC Forward Msg */ #define KEY_SAVE 234 /* AC Save */ #define KEY_DOCUMENTS 235 #define KEY_BATTERY 236 #define KEY_BLUETOOTH 237 #define KEY_WLAN 238 #define KEY_UWB 239 #define KEY_UNKNOWN 240 #define KEY_VIDEO_NEXT 241 /* drive next video source */ #define KEY_VIDEO_PREV 242 /* drive previous video source */ #define KEY_BRIGHTNESS_CYCLE 243 /* brightness up, after max is min */ #define KEY_BRIGHTNESS_AUTO 244 /* Set Auto Brightness: manual brightness control is off, rely on ambient */ #define KEY_BRIGHTNESS_ZERO KEY_BRIGHTNESS_AUTO #define KEY_DISPLAY_OFF 245 /* display device to off state */ #define KEY_WWAN 246 /* Wireless WAN (LTE, UMTS, GSM, etc.) */ #define KEY_WIMAX KEY_WWAN #define KEY_RFKILL 247 /* Key that controls all radios */ #define KEY_MICMUTE 248 /* Mute / unmute the microphone */ /* Oppo specific keycodes */ #define KEY_GESTURE_V_UP 249 #define KEY_GESTURE_CIRCLE 250 #define KEY_GESTURE_SWIPE_DOWN 251 #define KEY_GESTURE_V 252 #define KEY_GESTURE_LTR 253 #define KEY_GESTURE_GTR 254 #define KEY_DOUBLE_TAP 255 #define KEY_SWEEP_WAKE 255 /* Code 255 is reserved for special needs of AT keyboard driver */ #define BTN_MISC 0x100 #define BTN_0 0x100 #define BTN_1 0x101 #define BTN_2 0x102 #define BTN_3 0x103 #define BTN_4 0x104 #define BTN_5 0x105 #define BTN_6 0x106 #define BTN_7 0x107 #define BTN_8 0x108 #define BTN_9 0x109 #define BTN_MOUSE 0x110 #define BTN_LEFT 0x110 #define BTN_RIGHT 0x111 #define BTN_MIDDLE 0x112 #define BTN_SIDE 0x113 #define BTN_EXTRA 0x114 #define BTN_FORWARD 0x115 #define BTN_BACK 0x116 #define BTN_TASK 0x117 #define BTN_JOYSTICK 0x120 #define BTN_TRIGGER 0x120 #define BTN_THUMB 0x121 #define BTN_THUMB2 0x122 #define BTN_TOP 0x123 #define BTN_TOP2 0x124 #define BTN_PINKIE 0x125 #define BTN_BASE 0x126 #define BTN_BASE2 0x127 #define BTN_BASE3 0x128 #define BTN_BASE4 0x129 #define BTN_BASE5 0x12a #define BTN_BASE6 0x12b #define BTN_DEAD 0x12f #define BTN_GAMEPAD 0x130 #define BTN_SOUTH 0x130 #define BTN_A BTN_SOUTH #define BTN_EAST 0x131 #define BTN_B BTN_EAST #define BTN_C 0x132 #define BTN_NORTH 0x133 #define BTN_X BTN_NORTH #define BTN_WEST 0x134 #define BTN_Y BTN_WEST #define BTN_Z 0x135 #define BTN_TL 0x136 #define BTN_TR 0x137 #define BTN_TL2 0x138 #define BTN_TR2 0x139 #define BTN_SELECT 0x13a #define BTN_START 0x13b #define BTN_MODE 0x13c #define BTN_THUMBL 0x13d #define BTN_THUMBR 0x13e #define BTN_DIGI 0x140 #define BTN_TOOL_PEN 0x140 #define BTN_TOOL_RUBBER 0x141 #define BTN_TOOL_BRUSH 0x142 #define BTN_TOOL_PENCIL 0x143 #define BTN_TOOL_AIRBRUSH 0x144 #define BTN_TOOL_FINGER 0x145 #define BTN_TOOL_MOUSE 0x146 #define BTN_TOOL_LENS 0x147 #define BTN_TOOL_QUINTTAP 0x148 /* Five fingers on trackpad */ #define BTN_TOUCH 0x14a #define BTN_STYLUS 0x14b #define BTN_STYLUS2 0x14c #define BTN_TOOL_DOUBLETAP 0x14d #define BTN_TOOL_TRIPLETAP 0x14e #define BTN_TOOL_QUADTAP 0x14f /* Four fingers on trackpad */ #define BTN_WHEEL 0x150 #define BTN_GEAR_DOWN 0x150 #define BTN_GEAR_UP 0x151 #define KEY_OK 0x160 #define KEY_SELECT 0x161 #define KEY_GOTO 0x162 #define KEY_CLEAR 0x163 #define KEY_POWER2 0x164 #define KEY_OPTION 0x165 #define KEY_INFO 0x166 /* AL OEM Features/Tips/Tutorial */ #define KEY_TIME 0x167 #define KEY_VENDOR 0x168 #define KEY_ARCHIVE 0x169 #define KEY_PROGRAM 0x16a /* Media Select Program Guide */ #define KEY_CHANNEL 0x16b #define KEY_FAVORITES 0x16c #define KEY_EPG 0x16d #define KEY_PVR 0x16e /* Media Select Home */ #define KEY_MHP 0x16f #define KEY_LANGUAGE 0x170 #define KEY_TITLE 0x171 #define KEY_SUBTITLE 0x172 #define KEY_ANGLE 0x173 #define KEY_ZOOM 0x174 #define KEY_MODE 0x175 #define KEY_KEYBOARD 0x176 #define KEY_SCREEN 0x177 #define KEY_PC 0x178 /* Media Select Computer */ #define KEY_TV 0x179 /* Media Select TV */ #define KEY_TV2 0x17a /* Media Select Cable */ #define KEY_VCR 0x17b /* Media Select VCR */ #define KEY_VCR2 0x17c /* VCR Plus */ #define KEY_SAT 0x17d /* Media Select Satellite */ #define KEY_SAT2 0x17e #define KEY_CD 0x17f /* Media Select CD */ #define KEY_TAPE 0x180 /* Media Select Tape */ #define KEY_RADIO 0x181 #define KEY_TUNER 0x182 /* Media Select Tuner */ #define KEY_PLAYER 0x183 #define KEY_TEXT 0x184 #define KEY_DVD 0x185 /* Media Select DVD */ #define KEY_AUX 0x186 #define KEY_MP3 0x187 #define KEY_AUDIO 0x188 /* AL Audio Browser */ #define KEY_VIDEO 0x189 /* AL Movie Browser */ #define KEY_DIRECTORY 0x18a #define KEY_LIST 0x18b #define KEY_MEMO 0x18c /* Media Select Messages */ #define KEY_CALENDAR 0x18d #define KEY_RED 0x18e #define KEY_GREEN 0x18f #define KEY_YELLOW 0x190 #define KEY_BLUE 0x191 #define KEY_CHANNELUP 0x192 /* Channel Increment */ #define KEY_CHANNELDOWN 0x193 /* Channel Decrement */ #define KEY_FIRST 0x194 #define KEY_LAST 0x195 /* Recall Last */ #define KEY_AB 0x196 #define KEY_NEXT 0x197 #define KEY_RESTART 0x198 #define KEY_SLOW 0x199 #define KEY_SHUFFLE 0x19a #define KEY_BREAK 0x19b #define KEY_PREVIOUS 0x19c #define KEY_DIGITS 0x19d #define KEY_TEEN 0x19e #define KEY_TWEN 0x19f #define KEY_VIDEOPHONE 0x1a0 /* Media Select Video Phone */ #define KEY_GAMES 0x1a1 /* Media Select Games */ #define KEY_ZOOMIN 0x1a2 /* AC Zoom In */ #define KEY_ZOOMOUT 0x1a3 /* AC Zoom Out */ #define KEY_ZOOMRESET 0x1a4 /* AC Zoom */ #define KEY_WORDPROCESSOR 0x1a5 /* AL Word Processor */ #define KEY_EDITOR 0x1a6 /* AL Text Editor */ #define KEY_SPREADSHEET 0x1a7 /* AL Spreadsheet */ #define KEY_GRAPHICSEDITOR 0x1a8 /* AL Graphics Editor */ #define KEY_PRESENTATION 0x1a9 /* AL Presentation App */ #define KEY_DATABASE 0x1aa /* AL Database App */ #define KEY_NEWS 0x1ab /* AL Newsreader */ #define KEY_VOICEMAIL 0x1ac /* AL Voicemail */ #define KEY_ADDRESSBOOK 0x1ad /* AL Contacts/Address Book */ #define KEY_MESSENGER 0x1ae /* AL Instant Messaging */ #define KEY_DISPLAYTOGGLE 0x1af /* Turn display (LCD) on and off */ #define KEY_BRIGHTNESS_TOGGLE KEY_DISPLAYTOGGLE #define KEY_SPELLCHECK 0x1b0 /* AL Spell Check */ #define KEY_LOGOFF 0x1b1 /* AL Logoff */ #define KEY_DOLLAR 0x1b2 #define KEY_EURO 0x1b3 #define KEY_FRAMEBACK 0x1b4 /* Consumer - transport controls */ #define KEY_FRAMEFORWARD 0x1b5 #define KEY_CONTEXT_MENU 0x1b6 /* GenDesc - system context menu */ #define KEY_MEDIA_REPEAT 0x1b7 /* Consumer - transport control */ #define KEY_10CHANNELSUP 0x1b8 /* 10 channels up (10+) */ #define KEY_10CHANNELSDOWN 0x1b9 /* 10 channels down (10-) */ #define KEY_IMAGES 0x1ba /* AL Image Browser */ #define KEY_DEL_EOL 0x1c0 #define KEY_DEL_EOS 0x1c1 #define KEY_INS_LINE 0x1c2 #define KEY_DEL_LINE 0x1c3 #define KEY_FN 0x1d0 #define KEY_FN_ESC 0x1d1 #define KEY_FN_F1 0x1d2 #define KEY_FN_F2 0x1d3 #define KEY_FN_F3 0x1d4 #define KEY_FN_F4 0x1d5 #define KEY_FN_F5 0x1d6 #define KEY_FN_F6 0x1d7 #define KEY_FN_F7 0x1d8 #define KEY_FN_F8 0x1d9 #define KEY_FN_F9 0x1da #define KEY_FN_F10 0x1db #define KEY_FN_F11 0x1dc #define KEY_FN_F12 0x1dd #define KEY_FN_1 0x1de #define KEY_FN_2 0x1df #define KEY_FN_D 0x1e0 #define KEY_FN_E 0x1e1 #define KEY_FN_F 0x1e2 #define KEY_FN_S 0x1e3 #define KEY_FN_B 0x1e4 #define KEY_BRL_DOT1 0x1f1 #define KEY_BRL_DOT2 0x1f2 #define KEY_BRL_DOT3 0x1f3 #define KEY_BRL_DOT4 0x1f4 #define KEY_BRL_DOT5 0x1f5 #define KEY_BRL_DOT6 0x1f6 #define KEY_BRL_DOT7 0x1f7 #define KEY_BRL_DOT8 0x1f8 #define KEY_BRL_DOT9 0x1f9 #define KEY_BRL_DOT10 0x1fa #define KEY_NUMERIC_0 0x200 /* used by phones, remote controls, */ #define KEY_NUMERIC_1 0x201 /* and other keypads */ #define KEY_NUMERIC_2 0x202 #define KEY_NUMERIC_3 0x203 #define KEY_NUMERIC_4 0x204 #define KEY_NUMERIC_5 0x205 #define KEY_NUMERIC_6 0x206 #define KEY_NUMERIC_7 0x207 #define KEY_NUMERIC_8 0x208 #define KEY_NUMERIC_9 0x209 #define KEY_NUMERIC_STAR 0x20a #define KEY_NUMERIC_POUND 0x20b #define KEY_CAMERA_SNAPSHOT 0x2fe #define KEY_CAMERA_FOCUS 0x210 #define KEY_WPS_BUTTON 0x211 /* WiFi Protected Setup key */ #define KEY_TOUCHPAD_TOGGLE 0x212 /* Request switch touchpad on or off */ #define KEY_TOUCHPAD_ON 0x213 #define KEY_TOUCHPAD_OFF 0x214 #define KEY_CAMERA_ZOOMIN 0x215 #define KEY_CAMERA_ZOOMOUT 0x216 #define KEY_CAMERA_UP 0x217 #define KEY_CAMERA_DOWN 0x218 #define KEY_CAMERA_LEFT 0x219 #define KEY_CAMERA_RIGHT 0x21a #define BTN_DPAD_UP 0x220 #define BTN_DPAD_DOWN 0x221 #define BTN_DPAD_LEFT 0x222 #define BTN_DPAD_RIGHT 0x223 #define KEY_ALS_TOGGLE 0x230 /* Ambient light sensor */ #define KEY_BUTTONCONFIG 0x240 /* AL Button Configuration */ #define KEY_TASKMANAGER 0x241 /* AL Task/Project Manager */ #define KEY_JOURNAL 0x242 /* AL Log/Journal/Timecard */ #define KEY_CONTROLPANEL 0x243 /* AL Control Panel */ #define KEY_APPSELECT 0x244 /* AL Select Task/Application */ #define KEY_SCREENSAVER 0x245 /* AL Screen Saver */ #define KEY_VOICECOMMAND 0x246 /* Listening Voice Command */ #define KEY_BRIGHTNESS_MIN 0x250 /* Set Brightness to Minimum */ #define KEY_BRIGHTNESS_MAX 0x251 /* Set Brightness to Maximum */ #define BTN_TRIGGER_HAPPY 0x2c0 #define BTN_TRIGGER_HAPPY1 0x2c0 #define BTN_TRIGGER_HAPPY2 0x2c1 #define BTN_TRIGGER_HAPPY3 0x2c2 #define BTN_TRIGGER_HAPPY4 0x2c3 #define BTN_TRIGGER_HAPPY5 0x2c4 #define BTN_TRIGGER_HAPPY6 0x2c5 #define BTN_TRIGGER_HAPPY7 0x2c6 #define BTN_TRIGGER_HAPPY8 0x2c7 #define BTN_TRIGGER_HAPPY9 0x2c8 #define BTN_TRIGGER_HAPPY10 0x2c9 #define BTN_TRIGGER_HAPPY11 0x2ca #define BTN_TRIGGER_HAPPY12 0x2cb #define BTN_TRIGGER_HAPPY13 0x2cc #define BTN_TRIGGER_HAPPY14 0x2cd #define BTN_TRIGGER_HAPPY15 0x2ce #define BTN_TRIGGER_HAPPY16 0x2cf #define BTN_TRIGGER_HAPPY17 0x2d0 #define BTN_TRIGGER_HAPPY18 0x2d1 #define BTN_TRIGGER_HAPPY19 0x2d2 #define BTN_TRIGGER_HAPPY20 0x2d3 #define BTN_TRIGGER_HAPPY21 0x2d4 #define BTN_TRIGGER_HAPPY22 0x2d5 #define BTN_TRIGGER_HAPPY23 0x2d6 #define BTN_TRIGGER_HAPPY24 0x2d7 #define BTN_TRIGGER_HAPPY25 0x2d8 #define BTN_TRIGGER_HAPPY26 0x2d9 #define BTN_TRIGGER_HAPPY27 0x2da #define BTN_TRIGGER_HAPPY28 0x2db #define BTN_TRIGGER_HAPPY29 0x2dc #define BTN_TRIGGER_HAPPY30 0x2dd #define BTN_TRIGGER_HAPPY31 0x2de #define BTN_TRIGGER_HAPPY32 0x2df #define BTN_TRIGGER_HAPPY33 0x2e0 #define BTN_TRIGGER_HAPPY34 0x2e1 #define BTN_TRIGGER_HAPPY35 0x2e2 #define BTN_TRIGGER_HAPPY36 0x2e3 #define BTN_TRIGGER_HAPPY37 0x2e4 #define BTN_TRIGGER_HAPPY38 0x2e5 #define BTN_TRIGGER_HAPPY39 0x2e6 #define BTN_TRIGGER_HAPPY40 0x2e7 /* We avoid low common keys in module aliases so they don't get huge. */ #define KEY_MIN_INTERESTING KEY_MUTE #define KEY_MAX 0x2ff #define KEY_CNT (KEY_MAX+1) /* * Relative axes */ #define REL_X 0x00 #define REL_Y 0x01 #define REL_Z 0x02 #define REL_RX 0x03 #define REL_RY 0x04 #define REL_RZ 0x05 #define REL_HWHEEL 0x06 #define REL_DIAL 0x07 #define REL_WHEEL 0x08 #define REL_MISC 0x09 #define REL_MAX 0x0f #define REL_CNT (REL_MAX+1) /* * Absolute axes */ #define ABS_X 0x00 #define ABS_Y 0x01 #define ABS_Z 0x02 #define ABS_RX 0x03 #define ABS_RY 0x04 #define ABS_RZ 0x05 #define ABS_THROTTLE 0x06 #define ABS_RUDDER 0x07 #define ABS_WHEEL 0x08 #define ABS_GAS 0x09 #define ABS_BRAKE 0x0a #define ABS_HAT0X 0x10 #define ABS_HAT0Y 0x11 #define ABS_HAT1X 0x12 #define ABS_HAT1Y 0x13 #define ABS_HAT2X 0x14 #define ABS_HAT2Y 0x15 #define ABS_HAT3X 0x16 #define ABS_HAT3Y 0x17 #define ABS_PRESSURE 0x18 #define ABS_DISTANCE 0x19 #define ABS_TILT_X 0x1a #define ABS_TILT_Y 0x1b #define ABS_TOOL_WIDTH 0x1c #define ABS_VOLUME 0x20 #define ABS_MISC 0x28 #define ABS_MT_SLOT 0x2f /* MT slot being modified */ #define ABS_MT_TOUCH_MAJOR 0x30 /* Major axis of touching ellipse */ #define ABS_MT_TOUCH_MINOR 0x31 /* Minor axis (omit if circular) */ #define ABS_MT_WIDTH_MAJOR 0x32 /* Major axis of approaching ellipse */ #define ABS_MT_WIDTH_MINOR 0x33 /* Minor axis (omit if circular) */ #define ABS_MT_ORIENTATION 0x34 /* Ellipse orientation */ #define ABS_MT_POSITION_X 0x35 /* Center X ellipse position */ #define ABS_MT_POSITION_Y 0x36 /* Center Y ellipse position */ #define ABS_MT_TOOL_TYPE 0x37 /* Type of touching device */ #define ABS_MT_BLOB_ID 0x38 /* Group a set of packets as a blob */ #define ABS_MT_TRACKING_ID 0x39 /* Unique ID of initiated contact */ #define ABS_MT_PRESSURE 0x3a /* Pressure on contact area */ #define ABS_MT_DISTANCE 0x3b /* Contact hover distance */ #ifdef __KERNEL__ /* Implementation details, userspace should not care about these */ #define ABS_MT_FIRST ABS_MT_TOUCH_MAJOR #define ABS_MT_LAST ABS_MT_DISTANCE #endif #define ABS_MAX 0x3f #define ABS_CNT (ABS_MAX+1) /* * Switch events */ #define SW_LID 0x00 /* set = lid shut */ #define SW_TABLET_MODE 0x01 /* set = tablet mode */ #define SW_HEADPHONE_INSERT 0x02 /* set = inserted */ #define SW_RFKILL_ALL 0x03 /* rfkill master switch, type "any" set = radio enabled */ #define SW_RADIO SW_RFKILL_ALL /* deprecated */ #define SW_MICROPHONE_INSERT 0x04 /* set = inserted */ #define SW_DOCK 0x05 /* set = plugged into dock */ #define SW_LINEOUT_INSERT 0x06 /* set = inserted */ #define SW_JACK_PHYSICAL_INSERT 0x07 /* set = mechanical switch set */ #define SW_VIDEOOUT_INSERT 0x08 /* set = inserted */ #define SW_CAMERA_LENS_COVER 0x09 /* set = lens covered */ #define SW_KEYPAD_SLIDE 0x0a /* set = keypad slide out */ #define SW_FRONT_PROXIMITY 0x0b /* set = front proximity sensor active */ #define SW_ROTATE_LOCK 0x0c /* set = rotate locked/disabled */ #define SW_LINEIN_INSERT 0x0d /* set = inserted */ #define SW_HPHL_OVERCURRENT 0x0e /* set = over current on left hph */ #define SW_HPHR_OVERCURRENT 0x0f /* set = over current on right hph */ #define SW_UNSUPPORT_INSERT 0x10 /* set = unsupported device inserted */ #define SW_MICROPHONE2_INSERT 0x11 /* set = inserted */ #define SW_MUTE_DEVICE 0x12 /* set = device disabled */ #define SW_MAX 0x20 #define SW_CNT (SW_MAX+1) /* * Misc events */ #define MSC_SERIAL 0x00 #define MSC_PULSELED 0x01 #define MSC_GESTURE 0x02 #define MSC_RAW 0x03 #define MSC_SCAN 0x04 #define MSC_MAX 0x07 #define MSC_CNT (MSC_MAX+1) /* * LEDs */ #define LED_NUML 0x00 #define LED_CAPSL 0x01 #define LED_SCROLLL 0x02 #define LED_COMPOSE 0x03 #define LED_KANA 0x04 #define LED_SLEEP 0x05 #define LED_SUSPEND 0x06 #define LED_MUTE 0x07 #define LED_MISC 0x08 #define LED_MAIL 0x09 #define LED_CHARGING 0x0a #define LED_MAX 0x0f #define LED_CNT (LED_MAX+1) /* * Autorepeat values */ #define REP_DELAY 0x00 #define REP_PERIOD 0x01 #define REP_MAX 0x01 #define REP_CNT (REP_MAX+1) /* * Sounds */ #define SND_CLICK 0x00 #define SND_BELL 0x01 #define SND_TONE 0x02 #define SND_MAX 0x07 #define SND_CNT (SND_MAX+1) /* * IDs. */ #define ID_BUS 0 #define ID_VENDOR 1 #define ID_PRODUCT 2 #define ID_VERSION 3 #define BUS_PCI 0x01 #define BUS_ISAPNP 0x02 #define BUS_USB 0x03 #define BUS_HIL 0x04 #define BUS_BLUETOOTH 0x05 #define BUS_VIRTUAL 0x06 #define BUS_ISA 0x10 #define BUS_I8042 0x11 #define BUS_XTKBD 0x12 #define BUS_RS232 0x13 #define BUS_GAMEPORT 0x14 #define BUS_PARPORT 0x15 #define BUS_AMIGA 0x16 #define BUS_ADB 0x17 #define BUS_I2C 0x18 #define BUS_HOST 0x19 #define BUS_GSC 0x1A #define BUS_ATARI 0x1B #define BUS_SPI 0x1C /* * MT_TOOL types */ #define MT_TOOL_FINGER 0 #define MT_TOOL_PEN 1 #define MT_TOOL_MAX 1 /* * Values describing the status of a force-feedback effect */ #define FF_STATUS_STOPPED 0x00 #define FF_STATUS_PLAYING 0x01 #define FF_STATUS_MAX 0x01 /* * Structures used in ioctls to upload effects to a device * They are pieces of a bigger structure (called ff_effect) */ /* * All duration values are expressed in ms. Values above 32767 ms (0x7fff) * should not be used and have unspecified results. */ /** * struct ff_replay - defines scheduling of the force-feedback effect * @length: duration of the effect * @delay: delay before effect should start playing */ struct ff_replay { __u16 length; __u16 delay; }; /** * struct ff_trigger - defines what triggers the force-feedback effect * @button: number of the button triggering the effect * @interval: controls how soon the effect can be re-triggered */ struct ff_trigger { __u16 button; __u16 interval; }; /** * struct ff_envelope - generic force-feedback effect envelope * @attack_length: duration of the attack (ms) * @attack_level: level at the beginning of the attack * @fade_length: duration of fade (ms) * @fade_level: level at the end of fade * * The @attack_level and @fade_level are absolute values; when applying * envelope force-feedback core will convert to positive/negative * value based on polarity of the default level of the effect. * Valid range for the attack and fade levels is 0x0000 - 0x7fff */ struct ff_envelope { __u16 attack_length; __u16 attack_level; __u16 fade_length; __u16 fade_level; }; /** * struct ff_constant_effect - defines parameters of a constant force-feedback effect * @level: strength of the effect; may be negative * @envelope: envelope data */ struct ff_constant_effect { __s16 level; struct ff_envelope envelope; }; /** * struct ff_ramp_effect - defines parameters of a ramp force-feedback effect * @start_level: beginning strength of the effect; may be negative * @end_level: final strength of the effect; may be negative * @envelope: envelope data */ struct ff_ramp_effect { __s16 start_level; __s16 end_level; struct ff_envelope envelope; }; /** * struct ff_condition_effect - defines a spring or friction force-feedback effect * @right_saturation: maximum level when joystick moved all way to the right * @left_saturation: same for the left side * @right_coeff: controls how fast the force grows when the joystick moves * to the right * @left_coeff: same for the left side * @deadband: size of the dead zone, where no force is produced * @center: position of the dead zone */ struct ff_condition_effect { __u16 right_saturation; __u16 left_saturation; __s16 right_coeff; __s16 left_coeff; __u16 deadband; __s16 center; }; /** * struct ff_periodic_effect - defines parameters of a periodic force-feedback effect * @waveform: kind of the effect (wave) * @period: period of the wave (ms) * @magnitude: peak value * @offset: mean value of the wave (roughly) * @phase: 'horizontal' shift * @envelope: envelope data * @custom_len: number of samples (FF_CUSTOM only) * @custom_data: buffer of samples (FF_CUSTOM only) * * Known waveforms - FF_SQUARE, FF_TRIANGLE, FF_SINE, FF_SAW_UP, * FF_SAW_DOWN, FF_CUSTOM. The exact syntax FF_CUSTOM is undefined * for the time being as no driver supports it yet. * * Note: the data pointed by custom_data is copied by the driver. * You can therefore dispose of the memory after the upload/update. */ struct ff_periodic_effect { __u16 waveform; __u16 period; __s16 magnitude; __s16 offset; __u16 phase; struct ff_envelope envelope; __u32 custom_len; __s16 __user *custom_data; }; /** * struct ff_rumble_effect - defines parameters of a periodic force-feedback effect * @strong_magnitude: magnitude of the heavy motor * @weak_magnitude: magnitude of the light one * * Some rumble pads have two motors of different weight. Strong_magnitude * represents the magnitude of the vibration generated by the heavy one. */ struct ff_rumble_effect { __u16 strong_magnitude; __u16 weak_magnitude; }; /** * struct ff_effect - defines force feedback effect * @type: type of the effect (FF_CONSTANT, FF_PERIODIC, FF_RAMP, FF_SPRING, * FF_FRICTION, FF_DAMPER, FF_RUMBLE, FF_INERTIA, or FF_CUSTOM) * @id: an unique id assigned to an effect * @direction: direction of the effect * @trigger: trigger conditions (struct ff_trigger) * @replay: scheduling of the effect (struct ff_replay) * @u: effect-specific structure (one of ff_constant_effect, ff_ramp_effect, * ff_periodic_effect, ff_condition_effect, ff_rumble_effect) further * defining effect parameters * * This structure is sent through ioctl from the application to the driver. * To create a new effect application should set its @id to -1; the kernel * will return assigned @id which can later be used to update or delete * this effect. * * Direction of the effect is encoded as follows: * 0 deg -> 0x0000 (down) * 90 deg -> 0x4000 (left) * 180 deg -> 0x8000 (up) * 270 deg -> 0xC000 (right) */ struct ff_effect { __u16 type; __s16 id; __u16 direction; struct ff_trigger trigger; struct ff_replay replay; union { struct ff_constant_effect constant; struct ff_ramp_effect ramp; struct ff_periodic_effect periodic; struct ff_condition_effect condition[2]; /* One for each axis */ struct ff_rumble_effect rumble; } u; }; /* * Force feedback effect types */ #define FF_RUMBLE 0x50 #define FF_PERIODIC 0x51 #define FF_CONSTANT 0x52 #define FF_SPRING 0x53 #define FF_FRICTION 0x54 #define FF_DAMPER 0x55 #define FF_INERTIA 0x56 #define FF_RAMP 0x57 #define FF_EFFECT_MIN FF_RUMBLE #define FF_EFFECT_MAX FF_RAMP /* * Force feedback periodic effect types */ #define FF_SQUARE 0x58 #define FF_TRIANGLE 0x59 #define FF_SINE 0x5a #define FF_SAW_UP 0x5b #define FF_SAW_DOWN 0x5c #define FF_CUSTOM 0x5d #define FF_WAVEFORM_MIN FF_SQUARE #define FF_WAVEFORM_MAX FF_CUSTOM /* * Set ff device properties */ #define FF_GAIN 0x60 #define FF_AUTOCENTER 0x61 #define FF_MAX 0x7f #define FF_CNT (FF_MAX+1) #ifdef __KERNEL__ /* * In-kernel definitions. */ #include <linux/device.h> #include <linux/fs.h> #include <linux/timer.h> #include <linux/mod_devicetable.h> /** * struct input_dev - represents an input device * @name: name of the device * @phys: physical path to the device in the system hierarchy * @uniq: unique identification code for the device (if device has it) * @id: id of the device (struct input_id) * @propbit: bitmap of device properties and quirks * @evbit: bitmap of types of events supported by the device (EV_KEY, * EV_REL, etc.) * @keybit: bitmap of keys/buttons this device has * @relbit: bitmap of relative axes for the device * @absbit: bitmap of absolute axes for the device * @mscbit: bitmap of miscellaneous events supported by the device * @ledbit: bitmap of leds present on the device * @sndbit: bitmap of sound effects supported by the device * @ffbit: bitmap of force feedback effects supported by the device * @swbit: bitmap of switches present on the device * @hint_events_per_packet: average number of events generated by the * device in a packet (between EV_SYN/SYN_REPORT events). Used by * event handlers to estimate size of the buffer needed to hold * events. * @keycodemax: size of keycode table * @keycodesize: size of elements in keycode table * @keycode: map of scancodes to keycodes for this device * @getkeycode: optional legacy method to retrieve current keymap. * @setkeycode: optional method to alter current keymap, used to implement * sparse keymaps. If not supplied default mechanism will be used. * The method is being called while holding event_lock and thus must * not sleep * @ff: force feedback structure associated with the device if device * supports force feedback effects * @repeat_key: stores key code of the last key pressed; used to implement * software autorepeat * @timer: timer for software autorepeat * @rep: current values for autorepeat parameters (delay, rate) * @mt: pointer to array of struct input_mt_slot holding current values * of tracked contacts * @mtsize: number of MT slots the device uses * @slot: MT slot currently being transmitted * @trkid: stores MT tracking ID for the current contact * @absinfo: array of &struct input_absinfo elements holding information * about absolute axes (current value, min, max, flat, fuzz, * resolution) * @key: reflects current state of device's keys/buttons * @led: reflects current state of device's LEDs * @snd: reflects current state of sound effects * @sw: reflects current state of device's switches * @open: this method is called when the very first user calls * input_open_device(). The driver must prepare the device * to start generating events (start polling thread, * request an IRQ, submit URB, etc.) * @close: this method is called when the very last user calls * input_close_device(). * @flush: purges the device. Most commonly used to get rid of force * feedback effects loaded into the device when disconnecting * from it * @event: event handler for events sent _to_ the device, like EV_LED * or EV_SND. The device is expected to carry out the requested * action (turn on a LED, play sound, etc.) The call is protected * by @event_lock and must not sleep * @grab: input handle that currently has the device grabbed (via * EVIOCGRAB ioctl). When a handle grabs a device it becomes sole * recipient for all input events coming from the device * @event_lock: this spinlock is is taken when input core receives * and processes a new event for the device (in input_event()). * Code that accesses and/or modifies parameters of a device * (such as keymap or absmin, absmax, absfuzz, etc.) after device * has been registered with input core must take this lock. * @mutex: serializes calls to open(), close() and flush() methods * @users: stores number of users (input handlers) that opened this * device. It is used by input_open_device() and input_close_device() * to make sure that dev->open() is only called when the first * user opens device and dev->close() is called when the very * last user closes the device * @going_away: marks devices that are in a middle of unregistering and * causes input_open_device*() fail with -ENODEV. * @sync: set to %true when there were no new events since last EV_SYN * @dev: driver model's view of this device * @h_list: list of input handles associated with the device. When * accessing the list dev->mutex must be held * @node: used to place the device onto input_dev_list */ struct input_dev { const char *name; const char *phys; const char *uniq; struct input_id id; unsigned long propbit[BITS_TO_LONGS(INPUT_PROP_CNT)]; unsigned long evbit[BITS_TO_LONGS(EV_CNT)]; unsigned long keybit[BITS_TO_LONGS(KEY_CNT)]; unsigned long relbit[BITS_TO_LONGS(REL_CNT)]; unsigned long absbit[BITS_TO_LONGS(ABS_CNT)]; unsigned long mscbit[BITS_TO_LONGS(MSC_CNT)]; unsigned long ledbit[BITS_TO_LONGS(LED_CNT)]; unsigned long sndbit[BITS_TO_LONGS(SND_CNT)]; unsigned long ffbit[BITS_TO_LONGS(FF_CNT)]; unsigned long swbit[BITS_TO_LONGS(SW_CNT)]; unsigned int hint_events_per_packet; unsigned int keycodemax; unsigned int keycodesize; void *keycode; int (*setkeycode)(struct input_dev *dev, const struct input_keymap_entry *ke, unsigned int *old_keycode); int (*getkeycode)(struct input_dev *dev, struct input_keymap_entry *ke); struct ff_device *ff; unsigned int repeat_key; struct timer_list timer; int rep[REP_CNT]; struct input_mt_slot *mt; int mtsize; int slot; int trkid; struct input_absinfo *absinfo; unsigned long key[BITS_TO_LONGS(KEY_CNT)]; unsigned long led[BITS_TO_LONGS(LED_CNT)]; unsigned long snd[BITS_TO_LONGS(SND_CNT)]; unsigned long sw[BITS_TO_LONGS(SW_CNT)]; int (*open)(struct input_dev *dev); void (*close)(struct input_dev *dev); int (*flush)(struct input_dev *dev, struct file *file); int (*event)(struct input_dev *dev, unsigned int type, unsigned int code, int value); struct input_handle __rcu *grab; spinlock_t event_lock; struct mutex mutex; unsigned int users; bool going_away; bool sync; struct device dev; struct list_head h_list; struct list_head node; }; #define to_input_dev(d) container_of(d, struct input_dev, dev) /* * Verify that we are in sync with input_device_id mod_devicetable.h #defines */ #if EV_MAX != INPUT_DEVICE_ID_EV_MAX #error "EV_MAX and INPUT_DEVICE_ID_EV_MAX do not match" #endif #if KEY_MIN_INTERESTING != INPUT_DEVICE_ID_KEY_MIN_INTERESTING #error "KEY_MIN_INTERESTING and INPUT_DEVICE_ID_KEY_MIN_INTERESTING do not match" #endif #if KEY_MAX != INPUT_DEVICE_ID_KEY_MAX #error "KEY_MAX and INPUT_DEVICE_ID_KEY_MAX do not match" #endif #if REL_MAX != INPUT_DEVICE_ID_REL_MAX #error "REL_MAX and INPUT_DEVICE_ID_REL_MAX do not match" #endif #if ABS_MAX != INPUT_DEVICE_ID_ABS_MAX #error "ABS_MAX and INPUT_DEVICE_ID_ABS_MAX do not match" #endif #if MSC_MAX != INPUT_DEVICE_ID_MSC_MAX #error "MSC_MAX and INPUT_DEVICE_ID_MSC_MAX do not match" #endif #if LED_MAX != INPUT_DEVICE_ID_LED_MAX #error "LED_MAX and INPUT_DEVICE_ID_LED_MAX do not match" #endif #if SND_MAX != INPUT_DEVICE_ID_SND_MAX #error "SND_MAX and INPUT_DEVICE_ID_SND_MAX do not match" #endif #if FF_MAX != INPUT_DEVICE_ID_FF_MAX #error "FF_MAX and INPUT_DEVICE_ID_FF_MAX do not match" #endif #if SW_MAX != INPUT_DEVICE_ID_SW_MAX #error "SW_MAX and INPUT_DEVICE_ID_SW_MAX do not match" #endif #define INPUT_DEVICE_ID_MATCH_DEVICE \ (INPUT_DEVICE_ID_MATCH_BUS | INPUT_DEVICE_ID_MATCH_VENDOR | INPUT_DEVICE_ID_MATCH_PRODUCT) #define INPUT_DEVICE_ID_MATCH_DEVICE_AND_VERSION \ (INPUT_DEVICE_ID_MATCH_DEVICE | INPUT_DEVICE_ID_MATCH_VERSION) struct input_handle; /** * struct input_handler - implements one of interfaces for input devices * @private: driver-specific data * @event: event handler. This method is being called by input core with * interrupts disabled and dev->event_lock spinlock held and so * it may not sleep * @filter: similar to @event; separates normal event handlers from * "filters". * @match: called after comparing device's id with handler's id_table * to perform fine-grained matching between device and handler * @connect: called when attaching a handler to an input device * @disconnect: disconnects a handler from input device * @start: starts handler for given handle. This function is called by * input core right after connect() method and also when a process * that "grabbed" a device releases it * @fops: file operations this driver implements * @minor: beginning of range of 32 minors for devices this driver * can provide * @name: name of the handler, to be shown in /proc/bus/input/handlers * @id_table: pointer to a table of input_device_ids this driver can * handle * @h_list: list of input handles associated with the handler * @node: for placing the driver onto input_handler_list * * Input handlers attach to input devices and create input handles. There * are likely several handlers attached to any given input device at the * same time. All of them will get their copy of input event generated by * the device. * * The very same structure is used to implement input filters. Input core * allows filters to run first and will not pass event to regular handlers * if any of the filters indicate that the event should be filtered (by * returning %true from their filter() method). * * Note that input core serializes calls to connect() and disconnect() * methods. */ struct input_handler { void *private; void (*event)(struct input_handle *handle, unsigned int type, unsigned int code, int value); bool (*filter)(struct input_handle *handle, unsigned int type, unsigned int code, int value); bool (*match)(struct input_handler *handler, struct input_dev *dev); int (*connect)(struct input_handler *handler, struct input_dev *dev, const struct input_device_id *id); void (*disconnect)(struct input_handle *handle); void (*start)(struct input_handle *handle); const struct file_operations *fops; int minor; const char *name; const struct input_device_id *id_table; struct list_head h_list; struct list_head node; }; /** * struct input_handle - links input device with an input handler * @private: handler-specific data * @open: counter showing whether the handle is 'open', i.e. should deliver * events from its device * @name: name given to the handle by handler that created it * @dev: input device the handle is attached to * @handler: handler that works with the device through this handle * @d_node: used to put the handle on device's list of attached handles * @h_node: used to put the handle on handler's list of handles from which * it gets events */ struct input_handle { void *private; int open; const char *name; struct input_dev *dev; struct input_handler *handler; struct list_head d_node; struct list_head h_node; }; struct input_dev *input_allocate_device(void); void input_free_device(struct input_dev *dev); static inline struct input_dev *input_get_device(struct input_dev *dev) { return dev ? to_input_dev(get_device(&dev->dev)) : NULL; } static inline void input_put_device(struct input_dev *dev) { if (dev) put_device(&dev->dev); } static inline void *input_get_drvdata(struct input_dev *dev) { return dev_get_drvdata(&dev->dev); } static inline void input_set_drvdata(struct input_dev *dev, void *data) { dev_set_drvdata(&dev->dev, data); } int __must_check input_register_device(struct input_dev *); void input_unregister_device(struct input_dev *); void input_reset_device(struct input_dev *); int __must_check input_register_handler(struct input_handler *); void input_unregister_handler(struct input_handler *); int input_handler_for_each_handle(struct input_handler *, void *data, int (*fn)(struct input_handle *, void *)); int input_register_handle(struct input_handle *); void input_unregister_handle(struct input_handle *); int input_grab_device(struct input_handle *); void input_release_device(struct input_handle *); int input_open_device(struct input_handle *); void input_close_device(struct input_handle *); int input_flush_device(struct input_handle *handle, struct file *file); void input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value); void input_inject_event(struct input_handle *handle, unsigned int type, unsigned int code, int value); static inline void input_report_key(struct input_dev *dev, unsigned int code, int value) { input_event(dev, EV_KEY, code, !!value); } static inline void input_report_rel(struct input_dev *dev, unsigned int code, int value) { input_event(dev, EV_REL, code, value); } static inline void input_report_abs(struct input_dev *dev, unsigned int code, int value) { input_event(dev, EV_ABS, code, value); } static inline void input_report_ff_status(struct input_dev *dev, unsigned int code, int value) { input_event(dev, EV_FF_STATUS, code, value); } static inline void input_report_switch(struct input_dev *dev, unsigned int code, int value) { input_event(dev, EV_SW, code, !!value); } static inline void input_sync(struct input_dev *dev) { input_event(dev, EV_SYN, SYN_REPORT, 0); } static inline void input_mt_sync(struct input_dev *dev) { input_event(dev, EV_SYN, SYN_MT_REPORT, 0); } void input_set_capability(struct input_dev *dev, unsigned int type, unsigned int code); /** * input_set_events_per_packet - tell handlers about the driver event rate * @dev: the input device used by the driver * @n_events: the average number of events between calls to input_sync() * * If the event rate sent from a device is unusually large, use this * function to set the expected event rate. This will allow handlers * to set up an appropriate buffer size for the event stream, in order * to minimize information loss. */ static inline void input_set_events_per_packet(struct input_dev *dev, int n_events) { dev->hint_events_per_packet = n_events; } void input_alloc_absinfo(struct input_dev *dev); void input_set_abs_params(struct input_dev *dev, unsigned int axis, int min, int max, int fuzz, int flat); #define INPUT_GENERATE_ABS_ACCESSORS(_suffix, _item) \ static inline int input_abs_get_##_suffix(struct input_dev *dev, \ unsigned int axis) \ { \ return dev->absinfo ? dev->absinfo[axis]._item : 0; \ } \ \ static inline void input_abs_set_##_suffix(struct input_dev *dev, \ unsigned int axis, int val) \ { \ input_alloc_absinfo(dev); \ if (dev->absinfo) \ dev->absinfo[axis]._item = val; \ } INPUT_GENERATE_ABS_ACCESSORS(val, value) INPUT_GENERATE_ABS_ACCESSORS(min, minimum) INPUT_GENERATE_ABS_ACCESSORS(max, maximum) INPUT_GENERATE_ABS_ACCESSORS(fuzz, fuzz) INPUT_GENERATE_ABS_ACCESSORS(flat, flat) INPUT_GENERATE_ABS_ACCESSORS(res, resolution) int input_scancode_to_scalar(const struct input_keymap_entry *ke, unsigned int *scancode); int input_get_keycode(struct input_dev *dev, struct input_keymap_entry *ke); int input_set_keycode(struct input_dev *dev, const struct input_keymap_entry *ke); extern struct class input_class; /** * struct ff_device - force-feedback part of an input device * @upload: Called to upload an new effect into device * @erase: Called to erase an effect from device * @playback: Called to request device to start playing specified effect * @set_gain: Called to set specified gain * @set_autocenter: Called to auto-center device * @destroy: called by input core when parent input device is being * destroyed * @private: driver-specific data, will be freed automatically * @ffbit: bitmap of force feedback capabilities truly supported by * device (not emulated like ones in input_dev->ffbit) * @mutex: mutex for serializing access to the device * @max_effects: maximum number of effects supported by device * @effects: pointer to an array of effects currently loaded into device * @effect_owners: array of effect owners; when file handle owning * an effect gets closed the effect is automatically erased * * Every force-feedback device must implement upload() and playback() * methods; erase() is optional. set_gain() and set_autocenter() need * only be implemented if driver sets up FF_GAIN and FF_AUTOCENTER * bits. * * Note that playback(), set_gain() and set_autocenter() are called with * dev->event_lock spinlock held and interrupts off and thus may not * sleep. */ struct ff_device { int (*upload)(struct input_dev *dev, struct ff_effect *effect, struct ff_effect *old); int (*erase)(struct input_dev *dev, int effect_id); int (*playback)(struct input_dev *dev, int effect_id, int value); void (*set_gain)(struct input_dev *dev, u16 gain); void (*set_autocenter)(struct input_dev *dev, u16 magnitude); void (*destroy)(struct ff_device *); void *private; unsigned long ffbit[BITS_TO_LONGS(FF_CNT)]; struct mutex mutex; int max_effects; struct ff_effect *effects; struct file *effect_owners[]; }; int input_ff_create(struct input_dev *dev, unsigned int max_effects); void input_ff_destroy(struct input_dev *dev); int input_ff_event(struct input_dev *dev, unsigned int type, unsigned int code, int value); int input_ff_upload(struct input_dev *dev, struct ff_effect *effect, struct file *file); int input_ff_erase(struct input_dev *dev, int effect_id, struct file *file); int input_ff_create_memless(struct input_dev *dev, void *data, int (*play_effect)(struct input_dev *, void *, struct ff_effect *)); #endif #endif
AK-Kernel/AK-OnePone
include/linux/input.h
C
gpl-2.0
51,961
/* * Copyright (C) 2016-2022 ActionTech. * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher. */ package com.actiontech.dble.util.exception; public class NotSupportException extends RuntimeException { private static final long serialVersionUID = 7394431636300968222L; public NotSupportException(String errorCode, String errorDesc, Throwable cause) { super(errorCode + ":" + errorDesc, cause); } public NotSupportException(String errorCode, String errorDesc) { super(errorCode + ":" + errorDesc); } public NotSupportException(String errorCode, Throwable cause) { super(errorCode, cause); } public NotSupportException(String errorCode) { super(errorCode); } public NotSupportException(Throwable cause) { super(cause); } public NotSupportException() { super("not support yet!"); } }
actiontech/dble
src/main/java/com/actiontech/dble/util/exception/NotSupportException.java
Java
gpl-2.0
911
\hypertarget{event__groups_8c}{}\section{/var/www/html/\+S\+J\+S\+U-\/\+D\+E\+V-\/\+Linux/firmware/default/lib/\+L1\+\_\+\+Free\+R\+T\+O\+S/src/event\+\_\+groups.c File Reference} \label{event__groups_8c}\index{/var/www/html/\+S\+J\+S\+U-\/\+D\+E\+V-\/\+Linux/firmware/default/lib/\+L1\+\_\+\+Free\+R\+T\+O\+S/src/event\+\_\+groups.\+c@{/var/www/html/\+S\+J\+S\+U-\/\+D\+E\+V-\/\+Linux/firmware/default/lib/\+L1\+\_\+\+Free\+R\+T\+O\+S/src/event\+\_\+groups.\+c}} {\ttfamily \#include $<$stdlib.\+h$>$}\\* {\ttfamily \#include \char`\"{}Free\+R\+T\+O\+S.\+h\char`\"{}}\\* {\ttfamily \#include \char`\"{}task.\+h\char`\"{}}\\* {\ttfamily \#include \char`\"{}timers.\+h\char`\"{}}\\* {\ttfamily \#include \char`\"{}event\+\_\+groups.\+h\char`\"{}}\\* Include dependency graph for event\+\_\+groups.\+c\+:\nopagebreak \begin{figure}[H] \begin{center} \leavevmode \includegraphics[width=350pt]{d2/d48/event__groups_8c__incl} \end{center} \end{figure} \subsection*{Data Structures} \begin{DoxyCompactItemize} \item struct \hyperlink{structxEventGroupDefinition}{x\+Event\+Group\+Definition} \end{DoxyCompactItemize} \subsection*{Macros} \begin{DoxyCompactItemize} \item \#define \hyperlink{event__groups_8c_ab622d8c674f2a417a666a7ed89109e79}{M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE} \item \#define \hyperlink{event__groups_8c_a1404686af7c8070fa57675707c817abc}{event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT}~0x01000000\+UL \item \#define \hyperlink{event__groups_8c_ab451d5ad95813d5ec7ff1784d69e9ec3}{event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET}~0x02000000\+UL \item \#define \hyperlink{event__groups_8c_ae98d5f1271845ad42742aef9659e1568}{event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS}~0x04000000\+UL \item \#define \hyperlink{event__groups_8c_a46c8292a6ba88b017cca402f5baf670b}{event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES}~0xff000000\+UL \end{DoxyCompactItemize} \subsection*{Typedefs} \begin{DoxyCompactItemize} \item typedef struct \hyperlink{structxEventGroupDefinition}{x\+Event\+Group\+Definition} \hyperlink{event__groups_8c_a52ebd73f8020418f71e63c2f3934f999}{Event\+Group\+\_\+t} \end{DoxyCompactItemize} \subsection*{Functions} \begin{DoxyCompactItemize} \item \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} \hyperlink{event__groups_8c_ac38db316f0928c7ddaacb677a75dbc03}{x\+Event\+Group\+Sync} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group, const \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} ux\+Bits\+To\+Set, const \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} ux\+Bits\+To\+Wait\+For, \hyperlink{portmacro_8h_aa69c48c6e902ce54f70886e6573c92a9}{Tick\+Type\+\_\+t} x\+Ticks\+To\+Wait) \item \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} \hyperlink{event__groups_8c_a379c5cca4552d3d8acd4c51e8220a6c3}{x\+Event\+Group\+Wait\+Bits} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group, const \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} ux\+Bits\+To\+Wait\+For, const \hyperlink{portmacro_8h_a46fb21e00ae0729d7515c0fbf2269796}{Base\+Type\+\_\+t} x\+Clear\+On\+Exit, const \hyperlink{portmacro_8h_a46fb21e00ae0729d7515c0fbf2269796}{Base\+Type\+\_\+t} x\+Wait\+For\+All\+Bits, \hyperlink{portmacro_8h_aa69c48c6e902ce54f70886e6573c92a9}{Tick\+Type\+\_\+t} x\+Ticks\+To\+Wait) \item \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} \hyperlink{event__groups_8c_a71dd2680fdfbdde7d6b10db203e266ba}{x\+Event\+Group\+Clear\+Bits} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group, const \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} ux\+Bits\+To\+Clear) \item \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} \hyperlink{event__groups_8c_adcb3d3f7dded9fa372bb1ee405c36b8d}{x\+Event\+Group\+Get\+Bits\+From\+I\+SR} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group) \item \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} \hyperlink{event__groups_8c_a9ac7cd970f50e2e50a494b656e0eb239}{x\+Event\+Group\+Set\+Bits} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group, const \hyperlink{event__groups_8h_ab2f21b93db0b2a0ab64d7a81ff32ac2e}{Event\+Bits\+\_\+t} ux\+Bits\+To\+Set) \item void \hyperlink{event__groups_8c_a6939faca89fc4ba52fa8288527042464}{v\+Event\+Group\+Delete} (\hyperlink{event__groups_8h_a5119294106541c4eca46e8742fdb4e85}{Event\+Group\+Handle\+\_\+t} x\+Event\+Group) \item void \hyperlink{event__groups_8c_a54db6cc97bbb926aa4b78d5affc257d9}{v\+Event\+Group\+Set\+Bits\+Callback} (void $\ast$pv\+Event\+Group, const uint32\+\_\+t ul\+Bits\+To\+Set) \item void \hyperlink{event__groups_8c_a3bce459038e87064109c8462b1174c29}{v\+Event\+Group\+Clear\+Bits\+Callback} (void $\ast$pv\+Event\+Group, const uint32\+\_\+t ul\+Bits\+To\+Clear) \end{DoxyCompactItemize} \subsection{Macro Definition Documentation} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT@{event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT}} \index{event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT@{event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT}{eventCLEAR_EVENTS_ON_EXIT_BIT}}]{\setlength{\rightskip}{0pt plus 5cm}\#define event\+C\+L\+E\+A\+R\+\_\+\+E\+V\+E\+N\+T\+S\+\_\+\+O\+N\+\_\+\+E\+X\+I\+T\+\_\+\+B\+IT~0x01000000\+UL}\hypertarget{event__groups_8c_a1404686af7c8070fa57675707c817abc}{}\label{event__groups_8c_a1404686af7c8070fa57675707c817abc} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES@{event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES}} \index{event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES@{event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES}{eventEVENT_BITS_CONTROL_BYTES}}]{\setlength{\rightskip}{0pt plus 5cm}\#define event\+E\+V\+E\+N\+T\+\_\+\+B\+I\+T\+S\+\_\+\+C\+O\+N\+T\+R\+O\+L\+\_\+\+B\+Y\+T\+ES~0xff000000\+UL}\hypertarget{event__groups_8c_a46c8292a6ba88b017cca402f5baf670b}{}\label{event__groups_8c_a46c8292a6ba88b017cca402f5baf670b} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET@{event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET}} \index{event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET@{event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET}{eventUNBLOCKED_DUE_TO_BIT_SET}}]{\setlength{\rightskip}{0pt plus 5cm}\#define event\+U\+N\+B\+L\+O\+C\+K\+E\+D\+\_\+\+D\+U\+E\+\_\+\+T\+O\+\_\+\+B\+I\+T\+\_\+\+S\+ET~0x02000000\+UL}\hypertarget{event__groups_8c_ab451d5ad95813d5ec7ff1784d69e9ec3}{}\label{event__groups_8c_ab451d5ad95813d5ec7ff1784d69e9ec3} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS@{event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS}} \index{event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS@{event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS}{eventWAIT_FOR_ALL_BITS}}]{\setlength{\rightskip}{0pt plus 5cm}\#define event\+W\+A\+I\+T\+\_\+\+F\+O\+R\+\_\+\+A\+L\+L\+\_\+\+B\+I\+TS~0x04000000\+UL}\hypertarget{event__groups_8c_ae98d5f1271845ad42742aef9659e1568}{}\label{event__groups_8c_ae98d5f1271845ad42742aef9659e1568} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE@{M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE}} \index{M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE@{M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE}{MPU_WRAPPERS_INCLUDED_FROM_API_FILE}}]{\setlength{\rightskip}{0pt plus 5cm}\#define M\+P\+U\+\_\+\+W\+R\+A\+P\+P\+E\+R\+S\+\_\+\+I\+N\+C\+L\+U\+D\+E\+D\+\_\+\+F\+R\+O\+M\+\_\+\+A\+P\+I\+\_\+\+F\+I\+LE}\hypertarget{event__groups_8c_ab622d8c674f2a417a666a7ed89109e79}{}\label{event__groups_8c_ab622d8c674f2a417a666a7ed89109e79} \subsection{Typedef Documentation} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!Event\+Group\+\_\+t@{Event\+Group\+\_\+t}} \index{Event\+Group\+\_\+t@{Event\+Group\+\_\+t}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{Event\+Group\+\_\+t}{EventGroup_t}}]{\setlength{\rightskip}{0pt plus 5cm}typedef struct {\bf x\+Event\+Group\+Definition} {\bf Event\+Group\+\_\+t}}\hypertarget{event__groups_8c_a52ebd73f8020418f71e63c2f3934f999}{}\label{event__groups_8c_a52ebd73f8020418f71e63c2f3934f999} \subsection{Function Documentation} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!v\+Event\+Group\+Clear\+Bits\+Callback@{v\+Event\+Group\+Clear\+Bits\+Callback}} \index{v\+Event\+Group\+Clear\+Bits\+Callback@{v\+Event\+Group\+Clear\+Bits\+Callback}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{v\+Event\+Group\+Clear\+Bits\+Callback(void $\ast$pv\+Event\+Group, const uint32\+\_\+t ul\+Bits\+To\+Clear)}{vEventGroupClearBitsCallback(void *pvEventGroup, const uint32_t ulBitsToClear)}}]{\setlength{\rightskip}{0pt plus 5cm}void v\+Event\+Group\+Clear\+Bits\+Callback ( \begin{DoxyParamCaption} \item[{void $\ast$}]{pv\+Event\+Group, } \item[{const uint32\+\_\+t}]{ul\+Bits\+To\+Clear} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a3bce459038e87064109c8462b1174c29}{}\label{event__groups_8c_a3bce459038e87064109c8462b1174c29} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!v\+Event\+Group\+Delete@{v\+Event\+Group\+Delete}} \index{v\+Event\+Group\+Delete@{v\+Event\+Group\+Delete}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{v\+Event\+Group\+Delete(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group)}{vEventGroupDelete(EventGroupHandle_t xEventGroup)}}]{\setlength{\rightskip}{0pt plus 5cm}void v\+Event\+Group\+Delete ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a6939faca89fc4ba52fa8288527042464}{}\label{event__groups_8c_a6939faca89fc4ba52fa8288527042464} \hyperlink{event__groups_8h}{event\+\_\+groups.\+h} \begin{DoxyPre} void xEventGroupDelete( EventGroupHandle\_t xEventGroup ); \end{DoxyPre} Delete an event group that was previously created by a call to x\+Event\+Group\+Create(). Tasks that are blocked on the event group will be unblocked and obtain 0 as the event group\textquotesingle{}s value. \begin{DoxyParams}{Parameters} {\em x\+Event\+Group} & The event group being deleted. \\ \hline \end{DoxyParams} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!v\+Event\+Group\+Set\+Bits\+Callback@{v\+Event\+Group\+Set\+Bits\+Callback}} \index{v\+Event\+Group\+Set\+Bits\+Callback@{v\+Event\+Group\+Set\+Bits\+Callback}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{v\+Event\+Group\+Set\+Bits\+Callback(void $\ast$pv\+Event\+Group, const uint32\+\_\+t ul\+Bits\+To\+Set)}{vEventGroupSetBitsCallback(void *pvEventGroup, const uint32_t ulBitsToSet)}}]{\setlength{\rightskip}{0pt plus 5cm}void v\+Event\+Group\+Set\+Bits\+Callback ( \begin{DoxyParamCaption} \item[{void $\ast$}]{pv\+Event\+Group, } \item[{const uint32\+\_\+t}]{ul\+Bits\+To\+Set} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a54db6cc97bbb926aa4b78d5affc257d9}{}\label{event__groups_8c_a54db6cc97bbb926aa4b78d5affc257d9} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!x\+Event\+Group\+Clear\+Bits@{x\+Event\+Group\+Clear\+Bits}} \index{x\+Event\+Group\+Clear\+Bits@{x\+Event\+Group\+Clear\+Bits}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{x\+Event\+Group\+Clear\+Bits(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group, const Event\+Bits\+\_\+t ux\+Bits\+To\+Clear)}{xEventGroupClearBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear)}}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Event\+Bits\+\_\+t} x\+Event\+Group\+Clear\+Bits ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group, } \item[{const {\bf Event\+Bits\+\_\+t}}]{ux\+Bits\+To\+Clear} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a71dd2680fdfbdde7d6b10db203e266ba}{}\label{event__groups_8c_a71dd2680fdfbdde7d6b10db203e266ba} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!x\+Event\+Group\+Get\+Bits\+From\+I\+SR@{x\+Event\+Group\+Get\+Bits\+From\+I\+SR}} \index{x\+Event\+Group\+Get\+Bits\+From\+I\+SR@{x\+Event\+Group\+Get\+Bits\+From\+I\+SR}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{x\+Event\+Group\+Get\+Bits\+From\+I\+S\+R(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group)}{xEventGroupGetBitsFromISR(EventGroupHandle_t xEventGroup)}}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Event\+Bits\+\_\+t} x\+Event\+Group\+Get\+Bits\+From\+I\+SR ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_adcb3d3f7dded9fa372bb1ee405c36b8d}{}\label{event__groups_8c_adcb3d3f7dded9fa372bb1ee405c36b8d} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!x\+Event\+Group\+Set\+Bits@{x\+Event\+Group\+Set\+Bits}} \index{x\+Event\+Group\+Set\+Bits@{x\+Event\+Group\+Set\+Bits}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{x\+Event\+Group\+Set\+Bits(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group, const Event\+Bits\+\_\+t ux\+Bits\+To\+Set)}{xEventGroupSetBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet)}}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Event\+Bits\+\_\+t} x\+Event\+Group\+Set\+Bits ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group, } \item[{const {\bf Event\+Bits\+\_\+t}}]{ux\+Bits\+To\+Set} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a9ac7cd970f50e2e50a494b656e0eb239}{}\label{event__groups_8c_a9ac7cd970f50e2e50a494b656e0eb239} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!x\+Event\+Group\+Sync@{x\+Event\+Group\+Sync}} \index{x\+Event\+Group\+Sync@{x\+Event\+Group\+Sync}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{x\+Event\+Group\+Sync(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group, const Event\+Bits\+\_\+t ux\+Bits\+To\+Set, const Event\+Bits\+\_\+t ux\+Bits\+To\+Wait\+For, Tick\+Type\+\_\+t x\+Ticks\+To\+Wait)}{xEventGroupSync(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait)}}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Event\+Bits\+\_\+t} x\+Event\+Group\+Sync ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group, } \item[{const {\bf Event\+Bits\+\_\+t}}]{ux\+Bits\+To\+Set, } \item[{const {\bf Event\+Bits\+\_\+t}}]{ux\+Bits\+To\+Wait\+For, } \item[{{\bf Tick\+Type\+\_\+t}}]{x\+Ticks\+To\+Wait} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_ac38db316f0928c7ddaacb677a75dbc03}{}\label{event__groups_8c_ac38db316f0928c7ddaacb677a75dbc03} \index{event\+\_\+groups.\+c@{event\+\_\+groups.\+c}!x\+Event\+Group\+Wait\+Bits@{x\+Event\+Group\+Wait\+Bits}} \index{x\+Event\+Group\+Wait\+Bits@{x\+Event\+Group\+Wait\+Bits}!event\+\_\+groups.\+c@{event\+\_\+groups.\+c}} \subsubsection[{\texorpdfstring{x\+Event\+Group\+Wait\+Bits(\+Event\+Group\+Handle\+\_\+t x\+Event\+Group, const Event\+Bits\+\_\+t ux\+Bits\+To\+Wait\+For, const Base\+Type\+\_\+t x\+Clear\+On\+Exit, const Base\+Type\+\_\+t x\+Wait\+For\+All\+Bits, Tick\+Type\+\_\+t x\+Ticks\+To\+Wait)}{xEventGroupWaitBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait)}}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Event\+Bits\+\_\+t} x\+Event\+Group\+Wait\+Bits ( \begin{DoxyParamCaption} \item[{{\bf Event\+Group\+Handle\+\_\+t}}]{x\+Event\+Group, } \item[{const {\bf Event\+Bits\+\_\+t}}]{ux\+Bits\+To\+Wait\+For, } \item[{const {\bf Base\+Type\+\_\+t}}]{x\+Clear\+On\+Exit, } \item[{const {\bf Base\+Type\+\_\+t}}]{x\+Wait\+For\+All\+Bits, } \item[{{\bf Tick\+Type\+\_\+t}}]{x\+Ticks\+To\+Wait} \end{DoxyParamCaption} )}\hypertarget{event__groups_8c_a379c5cca4552d3d8acd4c51e8220a6c3}{}\label{event__groups_8c_a379c5cca4552d3d8acd4c51e8220a6c3}
kammce/SJSU-DEV-Linux
docs/api/latex/d1/d99/event__groups_8c.tex
TeX
gpl-2.0
18,131
var app = require('../../server'); var request = require('supertest'); var should = require('should'); var mongoose = require('mongoose'); var User = mongoose.model('User'); var Ranking = mongoose.model('Ranking'); var user, ranking; describe('Ranking controller unit tests:', function() { beforeEach(function(done) { user = new User({ firstName: 'Some', lastName: 'Name', email: 'mail@example.com', username: 'usrn', password: 'pass>=6', }); user.save(function() { ranking = new Ranking({ name: 'My Ranking', description: 'Test ranking', formula: 'x + y', published: true, user: user, }); ranking.save(function(err) { done(); }); }); }); describe('Testing the GET methods', function() { it('Should be able to get the list of rankings', function(done) { request(app).get('/api/rankings/') .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { res.body.should.be.an.Array.and.have.lengthOf(1); res.body[0].should.have.property('name', ranking.name); res.body[0].should.have.property('description', ranking.description); res.body[0].should.have.property('formula', ranking.formula); res.body[0].should.have.property('published', ranking.published); done(); }) ; }); }); afterEach(function(done) { Ranking.remove().exec(); User.remove().exec(); done(); }); });
peap/rankcfb
app/tests/rankings.controllers.js
JavaScript
gpl-2.0
1,838
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * * THIS FILE WAS MODIFIED BY SUN MICROSYSTEMS, INC. */ package com.sun.xml.internal.fastinfoset.stax.events; import javax.xml.namespace.QName; import javax.xml.stream.events.Attribute; import com.sun.xml.internal.fastinfoset.stax.events.Util; public class AttributeBase extends EventBase implements Attribute { //an Attribute consists of a qualified name and value private QName _QName; private String _value; private String _attributeType = null; //A flag indicating whether this attribute was actually specified in the start-tag //of its element or was defaulted from the schema. private boolean _specified = false; public AttributeBase(){ super(ATTRIBUTE); } public AttributeBase(String name, String value) { super(ATTRIBUTE); _QName = new QName(name); _value = value; } public AttributeBase(QName qname, String value) { _QName = qname; _value = value; } public AttributeBase(String prefix, String localName, String value) { this(prefix, null,localName, value, null); } public AttributeBase(String prefix, String namespaceURI, String localName, String value, String attributeType) { if (prefix == null) prefix = ""; _QName = new QName(namespaceURI, localName,prefix); _value = value; _attributeType = (attributeType == null) ? "CDATA":attributeType; } public void setName(QName name){ _QName = name ; } /** * Returns the QName for this attribute */ public QName getName() { return _QName; } public void setValue(String value){ _value = value; } public String getLocalName() { return _QName.getLocalPart(); } /** * Gets the normalized value of this attribute */ public String getValue() { return _value; } public void setAttributeType(String attributeType){ _attributeType = attributeType ; } /** * Gets the type of this attribute, default is * the String "CDATA" * @return the type as a String, default is "CDATA" */ public String getDTDType() { return _attributeType; } /** * A flag indicating whether this attribute was actually * specified in the start-tag of its element, or was defaulted from the schema. * @return returns true if this was specified in the start element */ public boolean isSpecified() { return _specified ; } public void setSpecified(boolean isSpecified){ _specified = isSpecified ; } public String toString() { String prefix = _QName.getPrefix(); if (!Util.isEmptyString(prefix)) return prefix + ":" + _QName.getLocalPart() + "='" + _value + "'"; return _QName.getLocalPart() + "='" + _value + "'"; } }
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/fastinfoset/stax/events/AttributeBase.java
Java
gpl-2.0
4,078
package com.cn.alex.dao; import com.cn.alex.model.User; public interface IUserDao { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
lxb11433/SSM
alex.maven.example/src/main/java/com/cn/alex/dao/IUserDao.java
Java
gpl-2.0
331
#define CONFIG_FBCON_CFB8_MODULE 1
rohankataria/linuxScheduler
include/config/fbcon/cfb8/module.h
C
gpl-2.0
35
/* xfrm_user.c: User interface to configure xfrm engine. * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * * Changes: * Mitsuru KANDA @USAGI * Kazunori MIYAZAWA @USAGI * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * IPv6 support * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/string.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/rtnetlink.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/init.h> #include <linux/security.h> #include <net/sock.h> #include <net/xfrm.h> #include <net/netlink.h> #include <asm/uaccess.h> #include <linux/in6.h> static int verify_one_alg(struct rtattr **xfrma, enum xfrm_attr_type_t type) { struct rtattr *rt = xfrma[type - 1]; struct xfrm_algo *algp; int len; if (!rt) return 0; len = (rt->rta_len - sizeof(*rt)) - sizeof(*algp); if (len < 0) return -EINVAL; algp = RTA_DATA(rt); len -= (algp->alg_key_len + 7U) / 8; if (len < 0) return -EINVAL; switch (type) { case XFRMA_ALG_AUTH: if (!algp->alg_key_len && strcmp(algp->alg_name, "digest_null") != 0) return -EINVAL; break; case XFRMA_ALG_CRYPT: if (!algp->alg_key_len && strcmp(algp->alg_name, "cipher_null") != 0) return -EINVAL; break; case XFRMA_ALG_COMP: /* Zero length keys are legal. */ break; default: return -EINVAL; }; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_encap_tmpl(struct rtattr **xfrma) { struct rtattr *rt = xfrma[XFRMA_ENCAP - 1]; struct xfrm_encap_tmpl *encap; if (!rt) return 0; if ((rt->rta_len - sizeof(*rt)) < sizeof(*encap)) return -EINVAL; return 0; } static inline int verify_sec_ctx_len(struct rtattr **xfrma) { struct rtattr *rt = xfrma[XFRMA_SEC_CTX - 1]; struct xfrm_user_sec_ctx *uctx; int len = 0; if (!rt) return 0; if (rt->rta_len < sizeof(*uctx)) return -EINVAL; uctx = RTA_DATA(rt); len += sizeof(struct xfrm_user_sec_ctx); len += uctx->ctx_len; if (uctx->len != len) return -EINVAL; return 0; } #ifdef CONFIG_XFRM_ENHANCEMENT static int verify_one_addr(struct rtattr **xfrma) { struct rtattr *rt = xfrma[XFRMA_ADDR - 1]; xfrm_address_t *addr; if (!rt) return 0; if ((rt->rta_len - sizeof(*rt)) < sizeof(*addr)) return -EINVAL; return 0; } #endif static int verify_newsa_info(struct xfrm_usersa_info *p, struct rtattr **xfrma) { int err; err = -EINVAL; switch (p->family) { case AF_INET: break; case AF_INET6: #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) break; #else err = -EAFNOSUPPORT; goto out; #endif default: goto out; }; err = -EINVAL; switch (p->id.proto) { case IPPROTO_AH: if (!xfrma[XFRMA_ALG_AUTH-1] || xfrma[XFRMA_ALG_CRYPT-1] || xfrma[XFRMA_ALG_COMP-1]) goto out; break; case IPPROTO_ESP: if ((!xfrma[XFRMA_ALG_AUTH-1] && !xfrma[XFRMA_ALG_CRYPT-1]) || xfrma[XFRMA_ALG_COMP-1]) goto out; break; case IPPROTO_COMP: if (!xfrma[XFRMA_ALG_COMP-1] || xfrma[XFRMA_ALG_AUTH-1] || xfrma[XFRMA_ALG_CRYPT-1]) goto out; break; #ifdef CONFIG_XFRM_ENHANCEMENT case IPPROTO_DSTOPTS: case IPPROTO_ROUTING: if (xfrma[XFRMA_ALG_COMP-1] || xfrma[XFRMA_ALG_AUTH-1] || xfrma[XFRMA_ALG_CRYPT-1] || !xfrma[XFRMA_ADDR-1]) { XFRM_DBG("invalid netlink message attributes.\n"); goto out; } /* * SPI must be 0 until assigning by kernel. */ if (p->id.spi) { printk(KERN_WARNING "%s: spi(specified %u) will be assigned by kernel\n", __FUNCTION__, p->id.spi); p->id.spi = 0; } break; #endif default: #ifdef CONFIG_XFRM_ENHANCEMENT err = -EPROTONOSUPPORT; #endif goto out; }; if ((err = verify_one_alg(xfrma, XFRMA_ALG_AUTH))) goto out; if ((err = verify_one_alg(xfrma, XFRMA_ALG_CRYPT))) goto out; if ((err = verify_one_alg(xfrma, XFRMA_ALG_COMP))) goto out; if ((err = verify_encap_tmpl(xfrma))) goto out; if ((err = verify_sec_ctx_len(xfrma))) goto out; #ifdef CONFIG_XFRM_ENHANCEMENT if ((err = verify_one_addr(xfrma))) goto out; #endif err = -EINVAL; switch (p->mode) { #ifdef CONFIG_XFRM_ENHANCEMENT case XFRM_MODE_TRANSPORT: case XFRM_MODE_TUNNEL: case XFRM_MODE_ROUTEOPTIMIZATION: #else case XFRM_MODE_TRANSPORT: case XFRM_MODE_TUNNEL: #endif break; default: goto out; }; err = 0; out: return err; } static int attach_one_algo(struct xfrm_algo **algpp, u8 *props, struct xfrm_algo_desc *(*get_byname)(char *, int), struct rtattr *u_arg) { struct rtattr *rta = u_arg; struct xfrm_algo *p, *ualg; struct xfrm_algo_desc *algo; int len; if (!rta) return 0; ualg = RTA_DATA(rta); algo = get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; len = sizeof(*ualg) + (ualg->alg_key_len + 7U) / 8; p = kmalloc(len, GFP_KERNEL); if (!p) return -ENOMEM; memcpy(p, ualg, len); *algpp = p; return 0; } static int attach_encap_tmpl(struct xfrm_encap_tmpl **encapp, struct rtattr *u_arg) { struct rtattr *rta = u_arg; struct xfrm_encap_tmpl *p, *uencap; if (!rta) return 0; uencap = RTA_DATA(rta); p = kmalloc(sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; memcpy(p, uencap, sizeof(*p)); *encapp = p; return 0; } static inline int xfrm_user_sec_ctx_size(struct xfrm_policy *xp) { struct xfrm_sec_ctx *xfrm_ctx = xp->security; int len = 0; if (xfrm_ctx) { len += sizeof(struct xfrm_user_sec_ctx); len += xfrm_ctx->ctx_len; } return len; } static int attach_sec_ctx(struct xfrm_state *x, struct rtattr *u_arg) { struct xfrm_user_sec_ctx *uctx; if (!u_arg) return 0; uctx = RTA_DATA(u_arg); return security_xfrm_state_alloc(x, uctx); } #ifdef CONFIG_XFRM_ENHANCEMENT static int attach_one_addr(xfrm_address_t **addrpp, struct rtattr *u_arg) { struct rtattr *rta = u_arg; xfrm_address_t *p, *uaddrp; if (!rta) return 0; uaddrp = RTA_DATA(rta); p = kmalloc(sizeof(*p), GFP_KERNEL); if (!p) return -ENOMEM; memcpy(p, uaddrp, sizeof(*p)); *addrpp = p; return 0; } #endif static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&x->id, &p->id, sizeof(x->id)); memcpy(&x->sel, &p->sel, sizeof(x->sel)); memcpy(&x->lft, &p->lft, sizeof(x->lft)); x->props.mode = p->mode; x->props.replay_window = p->replay_window; x->props.reqid = p->reqid; x->props.family = p->family; x->props.saddr = p->saddr; x->props.flags = p->flags; } /* * someday when pfkey also has support, we could have the code * somehow made shareable and move it to xfrm_state.c - JHS * */ static int xfrm_update_ae_params(struct xfrm_state *x, struct rtattr **xfrma) { int err = - EINVAL; struct rtattr *rp = xfrma[XFRMA_REPLAY_VAL-1]; struct rtattr *lt = xfrma[XFRMA_LTIME_VAL-1]; struct rtattr *et = xfrma[XFRMA_ETIMER_THRESH-1]; struct rtattr *rt = xfrma[XFRMA_REPLAY_THRESH-1]; if (rp) { struct xfrm_replay_state *replay; if (RTA_PAYLOAD(rp) < sizeof(*replay)) goto error; replay = RTA_DATA(rp); memcpy(&x->replay, replay, sizeof(*replay)); memcpy(&x->preplay, replay, sizeof(*replay)); } if (lt) { struct xfrm_lifetime_cur *ltime; if (RTA_PAYLOAD(lt) < sizeof(*ltime)) goto error; ltime = RTA_DATA(lt); x->curlft.bytes = ltime->bytes; x->curlft.packets = ltime->packets; x->curlft.add_time = ltime->add_time; x->curlft.use_time = ltime->use_time; } if (et) { if (RTA_PAYLOAD(et) < sizeof(u32)) goto error; x->replay_maxage = *(u32*)RTA_DATA(et); } if (rt) { if (RTA_PAYLOAD(rt) < sizeof(u32)) goto error; x->replay_maxdiff = *(u32*)RTA_DATA(rt); } return 0; error: return err; } static struct xfrm_state *xfrm_state_construct(struct xfrm_usersa_info *p, struct rtattr **xfrma, int *errp) { struct xfrm_state *x = xfrm_state_alloc(); int err = -ENOMEM; if (!x) goto error_no_put; copy_from_user_state(x, p); if ((err = attach_one_algo(&x->aalg, &x->props.aalgo, xfrm_aalg_get_byname, xfrma[XFRMA_ALG_AUTH-1]))) goto error; if ((err = attach_one_algo(&x->ealg, &x->props.ealgo, xfrm_ealg_get_byname, xfrma[XFRMA_ALG_CRYPT-1]))) goto error; if ((err = attach_one_algo(&x->calg, &x->props.calgo, xfrm_calg_get_byname, xfrma[XFRMA_ALG_COMP-1]))) goto error; if ((err = attach_encap_tmpl(&x->encap, xfrma[XFRMA_ENCAP-1]))) goto error; #ifdef CONFIG_XFRM_ENHANCEMENT if ((err = attach_one_addr(&x->coaddr, xfrma[XFRMA_ADDR-1]))) goto error; #endif err = xfrm_init_state(x); if (err) goto error; if ((err = attach_sec_ctx(x, xfrma[XFRMA_SEC_CTX-1]))) goto error; x->km.seq = p->seq; x->replay_maxdiff = sysctl_xfrm_aevent_rseqth; /* sysctl_xfrm_aevent_etime is in 100ms units */ x->replay_maxage = (sysctl_xfrm_aevent_etime*HZ)/XFRM_AE_ETH_M; x->preplay.bitmap = 0; x->preplay.seq = x->replay.seq+x->replay_maxdiff; x->preplay.oseq = x->replay.oseq +x->replay_maxdiff; /* override default values from above */ err = xfrm_update_ae_params(x, (struct rtattr **)xfrma); if (err < 0) goto error; return x; error: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); error_no_put: *errp = err; return NULL; } static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_usersa_info *p = NLMSG_DATA(nlh); struct xfrm_state *x; int err; struct km_event c; err = verify_newsa_info(p, (struct rtattr **)xfrma); if (err) return err; x = xfrm_state_construct(p, (struct rtattr **)xfrma, &err); if (!x) return err; xfrm_state_hold(x); if (nlh->nlmsg_type == XFRM_MSG_NEWSA) err = xfrm_state_add(x); else err = xfrm_state_update(x); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } #ifdef CONFIG_XFRM_ENHANCEMENT static struct xfrm_state *xfrm_user_state_lookup(struct xfrm_usersa_id *p) { if (!xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) return xfrm_state_lookup_byaddr(&p->daddr, &p->saddr, p->proto, p->family); else return xfrm_state_lookup(&p->daddr, p->spi, p->proto, p->family); } #endif static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_state *x; int err; struct km_event c; struct xfrm_usersa_id *p = NLMSG_DATA(nlh); #ifdef CONFIG_XFRM_ENHANCEMENT x = xfrm_user_state_lookup(p); #else x = xfrm_state_lookup(&p->daddr, p->spi, p->proto, p->family); #endif if (x == NULL) return -ESRCH; if ((err = security_xfrm_state_delete(x)) != 0) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); p->saddr = x->props.saddr; p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } struct xfrm_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; int start_idx; int this_idx; }; static int dump_one_state(struct xfrm_state *x, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct xfrm_usersa_info *p; struct nlmsghdr *nlh; unsigned char *b = skb->tail; if (sp->this_idx < sp->start_idx) goto out; nlh = NLMSG_PUT(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWSA, sizeof(*p)); nlh->nlmsg_flags = sp->nlmsg_flags; p = NLMSG_DATA(nlh); copy_to_user_state(x, p); if (x->aalg) RTA_PUT(skb, XFRMA_ALG_AUTH, sizeof(*(x->aalg))+(x->aalg->alg_key_len+7)/8, x->aalg); if (x->ealg) RTA_PUT(skb, XFRMA_ALG_CRYPT, sizeof(*(x->ealg))+(x->ealg->alg_key_len+7)/8, x->ealg); if (x->calg) RTA_PUT(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg); if (x->encap) RTA_PUT(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap); if (x->security) { int ctx_size = sizeof(struct xfrm_sec_ctx) + x->security->ctx_len; struct rtattr *rt = __RTA_PUT(skb, XFRMA_SEC_CTX, ctx_size); struct xfrm_user_sec_ctx *uctx = RTA_DATA(rt); uctx->exttype = XFRMA_SEC_CTX; uctx->len = ctx_size; uctx->ctx_doi = x->security->ctx_doi; uctx->ctx_alg = x->security->ctx_alg; uctx->ctx_len = x->security->ctx_len; memcpy(uctx + 1, x->security->ctx_str, x->security->ctx_len); } #ifdef CONFIG_XFRM_ENHANCEMENT if (x->coaddr) RTA_PUT(skb, XFRMA_ADDR, sizeof(*x->coaddr), x->coaddr); #endif nlh->nlmsg_len = skb->tail - b; out: sp->this_idx++; return 0; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) { struct xfrm_dump_info info; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; info.this_idx = 0; info.start_idx = cb->args[0]; #ifdef CONFIG_XFRM_ENHANCEMENT (void) xfrm_state_walk(0, dump_one_state, &info); #else (void) xfrm_state_walk(IPSEC_PROTO_ANY, dump_one_state, &info); #endif cb->args[0] = info.this_idx; return skb->len; } static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, struct xfrm_state *x, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; skb = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); NETLINK_CB(skb).dst_pid = NETLINK_CB(in_skb).pid; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; info.this_idx = info.start_idx = 0; if (dump_one_state(x, 0, &info)) { kfree_skb(skb); return NULL; } return skb; } static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_usersa_id *p = NLMSG_DATA(nlh); struct xfrm_state *x; struct sk_buff *resp_skb; int err; #ifdef CONFIG_XFRM_ENHANCEMENT x = xfrm_user_state_lookup(p); #else x = xfrm_state_lookup(&p->daddr, p->spi, p->proto, p->family); #endif err = -ESRCH; if (x == NULL) goto out_noput; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = netlink_unicast(xfrm_nl, resp_skb, NETLINK_CB(skb).pid, MSG_DONTWAIT); } xfrm_state_put(x); out_noput: return err; } static int verify_userspi_info(struct xfrm_userspi_info *p) { switch (p->info.id.proto) { case IPPROTO_AH: case IPPROTO_ESP: break; case IPPROTO_COMP: /* IPCOMP spi is 16-bits. */ if (p->max >= 0x10000) return -EINVAL; break; default: return -EINVAL; }; if (p->min > p->max) return -EINVAL; return 0; } static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_state *x; struct xfrm_userspi_info *p; struct sk_buff *resp_skb; xfrm_address_t *daddr; int family; int err; p = NLMSG_DATA(nlh); err = verify_userspi_info(p); if (err) goto out_noput; family = p->info.family; daddr = &p->info.id.daddr; x = NULL; if (p->info.seq) { x = xfrm_find_acq_byseq(p->info.seq); if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(p->info.mode, p->info.reqid, p->info.id.proto, daddr, &p->info.saddr, 1, family); err = -ENOENT; if (x == NULL) goto out_noput; resp_skb = ERR_PTR(-ENOENT); spin_lock_bh(&x->lock); if (x->km.state != XFRM_STATE_DEAD) { xfrm_alloc_spi(x, htonl(p->min), htonl(p->max)); if (x->id.spi) resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); } spin_unlock_bh(&x->lock); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); goto out; } err = netlink_unicast(xfrm_nl, resp_skb, NETLINK_CB(skb).pid, MSG_DONTWAIT); out: xfrm_state_put(x); out_noput: return err; } static int verify_policy_dir(__u8 dir) { switch (dir) { case XFRM_POLICY_IN: case XFRM_POLICY_OUT: #ifdef CONFIG_USE_POLICY_FWD case XFRM_POLICY_FWD: #endif break; default: return -EINVAL; }; return 0; } static int verify_newpolicy_info(struct xfrm_userpolicy_info *p) { switch (p->share) { case XFRM_SHARE_ANY: case XFRM_SHARE_SESSION: case XFRM_SHARE_USER: case XFRM_SHARE_UNIQUE: break; default: return -EINVAL; }; switch (p->action) { case XFRM_POLICY_ALLOW: case XFRM_POLICY_BLOCK: break; default: return -EINVAL; }; switch (p->sel.family) { case AF_INET: break; case AF_INET6: #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) break; #else return -EAFNOSUPPORT; #endif default: return -EINVAL; }; return verify_policy_dir(p->dir); } static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct rtattr **xfrma) { struct rtattr *rt = xfrma[XFRMA_SEC_CTX-1]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = RTA_DATA(rt); return security_xfrm_policy_alloc(pol, uctx); } static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut, int nr) { int i; xp->xfrm_nr = nr; for (i = 0; i < nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&t->id, &ut->id, sizeof(struct xfrm_id)); memcpy(&t->saddr, &ut->saddr, sizeof(xfrm_address_t)); t->reqid = ut->reqid; t->mode = ut->mode; t->share = ut->share; t->optional = ut->optional; t->aalgos = ut->aalgos; t->ealgos = ut->ealgos; t->calgos = ut->calgos; } } static int copy_from_user_tmpl(struct xfrm_policy *pol, struct rtattr **xfrma) { struct rtattr *rt = xfrma[XFRMA_TMPL-1]; struct xfrm_user_tmpl *utmpl; int nr; if (!rt) { pol->xfrm_nr = 0; } else { nr = (rt->rta_len - sizeof(*rt)) / sizeof(*utmpl); if (nr > XFRM_MAX_DEPTH) return -EINVAL; copy_templates(pol, RTA_DATA(rt), nr); } return 0; } static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p) { xp->priority = p->priority; xp->index = p->index; memcpy(&xp->selector, &p->sel, sizeof(xp->selector)); memcpy(&xp->lft, &p->lft, sizeof(xp->lft)); xp->action = p->action; xp->flags = p->flags; xp->family = p->sel.family; /* XXX xp->share = p->share; */ } static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ } static struct xfrm_policy *xfrm_policy_construct(struct xfrm_userpolicy_info *p, struct rtattr **xfrma, int *errp) { struct xfrm_policy *xp = xfrm_policy_alloc(GFP_KERNEL); int err; if (!xp) { *errp = -ENOMEM; return NULL; } copy_from_user_policy(xp, p); if (!(err = copy_from_user_tmpl(xp, xfrma))) err = copy_from_user_sec_ctx(xp, xfrma); if (err) { *errp = err; kfree(xp); xp = NULL; } return xp; } static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_userpolicy_info *p = NLMSG_DATA(nlh); struct xfrm_policy *xp; struct km_event c; int err; int excl; err = verify_newpolicy_info(p); if (err) return err; err = verify_sec_ctx_len((struct rtattr **)xfrma); if (err) return err; xp = xfrm_policy_construct(p, (struct rtattr **)xfrma, &err); if (!xp) return err; /* shouldnt excl be based on nlh flags?? * Aha! this is anti-netlink really i.e more pfkey derived * in netlink excl is a flag and you wouldnt need * a type XFRM_MSG_UPDPOLICY - JHS */ excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY; err = xfrm_policy_insert(p->dir, xp, excl); if (err) { security_xfrm_policy_free(xp); kfree(xp); return err; } c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); xfrm_pol_put(xp); return 0; } static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = xp->family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } RTA_PUT(skb, XFRMA_TMPL, (sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr), vec); return 0; rtattr_failure: return -1; } static int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb) { if (xp->security) { int ctx_size = sizeof(struct xfrm_sec_ctx) + xp->security->ctx_len; struct rtattr *rt = __RTA_PUT(skb, XFRMA_SEC_CTX, ctx_size); struct xfrm_user_sec_ctx *uctx = RTA_DATA(rt); uctx->exttype = XFRMA_SEC_CTX; uctx->len = ctx_size; uctx->ctx_doi = xp->security->ctx_doi; uctx->ctx_alg = xp->security->ctx_alg; uctx->ctx_len = xp->security->ctx_len; memcpy(uctx + 1, xp->security->ctx_str, xp->security->ctx_len); } return 0; rtattr_failure: return -1; } static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct xfrm_userpolicy_info *p; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct nlmsghdr *nlh; unsigned char *b = skb->tail; if (sp->this_idx < sp->start_idx) goto out; nlh = NLMSG_PUT(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWPOLICY, sizeof(*p)); p = NLMSG_DATA(nlh); nlh->nlmsg_flags = sp->nlmsg_flags; copy_to_user_policy(xp, p, dir); if (copy_to_user_tmpl(xp, skb) < 0) goto nlmsg_failure; if (copy_to_user_sec_ctx(xp, skb)) goto nlmsg_failure; nlh->nlmsg_len = skb->tail - b; out: sp->this_idx++; return 0; nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct xfrm_dump_info info; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; info.this_idx = 0; info.start_idx = cb->args[0]; (void) xfrm_policy_walk(dump_one_policy, &info); cb->args[0] = info.this_idx; return skb->len; } static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); NETLINK_CB(skb).dst_pid = NETLINK_CB(in_skb).pid; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; info.this_idx = info.start_idx = 0; if (dump_one_policy(xp, dir, 0, &info) < 0) { kfree_skb(skb); return NULL; } return skb; } static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_policy *xp; struct xfrm_userpolicy_id *p; int err; struct km_event c; int delete; p = NLMSG_DATA(nlh); delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(p->dir, p->index, delete); else { struct rtattr **rtattrs = (struct rtattr **)xfrma; struct rtattr *rt = rtattrs[XFRMA_SEC_CTX-1]; struct xfrm_policy tmp; err = verify_sec_ctx_len(rtattrs); if (err) return err; memset(&tmp, 0, sizeof(struct xfrm_policy)); if (rt) { struct xfrm_user_sec_ctx *uctx = RTA_DATA(rt); if ((err = security_xfrm_policy_alloc(&tmp, uctx))) return err; } xp = xfrm_policy_bysel_ctx(p->dir, &p->sel, tmp.security, delete); security_xfrm_policy_free(&tmp); } if (xp == NULL) return -ENOENT; if (!delete) { struct sk_buff *resp_skb; resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = netlink_unicast(xfrm_nl, resp_skb, NETLINK_CB(skb).pid, MSG_DONTWAIT); } } else { if ((err = security_xfrm_policy_delete(xp)) != 0) goto out; c.data.byid = p->index; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); } xfrm_pol_put(xp); out: return err; } static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct km_event c; struct xfrm_usersa_flush *p = NLMSG_DATA(nlh); xfrm_state_flush(p->proto); c.data.proto = p->proto; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_state_notify(NULL, &c); return 0; } static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, struct km_event *c) { struct xfrm_aevent_id *id; struct nlmsghdr *nlh; struct xfrm_lifetime_cur ltime; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id)); id = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; id->sa_id.daddr = x->id.daddr; id->sa_id.spi = x->id.spi; id->sa_id.family = x->props.family; id->sa_id.proto = x->id.proto; id->flags = c->data.aevent; RTA_PUT(skb, XFRMA_REPLAY_VAL, sizeof(x->replay), &x->replay); ltime.bytes = x->curlft.bytes; ltime.packets = x->curlft.packets; ltime.add_time = x->curlft.add_time; ltime.use_time = x->curlft.use_time; RTA_PUT(skb, XFRMA_LTIME_VAL, sizeof(struct xfrm_lifetime_cur), &ltime); if (id->flags&XFRM_AE_RTHR) { RTA_PUT(skb,XFRMA_REPLAY_THRESH,sizeof(u32),&x->replay_maxdiff); } if (id->flags&XFRM_AE_ETHR) { u32 etimer = x->replay_maxage*10/HZ; RTA_PUT(skb,XFRMA_ETIMER_THRESH,sizeof(u32),&etimer); } nlh->nlmsg_len = skb->tail - b; return skb->len; rtattr_failure: nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_state *x; struct sk_buff *r_skb; int err; struct km_event c; struct xfrm_aevent_id *p = NLMSG_DATA(nlh); int len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id)); struct xfrm_usersa_id *id = &p->sa_id; len += RTA_SPACE(sizeof(struct xfrm_replay_state)); len += RTA_SPACE(sizeof(struct xfrm_lifetime_cur)); if (p->flags&XFRM_AE_RTHR) len+=RTA_SPACE(sizeof(u32)); if (p->flags&XFRM_AE_ETHR) len+=RTA_SPACE(sizeof(u32)); r_skb = alloc_skb(len, GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; x = xfrm_state_lookup(&id->daddr, id->spi, id->proto, id->family); if (x == NULL) { kfree(r_skb); return -ESRCH; } /* * XXX: is this lock really needed - none of the other * gets lock (the concern is things getting updated * while we are still reading) - jhs */ spin_lock_bh(&x->lock); c.data.aevent = p->flags; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; if (build_aevent(r_skb, x, &c) < 0) BUG(); err = netlink_unicast(xfrm_nl, r_skb, NETLINK_CB(skb).pid, MSG_DONTWAIT); spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_state *x; struct km_event c; int err = - EINVAL; struct xfrm_aevent_id *p = NLMSG_DATA(nlh); struct rtattr *rp = xfrma[XFRMA_REPLAY_VAL-1]; struct rtattr *lt = xfrma[XFRMA_LTIME_VAL-1]; if (!lt && !rp) return err; /* pedantic mode - thou shalt sayeth replaceth */ if (!(nlh->nlmsg_flags&NLM_F_REPLACE)) return err; x = xfrm_state_lookup(&p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; if (x->km.state != XFRM_STATE_VALID) goto out; spin_lock_bh(&x->lock); err = xfrm_update_ae_params(x,(struct rtattr **)xfrma); spin_unlock_bh(&x->lock); if (err < 0) goto out; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.data.aevent = XFRM_AE_CU; km_state_notify(x, &c); err = 0; out: xfrm_state_put(x); return err; } static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct km_event c; xfrm_policy_flush(); c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(NULL, 0, &c); return 0; } static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_policy *xp; struct xfrm_user_polexpire *up = NLMSG_DATA(nlh); struct xfrm_userpolicy_info *p = &up->pol; int err = -ENOENT; if (p->index) xp = xfrm_policy_byid(p->dir, p->index, 0); else { struct rtattr **rtattrs = (struct rtattr **)xfrma; struct rtattr *rt = rtattrs[XFRMA_SEC_CTX-1]; struct xfrm_policy tmp; err = verify_sec_ctx_len(rtattrs); if (err) return err; memset(&tmp, 0, sizeof(struct xfrm_policy)); if (rt) { struct xfrm_user_sec_ctx *uctx = RTA_DATA(rt); if ((err = security_xfrm_policy_alloc(&tmp, uctx))) return err; } xp = xfrm_policy_bysel_ctx(p->dir, &p->sel, tmp.security, 0); security_xfrm_policy_free(&tmp); } if (xp == NULL) return err; read_lock(&xp->lock); if (xp->dead) { read_unlock(&xp->lock); goto out; } read_unlock(&xp->lock); err = 0; if (up->hard) { xfrm_policy_delete(xp, p->dir); } else { // reset the timers here? printk("Dont know what to do with soft policy expire\n"); } km_policy_expired(xp, p->dir, up->hard, current->pid); out: xfrm_pol_put(xp); return err; } static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_state *x; int err; struct xfrm_user_expire *ue = NLMSG_DATA(nlh); struct xfrm_usersa_info *p = &ue->state; x = xfrm_state_lookup(&p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) return err; err = -EINVAL; spin_lock_bh(&x->lock); if (x->km.state != XFRM_STATE_VALID) goto out; km_state_expired(x, ue->hard, current->pid); if (ue->hard) __xfrm_state_delete(x); out: spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_policy *xp; struct xfrm_user_tmpl *ut; int i; struct rtattr *rt = xfrma[XFRMA_TMPL-1]; struct xfrm_user_acquire *ua = NLMSG_DATA(nlh); struct xfrm_state *x = xfrm_state_alloc(); int err = -ENOMEM; if (!x) return err; err = verify_newpolicy_info(&ua->policy); if (err) { printk("BAD policy passed\n"); kfree(x); return err; } /* build an XP */ xp = xfrm_policy_construct(&ua->policy, (struct rtattr **) xfrma, &err); if (!xp) { kfree(x); return err; } memcpy(&x->id, &ua->id, sizeof(ua->id)); memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr)); memcpy(&x->sel, &ua->sel, sizeof(ua->sel)); ut = RTA_DATA(rt); /* extract the templates and for each call km_key */ for (i = 0; i < xp->xfrm_nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&x->id, &t->id, sizeof(x->id)); x->props.mode = t->mode; x->props.reqid = t->reqid; x->props.family = ut->family; t->aalgos = ua->aalgos; t->ealgos = ua->ealgos; t->calgos = ua->calgos; err = km_query(x, t, xp, XFRM_POLICY_OUT); } kfree(x); kfree(xp); return 0; } #ifdef CONFIG_XFRM_MIGRATE /* * Change the endpoint addresses. * */ static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, void **xfrma) { struct xfrm_user_migrate *m = NLMSG_DATA(nlh); struct rtattr *rt = xfrma[XFRMA_POLICY-1]; struct xfrm_userpolicy_id *pol = NULL; int err = -EINVAL; if (!m) goto error; switch (m->family) { case AF_INET: break; case AF_INET6: #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) break; #else XFRM_DBG("%s: not supported family = %u\n", __FUNCTION__, m->family); err = -EAFNOSUPPORT; goto error; #endif default: XFRM_DBG("%s: invalid family = %u\n", __FUNCTION__, m->family); err = -EINVAL; goto error; } if (rt) { if ((rt->rta_len - sizeof(*rt)) < sizeof(*pol)) { err = -EINVAL; goto error; } pol = RTA_DATA(rt); err = verify_policy_dir(pol->dir); if (err) { XFRM_DBG("%s: invalid dir = %d\n", __FUNCTION__, pol->dir); goto error; } } if (!pol) { err = -EINVAL; goto error; } return xfrm_migrate(m, pol); error: return err; } #endif #define XMSGSIZE(type) NLMSG_LENGTH(sizeof(struct type)) static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info), [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire), [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire), [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire), [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush), [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = NLMSG_LENGTH(0), [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), #ifdef CONFIG_XFRM_MIGRATE [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_migrate), #endif #ifdef CONFIG_XFRM_ENHANCEMENT [XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report), #endif }; #undef XMSGSIZE static struct xfrm_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, void **); int (*dump)(struct sk_buff *, struct netlink_callback *); } xfrm_dispatch[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa }, [XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa, .dump = xfrm_dump_sa }, [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy }, [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy, .dump = xfrm_dump_policy }, [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi }, [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire }, [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire }, [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire}, [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa }, [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy }, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae }, [XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae }, #ifdef CONFIG_XFRM_MIGRATE [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate }, #endif }; static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, int *errp) { struct rtattr *xfrma[XFRMA_MAX]; struct xfrm_link *link; int type, min_len; if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) return 0; type = nlh->nlmsg_type; /* A control message: ignore them */ if (type < XFRM_MSG_BASE) return 0; /* Unknown message: reply with EINVAL */ if (type > XFRM_MSG_MAX) goto err_einval; type -= XFRM_MSG_BASE; link = &xfrm_dispatch[type]; /* All operations require privileges, even GET */ if (security_netlink_recv(skb, CAP_NET_ADMIN)) { *errp = -EPERM; return -1; } if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) || type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) && (nlh->nlmsg_flags & NLM_F_DUMP)) { if (link->dump == NULL) goto err_einval; if ((*errp = netlink_dump_start(xfrm_nl, skb, nlh, link->dump, NULL)) != 0) { return -1; } netlink_queue_skip(nlh, skb); return -1; } memset(xfrma, 0, sizeof(xfrma)); if (nlh->nlmsg_len < (min_len = xfrm_msg_min[type])) goto err_einval; if (nlh->nlmsg_len > min_len) { int attrlen = nlh->nlmsg_len - NLMSG_ALIGN(min_len); struct rtattr *attr = (void *) nlh + NLMSG_ALIGN(min_len); while (RTA_OK(attr, attrlen)) { unsigned short flavor = attr->rta_type; if (flavor) { if (flavor > XFRMA_MAX) goto err_einval; xfrma[flavor - 1] = attr; } attr = RTA_NEXT(attr, attrlen); } } if (link->doit == NULL) goto err_einval; *errp = link->doit(skb, nlh, (void **) &xfrma); return *errp; err_einval: *errp = -EINVAL; return -1; } static void xfrm_netlink_rcv(struct sock *sk, int len) { unsigned int qlen = 0; do { mutex_lock(&xfrm_cfg_mutex); netlink_run_queue(sk, &qlen, &xfrm_user_rcv_msg); mutex_unlock(&xfrm_cfg_mutex); } while (qlen); } static int build_expire(struct sk_buff *skb, struct xfrm_state *x, struct km_event *c) { struct xfrm_user_expire *ue; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue)); ue = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; copy_to_user_state(x, &ue->state); ue->hard = (c->data.hard != 0) ? 1 : 0; nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_exp_state_notify(struct xfrm_state *x, struct km_event *c) { struct sk_buff *skb; int len = NLMSG_LENGTH(sizeof(struct xfrm_user_expire)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_expire(skb, x, c) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_EXPIRE; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_aevent_state_notify(struct xfrm_state *x, struct km_event *c) { struct sk_buff *skb; int len = NLMSG_LENGTH(sizeof(struct xfrm_aevent_id)); len += RTA_SPACE(sizeof(struct xfrm_replay_state)); len += RTA_SPACE(sizeof(struct xfrm_lifetime_cur)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_aevent(skb, x, c) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_AEVENTS; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC); } static int xfrm_notify_sa_flush(struct km_event *c) { struct xfrm_usersa_flush *p; struct nlmsghdr *nlh; struct sk_buff *skb; unsigned char *b; int len = NLMSG_LENGTH(sizeof(struct xfrm_usersa_flush)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p)); nlh->nlmsg_flags = 0; p = NLMSG_DATA(nlh); p->proto = c->data.proto; nlh->nlmsg_len = skb->tail - b; NETLINK_CB(skb).dst_group = XFRMNLGRP_SA; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); nlmsg_failure: kfree_skb(skb); return -1; } static int inline xfrm_sa_len(struct xfrm_state *x) { int l = 0; if (x->aalg) l += RTA_SPACE(sizeof(*x->aalg) + (x->aalg->alg_key_len+7)/8); if (x->ealg) l += RTA_SPACE(sizeof(*x->ealg) + (x->ealg->alg_key_len+7)/8); if (x->calg) l += RTA_SPACE(sizeof(*x->calg)); if (x->encap) l += RTA_SPACE(sizeof(*x->encap)); return l; } static int xfrm_notify_sa(struct xfrm_state *x, struct km_event *c) { struct xfrm_usersa_info *p; struct xfrm_usersa_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; unsigned char *b; int len = xfrm_sa_len(x); int headlen; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELSA) { len += RTA_SPACE(headlen); headlen = sizeof(*id); } len += NLMSG_SPACE(headlen); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, c->seq, c->event, headlen); nlh->nlmsg_flags = 0; p = NLMSG_DATA(nlh); if (c->event == XFRM_MSG_DELSA) { id = NLMSG_DATA(nlh); memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr)); id->spi = x->id.spi; id->family = x->props.family; id->proto = x->id.proto; p = RTA_DATA(__RTA_PUT(skb, XFRMA_SA, sizeof(*p))); } copy_to_user_state(x, p); if (x->aalg) RTA_PUT(skb, XFRMA_ALG_AUTH, sizeof(*(x->aalg))+(x->aalg->alg_key_len+7)/8, x->aalg); if (x->ealg) RTA_PUT(skb, XFRMA_ALG_CRYPT, sizeof(*(x->ealg))+(x->ealg->alg_key_len+7)/8, x->ealg); if (x->calg) RTA_PUT(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg); if (x->encap) RTA_PUT(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap); nlh->nlmsg_len = skb->tail - b; NETLINK_CB(skb).dst_group = XFRMNLGRP_SA; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); nlmsg_failure: rtattr_failure: kfree_skb(skb); return -1; } static int xfrm_send_state_notify(struct xfrm_state *x, struct km_event *c) { switch (c->event) { case XFRM_MSG_EXPIRE: return xfrm_exp_state_notify(x, c); case XFRM_MSG_NEWAE: return xfrm_aevent_state_notify(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_UPDSA: case XFRM_MSG_NEWSA: return xfrm_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return xfrm_notify_sa_flush(c); default: printk("xfrm_user: Unknown SA event %d\n", c->event); break; } return 0; } static int build_acquire(struct sk_buff *skb, struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { struct xfrm_user_acquire *ua; struct nlmsghdr *nlh; unsigned char *b = skb->tail; __u32 seq = xfrm_get_acqseq(); nlh = NLMSG_PUT(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua)); ua = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; memcpy(&ua->id, &x->id, sizeof(ua->id)); memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr)); memcpy(&ua->sel, &x->sel, sizeof(ua->sel)); copy_to_user_policy(xp, &ua->policy, dir); ua->aalgos = xt->aalgos; ua->ealgos = xt->ealgos; ua->calgos = xt->calgos; ua->seq = x->km.seq = seq; if (copy_to_user_tmpl(xp, skb) < 0) goto nlmsg_failure; if (copy_to_user_sec_ctx(xp, skb)) goto nlmsg_failure; nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { struct sk_buff *skb; size_t len; len = RTA_SPACE(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); len += NLMSG_SPACE(sizeof(struct xfrm_user_acquire)); len += RTA_SPACE(xfrm_user_sec_ctx_size(xp)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_acquire(skb, x, xt, xp, dir) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_ACQUIRE; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC); } /* User gives us xfrm_user_policy_info followed by an array of 0 * or more templates. */ static struct xfrm_policy *xfrm_compile_policy(u16 family, int opt, u8 *data, int len, int *dir) { struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data; struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1); struct xfrm_policy *xp; int nr; switch (family) { case AF_INET: if (opt != IP_XFRM_POLICY && opt != IP_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case AF_INET6: if (opt != IPV6_XFRM_POLICY && opt != IPV6_IPSEC_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(*p) || verify_newpolicy_info(p)) return NULL; nr = ((len - sizeof(*p)) / sizeof(*ut)); if (nr > XFRM_MAX_DEPTH) return NULL; if (p->dir > XFRM_POLICY_OUT) return NULL; xp = xfrm_policy_alloc(GFP_KERNEL); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } copy_from_user_policy(xp, p); copy_templates(xp, ut, nr); *dir = p->dir; return xp; } static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp, int dir, struct km_event *c) { struct xfrm_user_polexpire *upe; struct nlmsghdr *nlh; int hard = c->data.hard; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe)); upe = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; copy_to_user_policy(xp, &upe->pol, dir); if (copy_to_user_tmpl(xp, skb) < 0) goto nlmsg_failure; if (copy_to_user_sec_ctx(xp, skb)) goto nlmsg_failure; upe->hard = !!hard; nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, struct km_event *c) { struct sk_buff *skb; size_t len; len = RTA_SPACE(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); len += NLMSG_SPACE(sizeof(struct xfrm_user_polexpire)); len += RTA_SPACE(xfrm_user_sec_ctx_size(xp)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_polexpire(skb, xp, dir, c) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_EXPIRE; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, struct km_event *c) { struct xfrm_userpolicy_info *p; struct xfrm_userpolicy_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; unsigned char *b; int len = RTA_SPACE(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); int headlen; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELPOLICY) { len += RTA_SPACE(headlen); headlen = sizeof(*id); } len += NLMSG_SPACE(headlen); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, c->seq, c->event, headlen); p = NLMSG_DATA(nlh); if (c->event == XFRM_MSG_DELPOLICY) { id = NLMSG_DATA(nlh); memset(id, 0, sizeof(*id)); id->dir = dir; if (c->data.byid) id->index = xp->index; else memcpy(&id->sel, &xp->selector, sizeof(id->sel)); p = RTA_DATA(__RTA_PUT(skb, XFRMA_POLICY, sizeof(*p))); } nlh->nlmsg_flags = 0; copy_to_user_policy(xp, p, dir); if (copy_to_user_tmpl(xp, skb) < 0) goto nlmsg_failure; nlh->nlmsg_len = skb->tail - b; NETLINK_CB(skb).dst_group = XFRMNLGRP_POLICY; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); nlmsg_failure: rtattr_failure: kfree_skb(skb); return -1; } static int xfrm_notify_policy_flush(struct km_event *c) { struct nlmsghdr *nlh; struct sk_buff *skb; unsigned char *b; int len = NLMSG_LENGTH(0); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; b = skb->tail; nlh = NLMSG_PUT(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0); nlh->nlmsg_len = skb->tail - b; NETLINK_CB(skb).dst_group = XFRMNLGRP_POLICY; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); nlmsg_failure: kfree_skb(skb); return -1; } static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, struct km_event *c) { switch (c->event) { case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: case XFRM_MSG_DELPOLICY: return xfrm_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: return xfrm_notify_policy_flush(c); case XFRM_MSG_POLEXPIRE: return xfrm_exp_policy_notify(xp, dir, c); default: printk("xfrm_user: Unknown Policy event %d\n", c->event); } return 0; } #ifdef CONFIG_XFRM_MIGRATE static int build_migrate(struct sk_buff *skb, struct xfrm_user_migrate *m, struct xfrm_userpolicy_id *id) { struct xfrm_user_migrate *um; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*um)); um = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; memcpy(um, m, sizeof(*um)); if (id) RTA_PUT(skb, XFRMA_POLICY, sizeof(*id), id); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_send_migrate(struct xfrm_user_migrate *m, struct xfrm_userpolicy_id *id) { struct sk_buff *skb; size_t len; len = RTA_SPACE(sizeof(struct xfrm_userpolicy_id)); len += NLMSG_SPACE(sizeof(struct xfrm_user_migrate)); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_migrate(skb, m, id) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_MIGRATE; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC); } #endif #ifdef CONFIG_XFRM_ENHANCEMENT static int build_report(struct sk_buff *skb, __u8 dir, __u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct xfrm_user_report *ur; struct nlmsghdr *nlh; unsigned char *b = skb->tail; nlh = NLMSG_PUT(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur)); ur = NLMSG_DATA(nlh); nlh->nlmsg_flags = 0; ur->dir = dir; ur->proto = proto; memcpy(&ur->sel, sel, sizeof(ur->sel)); if (addr) RTA_PUT(skb, XFRMA_ADDR, sizeof(*addr), addr); XFRM_DBG("%s: dir = %d,\n", __FUNCTION__, dir); XFRM_DBG(" ifindex = %d,\n", sel->ifindex); XFRM_DBG(" dst = %s,\n", XFRMSTRADDR(sel->daddr, sel->family)); XFRM_DBG(" src = %s,\n", XFRMSTRADDR(sel->saddr, sel->family)); if (addr) XFRM_DBG(" coa = %s,\n", XFRMSTRADDR(*addr, sel->family)); XFRM_DBG(" flow = %u, xfrm = %u\n", sel->proto, proto); nlh->nlmsg_len = skb->tail - b; return skb->len; nlmsg_failure: rtattr_failure: skb_trim(skb, b - skb->data); return -1; } static int xfrm_send_report(__u8 dir, __u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct sk_buff *skb; size_t len; len = NLMSG_ALIGN(NLMSG_LENGTH(sizeof(struct xfrm_user_report))); skb = alloc_skb(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_report(skb, dir, proto, sel, addr) < 0) BUG(); NETLINK_CB(skb).dst_group = XFRMNLGRP_REPORT; return netlink_broadcast(xfrm_nl, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC); } #endif static struct xfrm_mgr netlink_mgr = { .id = "netlink", .notify = xfrm_send_state_notify, .acquire = xfrm_send_acquire, .compile_policy = xfrm_compile_policy, .notify_policy = xfrm_send_policy_notify, #ifdef CONFIG_XFRM_MIGRATE .migrate = xfrm_send_migrate, #endif #ifdef CONFIG_XFRM_ENHANCEMENT .report = xfrm_send_report, #endif }; static int __init xfrm_user_init(void) { struct sock *nlsk; printk(KERN_INFO "Initializing XFRM netlink socket\n"); nlsk = netlink_kernel_create(NETLINK_XFRM, XFRMNLGRP_MAX, xfrm_netlink_rcv, THIS_MODULE); if (nlsk == NULL) return -ENOMEM; rcu_assign_pointer(xfrm_nl, nlsk); xfrm_register_km(&netlink_mgr); return 0; } static void __exit xfrm_user_exit(void) { struct sock *nlsk = xfrm_nl; xfrm_unregister_km(&netlink_mgr); rcu_assign_pointer(xfrm_nl, NULL); synchronize_rcu(); sock_release(nlsk->sk_socket); } module_init(xfrm_user_init); module_exit(xfrm_user_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
xoox/linux-2.6.18_pro500
net/xfrm/xfrm_user.c
C
gpl-2.0
51,270
/* Copyright (C) 2006 - 2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * 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 */ /* ScriptData SDName: Boss_Talon_King_Ikiss SD%Complete: 80 SDComment: Heroic supported. Some details missing, but most are spell related. SDCategory: Auchindoun, Sethekk Halls EndScriptData */ #include "precompiled.h" #include "def_sethekk_halls.h" #define SAY_INTRO -1556007 #define SAY_AGGRO_1 -1556008 #define SAY_AGGRO_2 -1556009 #define SAY_AGGRO_3 -1556010 #define SAY_SLAY_1 -1556011 #define SAY_SLAY_2 -1556012 #define SAY_DEATH -1556013 #define EMOTE_ARCANE_EXP -1556015 #define SPELL_BLINK 38194 #define SPELL_BLINK_TELEPORT 38203 #define SPELL_MANA_SHIELD 38151 #define SPELL_ARCANE_BUBBLE 9438 #define H_SPELL_SLOW 35032 #define SPELL_POLYMORPH 38245 #define H_SPELL_POLYMORPH 43309 #define SPELL_ARCANE_VOLLEY 35059 #define H_SPELL_ARCANE_VOLLEY 40424 #define SPELL_ARCANE_EXPLOSION 38197 #define H_SPELL_ARCANE_EXPLOSION 40425 struct boss_talon_king_ikissAI : public ScriptedAI { boss_talon_king_ikissAI(Creature *c) : ScriptedAI(c) { pInstance = (c->GetInstanceData()); m_creature->GetPosition(wLoc); } ScriptedInstance* pInstance; bool HeroicMode; uint32 ArcaneVolley_Timer; uint32 Sheep_Timer; uint32 Blink_Timer; uint32 Slow_Timer; WorldLocation wLoc; bool ManaShield; bool Blink; bool Intro; void Reset() { HeroicMode = m_creature->GetMap()->IsHeroic(); ArcaneVolley_Timer = 5000; Sheep_Timer = 8000; Blink_Timer = 35000; Slow_Timer = 15000+rand()%15000; Blink = false; Intro = false; ManaShield = false; if(pInstance) pInstance->SetData(DATA_IKISSEVENT, NOT_STARTED); } void MoveInLineOfSight(Unit *who) { if( !m_creature->getVictim() && who->isTargetableForAttack() && ( m_creature->IsHostileTo( who )) && who->isInAccessiblePlacefor(m_creature) ) { if(!Intro && m_creature->IsWithinDistInMap(who, 100)) { Intro = true; DoScriptText(SAY_INTRO, m_creature); } if (!m_creature->CanFly() && m_creature->GetDistanceZ(who) > CREATURE_Z_ATTACK_RANGE) return; float attackRadius = m_creature->GetAttackDistance(who); if( m_creature->IsWithinDistInMap(who, attackRadius) && m_creature->IsWithinLOSInMap(who) ) { //who->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); AttackStart(who); } } } void EnterCombat(Unit *who) { DoScriptText(RAND(SAY_AGGRO_1, SAY_AGGRO_2, SAY_AGGRO_3), m_creature); if(pInstance) pInstance->SetData(DATA_IKISSEVENT, IN_PROGRESS); } void JustDied(Unit* Killer) { DoScriptText(SAY_DEATH, m_creature); if (pInstance) pInstance->SetData(DATA_IKISSEVENT, DONE); } void KilledUnit(Unit* victim) { DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2), m_creature); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (Blink) { DoCast(m_creature,HeroicMode ? H_SPELL_ARCANE_EXPLOSION : SPELL_ARCANE_EXPLOSION); m_creature->CastSpell(m_creature,SPELL_ARCANE_BUBBLE,true); Blink = false; } if (ArcaneVolley_Timer < diff) { DoCast(m_creature,HeroicMode ? H_SPELL_ARCANE_VOLLEY : SPELL_ARCANE_VOLLEY); ArcaneVolley_Timer = 10000+rand()%5000; } else ArcaneVolley_Timer -= diff; if (Sheep_Timer < diff) { //second top aggro target in normal, random target in heroic correct? Unit *target = NULL; target = HeroicMode ? SelectUnit(SELECT_TARGET_RANDOM,0, 60, true) : SelectUnit(SELECT_TARGET_TOPAGGRO,1, 60, true, m_creature->getVictimGUID()); if (target) DoCast(target,HeroicMode ? H_SPELL_POLYMORPH : SPELL_POLYMORPH); Sheep_Timer = 15000+rand()%2500; } else Sheep_Timer -= diff; //may not be correct time to cast if (!ManaShield && ((m_creature->GetHealth()*100) / m_creature->GetMaxHealth() < 20)) { DoCast(m_creature,SPELL_MANA_SHIELD); ManaShield = true; } if (HeroicMode) { if (Slow_Timer < diff) { DoCast(m_creature,H_SPELL_SLOW); Slow_Timer = 15000+rand()%25000; } else Slow_Timer -= diff; } if (Blink_Timer < diff) { DoScriptText(EMOTE_ARCANE_EXP, m_creature); if (Unit *target = SelectUnit(SELECT_TARGET_RANDOM,0, 60, true)) { if (m_creature->IsNonMeleeSpellCasted(false)) m_creature->InterruptNonMeleeSpells(false); //Spell doesn't work, but we use for visual effect at least DoCast(target,SPELL_BLINK); DoTeleportTo(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ()); DoCast(target,SPELL_BLINK_TELEPORT); Blink = true; } Blink_Timer = 35000+rand()%5000; } else Blink_Timer -= diff; if (!Blink) DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_talon_king_ikiss(Creature *_Creature) { return new boss_talon_king_ikissAI (_Creature); } void AddSC_boss_talon_king_ikiss() { Script *newscript; newscript = new Script; newscript->Name="boss_talon_king_ikiss"; newscript->GetAI = &GetAI_boss_talon_king_ikiss; newscript->RegisterSelf(); }
sergeev/hgroundcore
src/scripts/scripts/zone/aunchindoun/sethekk_halls/boss_tailonking_ikiss.cpp
C++
gpl-2.0
6,760
package org.milyn.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; public interface AnnotatedField { public ExtendedAnnotatedClass getAnnotatedClass(); public Field getField(); public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass); public Annotation[] getAllAnnotations(); public <T extends Annotation> T getAnnotation(Class<T> annotationClass); }
alessandrocolantoni/mandragora
src/main/java/org/milyn/annotation/AnnotatedField.java
Java
gpl-2.0
455
"""okc_scraper includes all the functions needed to scrape profiles from OKCupid""" import requests import cPickle as pickle import time from BeautifulSoup import BeautifulSoup def authorize(username, password): """Log into OKCupid to scrape profiles""" user_info = {"username": username, "password": password} okc = requests.session() okc.post("https://www.okcupid.com/login", data=user_info) return okc def getProfiles(okc): """Searches for profiles and returns a list of profiles (10)""" # match_info = {"filter1": "0,63", "filter2": "2,100,18", # "filter3": "5,2678400", "filter4": "1,1", # "locid": "1", "custom_search": "0", # "matchOrderBy": "SPECIAL_BLEND", # "sa": "1", "sort_type": "0", "update_prefs": "1"} soup = BeautifulSoup(okc.post("https://www.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=mwww.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=m").text) users = soup.findAll("div", {"class": "user_info"}) return (["https://www.okcupid.com" + user.find("a")["href"].replace("?cf=regular", "") for user in users], soup) def getProfile(okc, profile_link): """Takes a link to a profile and returns a BeautifulSoup object""" page = BeautifulSoup(okc.get(profile_link).text) return (page, page.find("form", {"id": "flag_form"}) .findAll("input")[0]["value"]) def getInfo(profile, profile_id): """Take a BeautifulSoup object corresponding to a profile's home page and the profile's id and return a list of the profile's user info (username, age, gender...)""" try: main = profile.find("div", {"id": "basic_info"}).findAll("span") return {"id_table": {"user_id": profile_id, "user_name": main[0].text, "user_age": main[1].text, "user_gender": main[2].text, "user_orient": main[3].text, "user_status": main[4].text, "user_location": main[5].text}, } except: print profile return {"id_table": {"user_id": profile_id, "data": "NA"}} def getEssays(profile, profile_id): """Takes a BeautifulSoup object corresponding to a profiles home page and returns a list of the profile's essays""" etd = {"user_id": profile_id, } essay_index = ["self_summary", "my_life", "good_at", "first_thing", "favorite", "six_things", "lot_time", "typical_Friday", "most_private"] main = profile.find("div", {"id": "main_column"}) for i in range(0, 9): try: etd[essay_index[i]] = (main.find("div", {"id": "essay_text_" + str(i)}) .getText(' ')) except: etd[essay_index[i]] = "" return {"essay_table": etd, } def getLookingFor(profile, profile_id): """Takes a BeautifulSoup object corresponding to a profiles home page and returns a list of the profile's looking for items""" try: main = (profile.find("div", {"id": "main_column"}) .find("div", {"id": "what_i_want"}).findAll("li")) if len(main) == 4: return {"looking_for_table": {"user_id": profile_id, "other_user": main[0].text, "other_age": main[1].text, "other_location": main[2].text, "other_type": main[3].text}, } if len(main) == 5: return {"looking_for_table": {"user_id": profile_id, "other_user": main[0].text, "other_age": main[1].text, "other_location": main[2].text, "other_status": main[3].text, "other_type": main[4].text}, } except: print profile return {"looking_for_table": {"user_id": profile_id, "data": "NA"}} def getDetails(profile, profile_id): """Takes a BeautifulSoup object corresponding to profiles home page and returns a list of profile's details""" try: main = profile.find("div", {"id": "profile_details"}).findAll("dd") return {"details_table": {"user_id": profile_id, "last_online": main[0].text, "ethnicity": main[1].text, "height": main[2].text, "body_type": main[3].text, "diet": main[4].text, "smokes": main[5].text, "drinks": main[6].text, "religion": main[7].text, "sign": main[8].text, "education": main[9].text, "job": main[10].text, "income": main[11].text, "offspring": main[12].text, "pets": main[13].text, "speaks": main[14].text}, } except: print profile return {"details_table": {"user_id": profile_id, "data": "NA"}} def getQuestions(okc, profile_link, profile_id): """Take a link to a profile and return a list the questions a user has answered""" # Currently this doesn't return anything. All functions need to be # changed up to work with mysql 07/19/2013 22:50 question_list = [] question_categories = ["Ethics", "Sex", "Religion", "Lifestyle", "Dating", "Other"] for category in question_categories: q = BeautifulSoup(okc.get(profile_link + "/questions?" + category).text) try: max_page = int(q.find("div", {"class": "pages clearfix"}) .findAll("li")[1].find("a").text) except IndexError: max_page = 1 except AttributeError: return [] for page in range(1, max_page + 1): q_page = BeautifulSoup(okc.get(profile_link + "/questions?" + category + "=" + str(page)).text) questions = [q for q in q_page.find("div", {"id": "questions"}) .findAll("div", {"class": "question public talk clearfix"})] for question in questions: question_id = question["id"] qtext = question.find("p", {"class": "qtext"}).text atext = question.find("p", {"class": "answer target clearfix"}).text question_list.append({"question_table": {"user_id": profile_id, "question_id": question_id, "question_text": qtext, "user_answer": atext, "question_category": category}, }) return question_list def pickleDict(dict_, dir): """Takes in a directory and a dictionary to be pickled and pickles the dict in the directory""" dict_id = dict_.keys()[0] tab_i = pickle.load(open(dir + dict_id + ".p", "rb")) tab_i.append(dict_) pickle.dump(tab_i, open(dir + dict_id + ".p", "wb")) def main(okc_instance): """The main event, takes an okc_instance (logged in) and writes a profile to the docs""" profiles, soup = getProfiles(okc_instance) locations = [l.text.split(";")[1] for l in soup.findAll("div", {"class": "userinfo"})] if len([l for l in locations if l == "Chicago, IL"]) > 2: print "Possible Reset" for profile in profiles: prof = getProfile(okc_instance, profile) pickleDict(getInfo(prof[0], prof[1]), "data/") pickleDict(getEssays(prof[0], prof[1]), "data/") pickleDict(getLookingFor(prof[0], prof[1]), "data/") pickleDict(getDetails(prof[0], prof[1]), "data/") time.sleep(2) return prof[1]
lbybee/okc_project
okc_scraper_no_q.py
Python
gpl-2.0
8,941
package net.minecraft.network.status.client; import java.io.IOException; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.status.INetHandlerStatusServer; public class C01PacketPing extends Packet { private long field_149290_a; private static final String __OBFID = "CL_00001392"; public C01PacketPing() {} public C01PacketPing(long p_i45276_1_) { this.field_149290_a = p_i45276_1_; } public void func_148837_a(PacketBuffer p_148837_1_) throws IOException { this.field_149290_a = p_148837_1_.readLong(); } public void func_148840_b(PacketBuffer p_148840_1_) throws IOException { p_148840_1_.writeLong(this.field_149290_a); } public void func_148833_a(INetHandlerStatusServer p_148833_1_) { p_148833_1_.func_147311_a(this); } public boolean func_148836_a() { return true; } public long func_149289_c() { return this.field_149290_a; } // $FF: synthetic method // $FF: bridge method public void func_148833_a(INetHandler p_148833_1_) { this.func_148833_a((INetHandlerStatusServer)p_148833_1_); } }
mviitanen/marsmod
mcp/temp/src/minecraft/net/minecraft/network/status/client/C01PacketPing.java
Java
gpl-2.0
1,214
<?php /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Catalog\Model\Product\Attribute\Source; use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource; use Magento\Eav\Model\Entity\Attribute\Source\SourceInterface; use Magento\Framework\Data\OptionSourceInterface; /** * Product status functionality model * * @api * @since 100.0.2 */ class Status extends AbstractSource implements SourceInterface, OptionSourceInterface { /**#@+ * Product Status values */ const STATUS_ENABLED = 1; const STATUS_DISABLED = 2; /**#@-*/ /** * Retrieve Visible Status Ids * * @return int[] */ public function getVisibleStatusIds() { return [self::STATUS_ENABLED]; } /** * Retrieve Saleable Status Ids * Default Product Enable status * * @return int[] */ public function getSaleableStatusIds() { return [self::STATUS_ENABLED]; } /** * Retrieve option array * * @return string[] */ public static function getOptionArray() { return [self::STATUS_ENABLED => __('Enabled'), self::STATUS_DISABLED => __('Disabled')]; } /** * Retrieve option array with empty value * * @return string[] */ public function getAllOptions() { $result = []; foreach (self::getOptionArray() as $index => $value) { $result[] = ['value' => $index, 'label' => $value]; } return $result; } /** * Retrieve option text by option value * * @param string $optionId * @return string */ public function getOptionText($optionId) { $options = self::getOptionArray(); return isset($options[$optionId]) ? $options[$optionId] : null; } /** * Add Value Sort To Collection Select * * @param \Magento\Eav\Model\Entity\Collection\AbstractCollection $collection * @param string $dir direction * @return AbstractSource */ public function addValueSortToCollection($collection, $dir = 'asc') { $attributeCode = $this->getAttribute()->getAttributeCode(); $attributeId = $this->getAttribute()->getId(); $attributeTable = $this->getAttribute()->getBackend()->getTable(); $linkField = $this->getAttribute()->getEntity()->getLinkField(); if ($this->getAttribute()->isScopeGlobal()) { $tableName = $attributeCode . '_t'; $collection->getSelect()->joinLeft( [$tableName => $attributeTable], "e.{$linkField}={$tableName}.{$linkField}" . " AND {$tableName}.attribute_id='{$attributeId}'" . " AND {$tableName}.store_id='0'", [] ); $valueExpr = $tableName . '.value'; } else { $valueTable1 = $attributeCode . '_t1'; $valueTable2 = $attributeCode . '_t2'; $collection->getSelect()->joinLeft( [$valueTable1 => $attributeTable], "e.{$linkField}={$valueTable1}.{$linkField}" . " AND {$valueTable1}.attribute_id='{$attributeId}'" . " AND {$valueTable1}.store_id='0'", [] )->joinLeft( [$valueTable2 => $attributeTable], "e.{$linkField}={$valueTable2}.{$linkField}" . " AND {$valueTable2}.attribute_id='{$attributeId}'" . " AND {$valueTable2}.store_id='{$collection->getStoreId()}'", [] ); $valueExpr = $collection->getConnection()->getCheckSql( $valueTable2 . '.value_id > 0', $valueTable2 . '.value', $valueTable1 . '.value' ); } $collection->getSelect()->order($valueExpr . ' ' . $dir); return $this; } }
kunj1988/Magento2
app/code/Magento/Catalog/Model/Product/Attribute/Source/Status.php
PHP
gpl-2.0
3,955
<?php /** * Theme Font Generator Admin Page Closing Container * * This file contains the closing the tags for the * html settings page. * * @package Easy_Google_Fonts * @author Sunny Johal - Titanium Themes <support@titaniumthemes.com> * @license GPL-2.0+ * @link http://wordpress.org/plugins/easy-google-fonts/ * @copyright Copyright (c) 2014, Titanium Themes * @version 1.3.7 * */ ?> </div><!-- /.wrap -->
KateYou/LandsEndImages
wp-content/plugins/easy-google-fonts/views/admin-page/page-end.php
PHP
gpl-2.0
438
/* * buffer.h * * Copyright (C) Thomas Oestreich - June 2001 * * This file is part of transcode, a video stream processing tool * * transcode 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, or (at your option) * any later version. * * transcode is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include "transcode.h" #ifndef _BUFFER_H #define _BUFFER_H #define BUFFER_NULL -1 #define BUFFER_EMPTY 0 #define BUFFER_READY 1 #define MAX_PCM_BUFFER (SIZE_PCM_FRAME<<2) typedef struct buffer_list { int id; // buffer number int status; // buffer status struct buffer_list *next; struct buffer_list *prev; int size; char *data; } buffer_list_t; buffer_list_t *buffer_register(int id); void buffer_remove(buffer_list_t *ptr); buffer_list_t *buffer_retrieve(void); extern buffer_list_t *buffer_list_head; extern buffer_list_t *buffer_list_tail; #endif
BackupTheBerlios/tcforge
tools/buffer.h
C
gpl-2.0
1,432
App.IndexController = Ember.Controller.extend({ actions:{ } }); App.IndexRoute = Ember.Route.extend({ model: function() { if(this.get('loaded') == true){ console.log('cached'); return Ember.RSVP.hash({ "news":this.store.all('news'), "assignments":this.store.all('assignment') }) } else console.log('not cached'); this.set('loaded',true); return Ember.RSVP.hash({ "news":this.store.find('news'), "assignments":this.store.find('assignment') }) //return }, actions: { loading: function(transition, originRoute) { // displayLoadingSpinner(); // Return true to bubble this event to `FooRoute` // or `ApplicationRoute`. $("body").spin(true); this.router.one('didTransition', function() { $("body").spin(false); }); return true; } }, setupController: function(controller,model){ this._super(controller, model); controller.set('loaded',new Date()); } });
mrl4214/studybranch
public/js/routes/index.js
JavaScript
gpl-2.0
1,168
# PlayerAugments Augment yourself to do bigger and better things.
tayjay/PlayerAugments
README.md
Markdown
gpl-2.0
66
<?php class Sogenactif { public function __construct($config, $api_key = 0) { $paiement = $config->get('paiement'); $this->api_key = sprintf("%04d", $api_key); $this->config = isset($paiement['sogenactif']) ? $paiement['sogenactif'] : array(); } public function form($data) { $reference = $data['reference'].$this->api_key; $transaction_id = $data['reference'] % 1000000; $html = ""; $parm = " merchant_id=".$this->config['merchant_id']; $parm .= " merchant_country=fr"; $parm .= " amount=".floor($data['montant'] * 100); $parm .= " language=".$data['lgue']; $parm .= " customer_email=".$data['mail']; $parm .= " caddie=".$reference; $parm .= " currency_code=978"; $parm .= " normal_return_url=".$data['normal_return_url']; $parm .= " cancel_return_url=".$data['cancel_return_url']; $parm .= " automatic_response_url=".$data['automatic_response_url']; $parm .= " pathfile=".$this->config['pathfile']; $parm .= " transaction_id=".$transaction_id; $parm .= " order_id=".$data['reference']; $output = array(); $return_var = 0; $result = exec(trim($this->config['request']." ".$parm." 2>&1"), $output, $return_var); $tableau = explode ("!", "$result"); $code = $tableau[1]; $error = $tableau[2]; $message = $tableau[3]; if ($return_var) { $html .= $result; } else if (($code == "") && ($error == "")) { $html .= "<br />erreur appel request<br />"; $html .= "executable request non trouve $path_bin"; } else if ($code != 0) { $html .= "<strong><h2>Erreur appel API de paiement.</h2></strong>"; $html .= "<br /><br /><br />"; $html .= " message erreur : $error <br>"; } else { $html .= "<br /><br />"; $html .= "$message <br />"; } return $html; } public function check($post) { if(isset($post['DATA'])) { $pathfile = "pathfile=".$this->config['pathfile']; $message = "message=".$_POST['DATA']; $result = exec(trim($this->config['response']." ".$message." ".$pathfile)); $tableau = explode ("!", $result); $data = array(); $data['code'] = $tableau[1]; $data['error'] = $tableau[2]; $data['merchant_id'] = $tableau[3]; $data['merchant_country'] = $tableau[4]; $data['amount'] = $tableau[5]; $data['transaction_id'] = $tableau[6]; $data['payment_means'] = $tableau[7]; $data['transmission_date']= $tableau[8]; $data['payment_time'] = $tableau[9]; $data['payment_date'] = $tableau[10]; $data['response_code'] = $tableau[11]; $data['payment_certificate'] = $tableau[12]; $data['authorisation_id'] = $tableau[13]; $data['currency_code'] = $tableau[14]; $data['card_number'] = $tableau[15]; $data['cvv_flag'] = $tableau[16]; $data['cvv_response_code'] = $tableau[17]; $data['bank_response_code'] = $tableau[18]; $data['complementary_code'] = $tableau[19]; $data['complementary_info'] = $tableau[20]; $data['return_context'] = $tableau[21]; $data['caddie'] = $tableau[22]; $data['receipt_complement'] = $tableau[23]; $data['merchant_language'] = $tableau[24]; $data['language'] = $tableau[25]; $data['customer_id'] = $tableau[26]; $data['order_id'] = $tableau[27]; $data['customer_email'] = $tableau[28]; $data['customer_ip_address'] = $tableau[29]; $data['capture_day'] = $tableau[30]; $data['capture_mode'] = $tableau[31]; $data['data'] = $tableau[32]; if (($data['code'] == "") && ($data['error'] == "")) { echo "erreur appel response\n"; print ("executable response non trouve $path_bin\n"); return false; } else if ($data['code'] != 0){ echo " API call error.\n"; echo "Error message : $error\n"; return false; } else { return $data; } } } }
noparking/alticcio
core/paiement/sogenactif.php
PHP
gpl-2.0
3,723
jQuery(document).ready(function($) { "use strict"; $('#woocommerce_pip_reset_start').live('click', function(){ $('#woocommerce_pip_invoice_start').attr('readonly', 'readonly'); if ($(this).is(':checked')) { $('#woocommerce_pip_invoice_start').removeAttr('readonly'); } }); $('#pip_settings').validate({ rules: { woocommerce_pip_invoice_start: { min: 1, digits: true } } }); // Handling uploading of the logo on PIP settings form. // Adapted from Mike Jolley // http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/ var file_frame; $('#upload_image_button').live('click', function( event ){ event.preventDefault(); // If the media frame already exists, reopen it. if ( file_frame ) { file_frame.open(); return; } // Create the media frame. file_frame = wp.media.frames.file_frame = wp.media({ title: jQuery( this ).data( 'uploader_title' ), button: { text: jQuery( this ).data( 'uploader_button_text' ), }, // Set to true to allow multiple files to be selected multiple: false }); // When an image is selected, run a callback. file_frame.on( 'select', function() { // We set multiple to false so only get one image from the uploader var attachment = file_frame.state().get('selection').first().toJSON(); // Send the value of attachment.url back to PIP settings form jQuery('#woocommerce_pip_logo').val(attachment.url); }); // Finally, open the modal file_frame.open(); }); });
danielkalen/bwd_old
wp-content/plugins/woocommerce-pip/js/woocommerce-pip-admin.js
JavaScript
gpl-2.0
1,516
#include <construo/construoGlobals.h> namespace crusta { ConstruoSettings CONSTRUO_SETTINGS; } //namespace crusta
KeckCAVES/crusta
src/construo/construoGlobals.cpp
C++
gpl-2.0
120
ArduinoJson: change log ======================= v5.13.0 ------- * Changed the rules of string duplication (issue #658) * `RawJson()` accepts any kind of string and obeys to the same rules for duplication * Changed the return type of `strdup()` to `const char*` to prevent double duplication * Marked `strdup()` as deprecated > ### New rules for string duplication > > | type | duplication | > |:---------------------------|:------------| > | const char* | no | > | char* | ~~no~~ yes | > | String | yes | > | std::string | yes | > | const __FlashStringHelper* | yes | > > These new rules make `JsonBuffer::strdup()` useless. v5.12.0 ------- * Added `JsonVariant::operator|` to return a default value (see below) * Added a clear error message when compiled as C instead of C++ (issue #629) * Added detection of MPLAB XC compiler (issue #629) * Added detection of Keil ARM Compiler (issue #629) * Added an example that shows how to save and load a configuration file * Reworked all other examples > ### How to use the new feature? > > If you have a block like this: > > ```c++ > const char* ssid = root["ssid"]; > if (!ssid) > ssid = "default ssid"; > ``` > > You can simplify like that: > > ```c++ > const char* ssid = root["ssid"] | "default ssid"; > ``` v5.11.2 ------- * Fixed `DynamicJsonBuffer::clear()` not resetting allocation size (issue #561) * Fixed incorrect rounding for float values (issue #588) v5.11.1 ------- * Removed dependency on `PGM_P` as Particle 0.6.2 doesn't define it (issue #546) * Fixed warning "dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]" * Fixed warning "floating constant exceeds range of 'float' [-Woverflow]" (issue #544) * Fixed warning "this statement may fall through" [-Wimplicit-fallthrough=] (issue #539) * Removed `ARDUINOJSON_DOUBLE_IS_64BITS` as it became useless. * Fixed too many decimals places in float serialization (issue #543) v5.11.0 ------- * Made `JsonBuffer` non-copyable (PR #524 by @luisrayas3) * Added `StaticJsonBuffer::clear()` * Added `DynamicJsonBuffer::clear()` v5.10.1 ------- * Fixed IntelliSense errors in Visual Micro (issue #483) * Fixed compilation in IAR Embedded Workbench (issue #515) * Fixed reading "true" as a float (issue #516) * Added `ARDUINOJSON_DOUBLE_IS_64BITS` * Added `ARDUINOJSON_EMBEDDED_MODE` v5.10.0 ------- * Removed configurable number of decimal places (issues #288, #427 and #506) * Changed exponentiation thresholds to `1e7` and `1e-5` (issues #288, #427 and #506) * `JsonVariant::is<double>()` now returns `true` for integers * Fixed error `IsBaseOf is not a member of ArduinoJson::TypeTraits` (issue #495) * Fixed error `forming reference to reference` (issue #495) > ### BREAKING CHANGES :warning: > > | Old syntax | New syntax | > |:--------------------------------|:--------------------| > | `double_with_n_digits(3.14, 2)` | `3.14` | > | `float_with_n_digits(3.14, 2)` | `3.14f` | > | `obj.set("key", 3.14, 2)` | `obj["key"] = 3.14` | > | `arr.add(3.14, 2)` | `arr.add(3.14)` | > > | Input | Old output | New output | > |:----------|:-----------|:-----------| > | `3.14159` | `3.14` | `3.14159` | > | `42.0` | `42.00` | `42` | > | `0.0` | `0.00` | `0` | > > | Expression | Old result | New result | > |:-------------------------------|:-----------|:-----------| > | `JsonVariant(42).is<int>()` | `true` | `true` | > | `JsonVariant(42).is<float>()` | `false` | `true` | > | `JsonVariant(42).is<double>()` | `false` | `true` | v5.9.0 ------ * Added `JsonArray::remove(iterator)` (issue #479) * Added `JsonObject::remove(iterator)` * Renamed `JsonArray::removeAt(size_t)` into `remove(size_t)` * Renamed folder `include/` to `src/` * Fixed warnings `floating constant exceeds range of float`and `floating constant truncated to zero` (issue #483) * Removed `Print` class and converted `printTo()` to a template method (issue #276) * Removed example `IndentedPrintExample.ino` * Now compatible with Particle 0.6.1, thanks to Jacob Nite (issue #294 and PR #461 by @foodbag) v5.8.4 ------ * Added custom implementation of `strtod()` (issue #453) * Added custom implementation of `strtol()` (issue #465) * `char` is now treated as an integral type (issue #337, #370) v5.8.3 ------ * Fixed an access violation in `DynamicJsonBuffer` when memory allocation fails (issue #433) * Added operators `==` and `!=` for two `JsonVariant`s (issue #436) * Fixed `JsonVariant::operator[const FlashStringHelper*]` (issue #441) v5.8.2 ------ * Fixed parsing of comments (issue #421) * Fixed ignored `Stream` timeout (issue #422) * Made sure we don't read more that necessary (issue #422) * Fixed error when the key of a `JsonObject` is a `char[]` (issue #423) * Reduced code size when using `const` references * Fixed error with string of type `unsigned char*` (issue #428) * Added `deprecated` attribute on `asArray()`, `asObject()` and `asString()` (issue #420) v5.8.1 ------ * Fixed error when assigning a `volatile int` to a `JsonVariant` (issue #415) * Fixed errors with Variable Length Arrays (issue #416) * Fixed error when both `ARDUINOJSON_ENABLE_STD_STREAM` and `ARDUINOJSON_ENABLE_ARDUINO_STREAM` are set to `1` * Fixed error "Stream does not name a type" (issue #412) v5.8.0 ------ * Added operator `==` to compare `JsonVariant` and strings (issue #402) * Added support for `Stream` (issue #300) * Reduced memory consumption by not duplicating spaces and comments > ### BREAKING CHANGES :warning: > > `JsonBuffer::parseObject()` and `JsonBuffer::parseArray()` have been pulled down to the derived classes `DynamicJsonBuffer` and `StaticJsonBufferBase`. > > This means that if you have code like: > > ```c++ > void myFunction(JsonBuffer& jsonBuffer); > ``` > > you need to replace it with one of the following: > > ```c++ > void myFunction(DynamicJsonBuffer& jsonBuffer); > void myFunction(StaticJsonBufferBase& jsonBuffer); > template<typename TJsonBuffer> void myFunction(TJsonBuffer& jsonBuffer); > ``` v5.7.3 ------ * Added an `printTo(char[N])` and `prettyPrintTo(char[N])` (issue #292) * Added ability to set a nested value like this: `root["A"]["B"] = "C"` (issue #352) * Renamed `*.ipp` to `*Impl.hpp` because they were ignored by Arduino IDE (issue #396) v5.7.2 ------ * Made PROGMEM available on more platforms (issue #381) * Fixed PROGMEM causing an exception on ESP8266 (issue #383) v5.7.1 ------ * Added support for PROGMEM (issue #76) * Fixed compilation error when index is not an `int` (issue #381) v5.7.0 ------ * Templatized all functions using `String` or `std::string` * Removed `ArduinoJson::String` * Removed `JsonVariant::defaultValue<T>()` * Removed non-template `JsonObject::get()` and `JsonArray.get()` * Fixed support for `StringSumHelper` (issue #184) * Replaced `ARDUINOJSON_USE_ARDUINO_STRING` by `ARDUINOJSON_ENABLE_STD_STRING` and `ARDUINOJSON_ENABLE_ARDUINO_STRING` (issue #378) * Added example `StringExample.ino` to show where `String` can be used * Increased default nesting limit to 50 when compiled for a computer (issue #349) > ### BREAKING CHANGES :warning: > > The non-template functions `JsonObject::get()` and `JsonArray.get()` have been removed. This means that you need to explicitely tell the type you expect in return. > > Old code: > > ```c++ > #define ARDUINOJSON_USE_ARDUINO_STRING 0 > JsonVariant value1 = myObject.get("myKey"); > JsonVariant value2 = myArray.get(0); > ``` > > New code: > > ```c++ > #define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 > #define ARDUINOJSON_ENABLE_STD_STRING 1 > JsonVariant value1 = myObject.get<JsonVariant>("myKey"); > JsonVariant value2 = myArray.get<JsonVariant>(0); > ``` v5.6.7 ------ * Fixed `array[idx].as<JsonVariant>()` and `object[key].as<JsonVariant>()` * Fixed return value of `JsonObject::set()` (issue #350) * Fixed undefined behavior in `Prettyfier` and `Print` (issue #354) * Fixed parser that incorrectly rejected floats containing a `+` (issue #349) v5.6.6 ------ * Fixed `-Wparentheses` warning introduced in v5.6.5 (PR #335 by @nuket) * Added `.mbedignore` for ARM mbdeb (PR #334 by @nuket) * Fixed `JsonVariant::success()` which didn't propagate `JsonArray::success()` nor `JsonObject::success()` (issue #342). v5.6.5 ------ * `as<char*>()` now returns `true` when input is `null` (issue #330) v5.6.4 ------ * Fixed error in float serialization (issue #324) v5.6.3 ------ * Improved speed of float serialization (about twice faster) * Added `as<JsonArray>()` as a synonym for `as<JsonArray&>()`... (issue #291) * Fixed `call of overloaded isinf(double&) is ambiguous` (issue #284) v5.6.2 ------ * Fixed build when another lib does `#undef isnan` (issue #284) v5.6.1 ------ * Added missing `#pragma once` (issue #310) v5.6.0 ------ * ArduinoJson is now a header-only library (issue #199) v5.5.1 ------ * Fixed compilation error with Intel Galileo (issue #299) v5.5.0 ------ * Added `JsonVariant::success()` (issue #279) * Renamed `JsonVariant::invalid<T>()` to `JsonVariant::defaultValue<T>()` v5.4.0 ------ * Changed `::String` to `ArduinoJson::String` (issue #275) * Changed `::Print` to `ArduinoJson::Print` too v5.3.0 ------ * Added custom implementation of `ftoa` (issues #266, #267, #269 and #270) * Added `JsonVariant JsonBuffer::parse()` (issue #265) * Fixed `unsigned long` printed as `signed long` (issue #170) v5.2.0 ------ * Added `JsonVariant::as<char*>()` as a synonym for `JsonVariant::as<const char*>()` (issue #257) * Added example `JsonHttpClient` (issue #256) * Added `JsonArray::copyTo()` and `JsonArray::copyFrom()` (issue #254) * Added `RawJson()` to insert pregenerated JSON portions (issue #259) v5.1.1 ------ * Removed `String` duplication when one replaces a value in a `JsonObject` (PR #232 by @ulion) v5.1.0 ------ * Added support of `long long` (issue #171) * Moved all build settings to `ArduinoJson/Configuration.hpp` > ### BREAKING CHANGE :warning: > > If you defined `ARDUINOJSON_ENABLE_STD_STREAM`, you now need to define it to `1`. v5.0.8 ------ * Made the library compatible with [PlatformIO](http://platformio.org/) (issue #181) * Fixed `JsonVariant::is<bool>()` that was incorrectly returning false (issue #214) v5.0.7 ------ * Made library easier to use from a CMake project: simply `add_subdirectory(ArduinoJson/src)` * Changed `String` to be a `typedef` of `std::string` (issues #142 and #161) > ### BREAKING CHANGES :warning: > > - `JsonVariant(true).as<String>()` now returns `"true"` instead of `"1"` > - `JsonVariant(false).as<String>()` now returns `"false"` instead of `"0"` v5.0.6 ------ * Added parameter to `DynamicJsonBuffer` constructor to set initial size (issue #152) * Fixed warning about library category in Arduino 1.6.6 (issue #147) * Examples: Added a loop to wait for serial port to be ready (issue #156) v5.0.5 ------ * Added overload `JsonObjectSuscript::set(value, decimals)` (issue #143) * Use `float` instead of `double` to reduce the size of `JsonVariant` (issue #134) v5.0.4 ------ * Fixed ambiguous overload with `JsonArraySubscript` and `JsonObjectSubscript` (issue #122) v5.0.3 ------ * Fixed `printTo(String)` which wrote numbers instead of strings (issue #120) * Fixed return type of `JsonArray::is<T>()` and some others (issue #121) v5.0.2 ------ * Fixed segmentation fault in `parseObject(String)` and `parseArray(String)`, when the `StaticJsonBuffer` is too small to hold a copy of the string * Fixed Clang warning "register specifier is deprecated" (issue #102) * Fixed GCC warning "declaration shadows a member" (issue #103) * Fixed memory alignment, which made ESP8266 crash (issue #104) * Fixed compilation on Visual Studio 2010 and 2012 (issue #107) v5.0.1 ------ * Fixed compilation with Arduino 1.0.6 (issue #99) v5.0.0 ------ * Added support of `String` class (issues #55, #56, #70, #77) * Added `JsonBuffer::strdup()` to make a copy of a string (issues #10, #57) * Implicitly call `strdup()` for `String` but not for `char*` (issues #84, #87) * Added support of non standard JSON input (issue #44) * Added support of comments in JSON input (issue #88) * Added implicit cast between numerical types (issues #64, #69, #93) * Added ability to read number values as string (issue #90) * Redesigned `JsonVariant` to leverage converting constructors instead of assignment operators (issue #66) * Switched to new the library layout (requires Arduino 1.0.6 or above) > ### BREAKING CHANGES :warning: > > - `JsonObject::add()` was renamed to `set()` > - `JsonArray::at()` and `JsonObject::at()` were renamed to `get()` > - Number of digits of floating point value are now set with `double_with_n_digits()` **Personal note about the `String` class**: Support of the `String` class has been added to the library because many people use it in their programs. However, you should not see this as an invitation to use the `String` class. The `String` class is **bad** because it uses dynamic memory allocation. Compared to static allocation, it compiles to a bigger, slower program, and is less predictable. You certainly don't want that in an embedded environment! v4.6 ---- * Fixed segmentation fault in `DynamicJsonBuffer` when memory allocation fails (issue #92) v4.5 ---- * Fixed buffer overflow when input contains a backslash followed by a terminator (issue #81) **Upgrading is recommended** since previous versions contain a potential security risk. Special thanks to [Giancarlo Canales Barreto](https://github.com/gcanalesb) for finding this nasty bug. v4.4 ---- * Added `JsonArray::measureLength()` and `JsonObject::measureLength()` (issue #75) v4.3 ---- * Added `JsonArray::removeAt()` to remove an element of an array (issue #58) * Fixed stack-overflow in `DynamicJsonBuffer` when parsing huge JSON files (issue #65) * Fixed wrong return value of `parseArray()` and `parseObject()` when allocation fails (issue #68) v4.2 ---- * Switched back to old library layout (issues #39, #43 and #45) * Removed global new operator overload (issue #40, #45 and #46) * Added an example with EthernetServer v4.1 ---- * Added DynamicJsonBuffer (issue #19) v4.0 ---- * Unified parser and generator API (issue #23) * Updated library layout, now requires Arduino 1.0.6 or newer > ### BREAKING CHANGES :warning: > > API changed significantly since v3, see [Migrating code to the new API](https://arduinojson.org/doc/migration/).
juehv/SmartHomeProject
ESP-SmartCardReader/libraries/ArduinoJson/CHANGELOG.md
Markdown
gpl-2.0
14,620
# # # Copyright (C) 2013 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Support classes and functions for testing the cmdlib module. """ from cmdlib.testsupport.cmdlib_testcase import CmdlibTestCase, \ withLockedLU from cmdlib.testsupport.config_mock import ConfigMock from cmdlib.testsupport.iallocator_mock import patchIAllocator from cmdlib.testsupport.livelock_mock import LiveLockMock from cmdlib.testsupport.utils_mock import patchUtils from cmdlib.testsupport.netutils_mock import patchNetutils, HostnameMock from cmdlib.testsupport.processor_mock import ProcessorMock from cmdlib.testsupport.rpc_runner_mock import CreateRpcRunnerMock, \ RpcResultsBuilder from cmdlib.testsupport.ssh_mock import patchSsh from cmdlib.testsupport.wconfd_mock import WConfdMock __all__ = ["CmdlibTestCase", "withLockedLU", "ConfigMock", "CreateRpcRunnerMock", "HostnameMock", "patchIAllocator", "patchUtils", "patchNetutils", "patchSsh", "ProcessorMock", "RpcResultsBuilder", "LiveLockMock", "WConfdMock", ]
ribag/ganeti-experiments
test/py/cmdlib/testsupport/__init__.py
Python
gpl-2.0
1,827
/* This source file is a part of the GePhex Project. Copyright (C) 2001-2004 Georg Seidel <georg@gephex.org> Martin Bayer <martin@gephex.org> Phillip Promesberger <coma@gephex.org> 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 "audiobuffer.h" #include <stdio.h> #include <assert.h> #include <windows.h> // --------------------------------------------------------------------------- static int init_buffer_block(HWAVEIN wavein, WAVEHDR* hdr, int block_size) { MMRESULT res; memset(hdr, 0, sizeof(*hdr)); hdr->lpData = malloc(block_size); hdr->dwBufferLength = block_size; hdr->dwFlags = 0; res = waveInPrepareHeader(wavein, hdr, sizeof(*hdr)); if (res != MMSYSERR_NOERROR) { char error_msg[128]; waveInGetErrorText(res, error_msg, sizeof(error_msg)); printf("init_buffer_block failed: %s!\n", error_msg); return 0; } return 1; } static int deinit_buffer_block(HWAVEIN wavein, WAVEHDR* hdr) { MMRESULT res; res = waveInUnprepareHeader(wavein, hdr, sizeof(*hdr)); if (res != MMSYSERR_NOERROR) { char error_msg[128]; waveInGetErrorText(res, error_msg, sizeof(error_msg)); printf("init_buffer_block failed: %s!\n", error_msg); return 0; } free(hdr->lpData); return 1; } // --------------------------------------------------------------------------- struct ab_queue_node { struct ab_queue_node* next; WAVEHDR hdr; }; struct ab_queue { int len; HWAVEIN wavein; struct ab_queue_node* first; }; static struct ab_queue* ab_queue_create(int len, int block_size, HWAVEIN wavein) { struct ab_queue* queue = malloc(sizeof(*queue)); struct ab_queue_node* last_node; struct ab_queue_node* current_node; int i; queue->len = len; queue->wavein = wavein; last_node = 0; for (i = 0; i < len; ++i) { MMRESULT res; current_node = malloc(sizeof(*current_node)); init_buffer_block(wavein, &current_node->hdr, block_size); res = waveInAddBuffer(wavein, &current_node->hdr, sizeof(current_node->hdr)); if (res != MMSYSERR_NOERROR) { char error_msg[128]; waveInGetErrorText(res, error_msg, sizeof(error_msg)); printf("waveInAddBuffer failed: %s!\n", error_msg); return 0; } if (last_node != 0) last_node->next = current_node; else { queue->first = current_node; } last_node = current_node; } last_node->next = queue->first; return queue; } static void ab_queue_destroy(struct ab_queue* queue) { int num_nodes = 0; struct ab_queue_node* current; current = queue->first; do { struct ab_queue_node* tmp; deinit_buffer_block(queue->wavein, &current->hdr); tmp = current; current = current->next; free(tmp); ++num_nodes; } while (current != queue->first); assert(num_nodes = queue->len); free(queue); } static WAVEHDR* ab_queue_top(struct ab_queue* self) { return &self->first->hdr; } static void ab_queue_next(struct ab_queue* self) { self->first = self->first->next; } // --------------------------------------------------------------------------- struct audio_buffer { int block_size; int num_blocks; HWAVEIN wavein; struct ab_queue* queue; }; struct audio_buffer* ab_create(void* wavein, int block_size, int num_blocks) { struct audio_buffer* buf = malloc(sizeof(*buf)); buf->block_size = block_size; buf->num_blocks = num_blocks; buf->wavein = wavein; buf->queue = ab_queue_create(num_blocks, block_size, wavein); return buf; } void ab_destroy(struct audio_buffer* buf) { ab_queue_destroy(buf->queue); free(buf); } int ab_block_ready(const struct audio_buffer* buf) { const WAVEHDR* hdr = ab_queue_top(buf->queue); return (hdr->dwFlags & WHDR_DONE); } int ab_get_block(struct audio_buffer* buf, unsigned char* data, int data_len) { WAVEHDR* hdr; MMRESULT res; int min_len; if (!ab_block_ready(buf)) return 0; hdr = ab_queue_top(buf->queue); min_len = min(data_len, (int)hdr->dwBytesRecorded); memcpy(data, hdr->lpData, min_len); //TODO: is it necessary to unprepare and prepare the header here? res = waveInAddBuffer(buf->wavein, hdr, sizeof(*hdr)); if (res != MMSYSERR_NOERROR) { char error_msg[128]; waveInGetErrorText(res, error_msg, sizeof(error_msg)); printf("waveInAddBuffer failed: %s!\n", error_msg); return 0; } ab_queue_next(buf->queue); return min_len; } // ---------------------------------------------------------------------------
ChristianFrisson/gephex
modules/src/audioinmodule/audiobuffer.c
C
gpl-2.0
4,990
using System; using System.Collections.Generic; namespace Trados.Transcreate.FileTypeSupport.XLIFF.Model { public class Source : Segment, ICloneable { public Source() { Elements = new List<Element>(); } public string Id { get; set; } public object Clone() { var source = new Source(); source.Id = Id; foreach (var element in Elements) { source.Elements.Add(element.Clone() as Element); } return source; } } }
sdl/Sdl-Community
SDLTranscreate/SDLTranscreate/FileTypeSupport/XLIFF/Model/Source.cs
C#
gpl-2.0
461
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "ObjectMgr.h" #include "WorldPacket.h" #include "ArenaTeam.h" #include "World.h" #include "Group.h" #include "ArenaTeamMgr.h" ArenaTeam::ArenaTeam() { TeamId = 0; Type = 0; TeamName = ""; CaptainGuid = 0; BackgroundColor = 0; EmblemStyle = 0; EmblemColor = 0; BorderStyle = 0; BorderColor = 0; Stats.WeekGames = 0; Stats.SeasonGames = 0; Stats.Rank = 0; Stats.Rating = sWorld->getIntConfig(CONFIG_ARENA_START_RATING); Stats.WeekWins = 0; Stats.SeasonWins = 0; } ArenaTeam::~ArenaTeam() {} bool ArenaTeam::Create(uint32 captainGuid, uint8 type, std::string teamName, uint32 backgroundColor, uint8 emblemStyle, uint32 emblemColor, uint8 borderStyle, uint32 borderColor) { // Check if captain is present if (!sObjectMgr->GetPlayer(captainGuid)) return false; // Check if arena team name is already taken if (sArenaTeamMgr->GetArenaTeamByName(TeamName)) return false; // Generate new arena team id TeamId = sArenaTeamMgr->GenerateArenaTeamId(); // Assign member variables CaptainGuid = captainGuid; Type = type; TeamName = teamName; BackgroundColor = backgroundColor; EmblemStyle = emblemStyle; EmblemColor = emblemColor; BorderStyle = borderStyle; BorderColor = borderColor; // Save arena team to db PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_ARENA_TEAM); stmt->setUInt32(0, TeamId); stmt->setString(1, TeamName); stmt->setUInt32(2, GUID_LOPART(CaptainGuid)); stmt->setUInt8(3, Type); stmt->setUInt16(4, Stats.Rating); stmt->setUInt32(5, BackgroundColor); stmt->setUInt8(6, EmblemStyle); stmt->setUInt32(7, EmblemColor); stmt->setUInt8(8, BorderStyle); stmt->setUInt32(9, BorderColor); CharacterDatabase.Execute(stmt); // Add captain as member AddMember(CaptainGuid); sLog->outArena("New ArenaTeam created [Id: %u] [Type: %u] [Captain low GUID: %u]", GetId(), GetType(), GUID_LOPART(CaptainGuid)); return true; } bool ArenaTeam::AddMember(const uint64& playerGuid) { std::string playerName; uint8 playerClass; // Check if arena team is full (Can't have more than type * 2 players) if (GetMembersSize() >= GetType() * 2) return false; // Get player name and class either from db or ObjectMgr Player* player = sObjectMgr->GetPlayer(playerGuid); if (player) { playerClass = player->getClass(); playerName = player->GetName(); } else { // 0 1 // SELECT name, class FROM characters WHERE guid = ? PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_PLAYER_NAME_CLASS); stmt->setUInt32(0, GUID_LOPART(playerGuid)); PreparedQueryResult result = CharacterDatabase.Query(stmt); if (!result) return false; playerName = (*result)[0].GetString(); playerClass = (*result)[1].GetUInt8(); } // Check if player is already in a similar arena team if ((player && player->GetArenaTeamId(GetSlot())) || Player::GetArenaTeamIdFromDB(playerGuid, GetType()) != 0) { sLog->outError("Arena: Player %s (guid: %u) already has an arena team of type %u", playerName.c_str(), GUID_LOPART(playerGuid), GetType()); return false; } // Set player's personal rating uint32 personalRating = 0; if (sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING) > 0) personalRating = sWorld->getIntConfig(CONFIG_ARENA_START_PERSONAL_RATING); else if (GetRating() >= 1000) personalRating = 1000; // Try to get player's match maker rating from db and fall back to config setting if not found PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_MATCH_MAKER_RATING); stmt->setUInt32(0, GUID_LOPART(playerGuid)); stmt->setUInt8(1, GetSlot()); PreparedQueryResult result = CharacterDatabase.Query(stmt); uint32 matchMakerRating; if (result) matchMakerRating = (*result)[0].GetUInt32(); else matchMakerRating = sWorld->getIntConfig(CONFIG_ARENA_START_MATCHMAKER_RATING); // Remove all player signatures from other petitions // This will prevent player from joining too many arena teams and corrupt arena team data integrity Player::RemovePetitionsAndSigns(playerGuid, GetType()); // Feed data to the struct ArenaTeamMember newmember; newmember.Name = playerName; newmember.Guid = playerGuid; newmember.Class = playerClass; newmember.SeasonGames = 0; newmember.WeekGames = 0; newmember.SeasonWins = 0; newmember.WeekWins = 0; newmember.PersonalRating = personalRating; newmember.MatchMakerRating = matchMakerRating; Members.push_back(newmember); // Save player's arena team membership to db stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_ARENA_TEAM_MEMBER); stmt->setUInt32(0, TeamId); stmt->setUInt32(1, GUID_LOPART(playerGuid)); CharacterDatabase.Execute(stmt); // Inform player if online if (player) { player->SetInArenaTeam(TeamId, GetSlot(), GetType()); player->SetArenaTeamIdInvited(0); // Hide promote/remove buttons if (CaptainGuid != playerGuid) player->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1); } sLog->outArena("Player: %s [GUID: %u] joined arena team type: %u [Id: %u].", playerName.c_str(), GUID_LOPART(playerGuid), GetType(), GetId()); return true; } bool ArenaTeam::LoadArenaTeamFromDB(QueryResult result) { if (!result) return false; Field *fields = result->Fetch(); TeamId = fields[0].GetUInt32(); TeamName = fields[1].GetString(); CaptainGuid = MAKE_NEW_GUID(fields[2].GetUInt32(), 0, HIGHGUID_PLAYER); Type = fields[3].GetUInt8(); BackgroundColor = fields[4].GetUInt32(); EmblemStyle = fields[5].GetUInt8(); EmblemColor = fields[6].GetUInt32(); BorderStyle = fields[7].GetUInt8(); BorderColor = fields[8].GetUInt32(); Stats.Rating = fields[9].GetUInt16(); Stats.WeekGames = fields[10].GetUInt16(); Stats.WeekWins = fields[11].GetUInt16(); Stats.SeasonGames = fields[12].GetUInt16(); Stats.SeasonWins = fields[13].GetUInt16(); Stats.Rank = fields[14].GetUInt32(); return true; } bool ArenaTeam::LoadMembersFromDB(QueryResult result) { if (!result) return false; bool captainPresentInTeam = false; do { Field *fields = result->Fetch(); // Prevent crash if db records are broken when all members in result are already processed and current team doesn't have any members if (!fields) break; uint32 arenaTeamId = fields[0].GetUInt32(); // We loaded all members for this arena_team already, break cycle if (arenaTeamId > TeamId) break; ArenaTeamMember newMember; newMember.Guid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_PLAYER); newMember.WeekGames = fields[2].GetUInt16(); newMember.WeekWins = fields[3].GetUInt16(); newMember.SeasonGames = fields[4].GetUInt16(); newMember.SeasonWins = fields[5].GetUInt16(); newMember.Name = fields[6].GetString(); newMember.Class = fields[7].GetUInt8(); newMember.PersonalRating = fields[8].GetUInt16(); newMember.MatchMakerRating = fields[9].GetUInt16() > 0 ? fields[9].GetUInt16() : 1500; // Delete member if character information is missing if (newMember.Name.empty()) { sLog->outErrorDb("ArenaTeam %u has member with empty name - probably player %u doesn't exist, deleting him from memberlist!", arenaTeamId, GUID_LOPART(newMember.Guid)); this->DelMember(newMember.Guid, true); continue; } // Check if team team has a valid captain if (newMember.Guid == GetCaptain()) captainPresentInTeam = true; // Put the player in the team Members.push_back(newMember); } while (result->NextRow()); if (Empty() || !captainPresentInTeam) { // Arena team is empty or captain is not in team, delete from db sLog->outErrorDb("ArenaTeam %u does not have any members or its captain is not in team, disbanding it...", TeamId); return false; } return true; } void ArenaTeam::SetCaptain(const uint64& guid) { // Disable remove/promote buttons Player* oldCaptain = sObjectMgr->GetPlayer(GetCaptain()); if (oldCaptain) oldCaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 1); // Set new captain CaptainGuid = guid; // Update database PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_CAPTAIN); stmt->setUInt32(0, GUID_LOPART(guid)); stmt->setUInt32(1, GetId()); CharacterDatabase.Execute(stmt); // Enable remove/promote buttons Player *newCaptain = sObjectMgr->GetPlayer(guid); if (newCaptain) { newCaptain->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_MEMBER, 0); sLog->outArena("Player: %s [GUID: %u] promoted player: %s [GUID: %u] to leader of arena team [Id: %u] [Type: %u].", oldCaptain->GetName(), oldCaptain->GetGUIDLow(), newCaptain->GetName(), newCaptain->GetGUIDLow(), GetId(), GetType()); } } void ArenaTeam::DelMember(uint64 guid, bool cleanDb) { // Remove member from team for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) if (itr->Guid == guid) { Members.erase(itr); break; } // Inform player and remove arena team info from player data if (Player* player = sObjectMgr->GetPlayer(guid)) { player->GetSession()->SendArenaTeamCommandResult(ERR_ARENA_TEAM_QUIT_S, GetName(), "", 0); // delete all info regarding this team for (uint32 i = 0; i < ARENA_TEAM_END; ++i) player->SetArenaTeamInfoField(GetSlot(), ArenaTeamInfoType(i), 0); sLog->outArena("Player: %s [GUID: %u] left arena team type: %u [Id: %u].", player->GetName(), player->GetGUIDLow(), GetType(), GetId()); } // Only used for single member deletion, for arena team disband we use a single query for more efficiency if (cleanDb) { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBER); stmt->setUInt32(0, GetId()); stmt->setUInt32(1, GUID_LOPART(guid)); CharacterDatabase.Execute(stmt); } } void ArenaTeam::Disband(WorldSession* session) { // Remove all members from arena team while (!Members.empty()) DelMember(Members.front().Guid, false); // Broadcast update if (session) { BroadcastEvent(ERR_ARENA_TEAM_DISBANDED_S, 0, 2, session->GetPlayerName(), GetName(), ""); if (Player* player = session->GetPlayer()) sLog->outArena("Player: %s [GUID: %u] disbanded arena team type: %u [Id: %u].", player->GetName(), player->GetGUIDLow(), GetType(), GetId()); } // Update database SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM); stmt->setUInt32(0, TeamId); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ARENA_TEAM_MEMBERS); stmt->setUInt32(0, TeamId); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); // Remove arena team from ObjectMgr sArenaTeamMgr->RemoveArenaTeam(TeamId); } void ArenaTeam::Roster(WorldSession* session) { Player* pl = NULL; uint8 unk308 = 0; WorldPacket data(SMSG_ARENA_TEAM_ROSTER, 100); data << uint32(GetId()); // team id data << uint8(unk308); // 308 unknown value but affect packet structure data << uint32(GetMembersSize()); // members count data << uint32(GetType()); // arena team type? for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) { pl = sObjectMgr->GetPlayer(itr->Guid); data << uint64(itr->Guid); // guid data << uint8((pl ? 1 : 0)); // online flag data << itr->Name; // member name data << uint32((itr->Guid == GetCaptain() ? 0 : 1));// captain flag 0 captain 1 member data << uint8((pl ? pl->getLevel() : 0)); // unknown, level? data << uint8(itr->Class); // class data << uint32(itr->WeekGames); // played this week data << uint32(itr->WeekWins); // wins this week data << uint32(itr->SeasonGames); // played this season data << uint32(itr->SeasonWins); // wins this season data << uint32(itr->PersonalRating); // personal rating if (unk308) { data << float(0.0); // 308 unk data << float(0.0); // 308 unk } } session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_ROSTER"); } void ArenaTeam::Query(WorldSession* session) { WorldPacket data(SMSG_ARENA_TEAM_QUERY_RESPONSE, 4*7+GetName().size()+1); data << uint32(GetId()); // team id data << GetName(); // team name data << uint32(GetType()); // arena team type (2=2x2, 3=3x3 or 5=5x5) data << uint32(BackgroundColor); // background color data << uint32(EmblemStyle); // emblem style data << uint32(EmblemColor); // emblem color data << uint32(BorderStyle); // border style data << uint32(BorderColor); // border color session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_QUERY_RESPONSE"); } void ArenaTeam::SendStats(WorldSession* session) { WorldPacket data(SMSG_ARENA_TEAM_STATS, 4*7); data << uint32(GetId()); // team id data << uint32(Stats.Rating); // rating data << uint32(Stats.WeekGames); // games this week data << uint32(Stats.WeekWins); // wins this week data << uint32(Stats.SeasonGames); // played this season data << uint32(Stats.SeasonWins); // wins this season data << uint32(Stats.Rank); // rank session->SendPacket(&data); } void ArenaTeam::NotifyStatsChanged() { // This is called after a rated match ended // Updates arena team stats for every member of the team (not only the ones who participated!) for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) { Player* plr = sObjectMgr->GetPlayer(itr->Guid); if (plr) SendStats(plr->GetSession()); } } void ArenaTeam::Inspect(WorldSession* session, uint64 guid) { ArenaTeamMember* member = GetMember(guid); if (!member) return; WorldPacket data(MSG_INSPECT_ARENA_TEAMS, 8+1+4*6); data << uint64(guid); // player guid data << uint8(GetSlot()); // slot (0...2) data << uint32(GetId()); // arena team id data << uint32(Stats.Rating); // rating data << uint32(Stats.SeasonGames); // season played data << uint32(Stats.SeasonWins); // season wins data << uint32(member->SeasonGames); // played (count of all games, that the inspected member participated...) data << uint32(member->PersonalRating); // personal rating session->SendPacket(&data); } void ArenaTeamMember::ModifyPersonalRating(Player* plr, int32 mod, uint32 slot) { if (int32(PersonalRating) + mod < 0) PersonalRating = 0; else PersonalRating += mod; if (plr) { plr->SetArenaTeamInfoField(slot, ARENA_TEAM_PERSONAL_RATING, PersonalRating); plr->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING, PersonalRating, slot); } } void ArenaTeamMember::ModifyMatchmakerRating(int32 mod, uint32 /*slot*/) { if (int32(MatchMakerRating) + mod < 0) MatchMakerRating = 0; else MatchMakerRating += mod; } void ArenaTeam::BroadcastPacket(WorldPacket* packet) { for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) { Player* player = sObjectMgr->GetPlayer(itr->Guid); if (player) player->GetSession()->SendPacket(packet); } } void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, uint64 guid, uint8 strCount, std::string str1, std::string str2, std::string str3) { WorldPacket data(SMSG_ARENA_TEAM_EVENT, 1+1+1); data << uint8(event); data << uint8(strCount); switch (strCount) { case 0: break; case 1: data << str1; break; case 2: data << str1 << str2; break; case 3: data << str1 << str2 << str3; break; default: sLog->outError("Unhandled strCount %u in ArenaTeam::BroadcastEvent", strCount); return; } if (guid) data << uint64(guid); BroadcastPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_ARENA_TEAM_EVENT"); } uint8 ArenaTeam::GetSlotByType(uint32 type) { switch(type) { case ARENA_TEAM_2v2: return 0; case ARENA_TEAM_3v3: return 1; case ARENA_TEAM_5v5: return 2; default: break; } sLog->outError("FATAL: Unknown arena team type %u for some arena team", type); return 0xFF; } bool ArenaTeam::IsMember(const uint64& guid) const { for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) if (itr->Guid == guid) return true; return false; } uint32 ArenaTeam::GetPoints(uint32 memberRating) { // Returns how many points would be awarded with this team type with this rating float points; uint32 rating = memberRating + 150 < Stats.Rating ? memberRating : Stats.Rating; if (rating <= 1500) { if (sWorld->getIntConfig(CONFIG_ARENA_SEASON_ID) < 6) points = (float)rating * 0.22f + 14.0f; else points = 344; } else points = 1511.26f / (1.0f + 1639.28f * exp(-0.00412f * (float)rating)); // Type penalties for teams < 5v5 if (Type == ARENA_TEAM_2v2) points *= 0.76f; else if (Type == ARENA_TEAM_3v3) points *= 0.88f; return (uint32) points; } uint32 ArenaTeam::GetAverageMMR(Group* group) const { if (!group) return 0; return Stats.Rating; } float ArenaTeam::GetChanceAgainst(uint32 ownRating, uint32 opponentRating) { // Returns the chance to win against a team with the given rating, used in the rating adjustment calculation // ELO system return 1.0f / (1.0f + exp(log(10.0f) * (float)((float)opponentRating - (float)ownRating) / 400.0f)); } int32 ArenaTeam::GetMatchmakerRatingMod(uint32 ownRating, uint32 opponentRating, bool won /*, float& confidence_factor*/) { // 'Chance' calculation - to beat the opponent // This is a simulation. Not much info on how it really works float chance = GetChanceAgainst(ownRating, opponentRating); float won_mod = (won) ? 1.0f : 0.0f; float mod = won_mod - chance; // Work in progress: /* // This is a simulation, as there is not much info on how it really works float confidence_mod = min(1.0f - fabs(mod), 0.5f); // Apply confidence factor to the mod: mod *= confidence_factor // And only after that update the new confidence factor confidence_factor -= ((confidence_factor - 1.0f) * confidence_mod) / confidence_factor; */ // Real rating modification mod *= 24.0f; return (int32)ceil(mod); } int32 ArenaTeam::GetRatingMod(uint32 ownRating, uint32 opponentRating, bool won /*, float confidence_factor*/) { // 'Chance' calculation - to beat the opponent // This is a simulation. Not much info on how it really works float chance = GetChanceAgainst(ownRating, opponentRating); float won_mod = (won) ? 1.0f : 0.0f; // Calculate the rating modification float mod; // TODO: Replace this hack with using the confidence factor (limiting the factor to 2.0f) if (won && ownRating < 1300) { if (ownRating < 1000) mod = 48.0f * (won_mod - chance); else mod = (24.0f + (24.0f * (1300.0f - float(ownRating)) / 300.0f)) * (won_mod - chance); } else mod = 24.0f * (won_mod - chance); return (int32)ceil(mod); } void ArenaTeam::FinishGame(int32 mod) { // Rating can only drop to 0 if (int32(Stats.Rating) + mod < 0) Stats.Rating = 0; else { Stats.Rating += mod; // Check if rating related achivements are met for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) if (Player* member = ObjectAccessor::FindPlayer(itr->Guid)) member->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING, Stats.Rating, Type); } // Update number of games played per season or week Stats.WeekGames += 1; Stats.SeasonGames += 1; // Update team's rank, start with rank 1 and increase until no team with more rating was found Stats.Rank = 1; ArenaTeamMgr::ArenaTeamContainer::const_iterator i = sArenaTeamMgr->GetArenaTeamMapBegin(); for (; i != sArenaTeamMgr->GetArenaTeamMapEnd(); ++i) { if (i->second->GetType() == Type && i->second->GetStats().Rating > Stats.Rating) ++Stats.Rank; } } int32 ArenaTeam::WonAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change) { // Called when the team has won // Change in Matchmaker rating int32 mod = GetMatchmakerRatingMod(Own_MMRating, Opponent_MMRating, true); // Change in Team Rating rating_change = GetRatingMod(Stats.Rating, Opponent_MMRating, true); // Modify the team stats accordingly FinishGame(rating_change); // Update number of wins per season and week Stats.WeekWins += 1; Stats.SeasonWins += 1; // Return the rating change, used to display it on the results screen return mod; } int32 ArenaTeam::LostAgainst(uint32 Own_MMRating, uint32 Opponent_MMRating, int32& rating_change) { // Called when the team has lost // Change in Matchmaker Rating int32 mod = GetMatchmakerRatingMod(Own_MMRating, Opponent_MMRating, false); // Change in Team Rating rating_change = GetRatingMod(Stats.Rating, Opponent_MMRating, false); // Modify the team stats accordingly FinishGame(rating_change); // return the rating change, used to display it on the results screen return mod; } void ArenaTeam::MemberLost(Player* plr, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange) { // Called for each participant of a match after losing for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) { if (itr->Guid == plr->GetGUID()) { // Update personal rating int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false); itr->ModifyPersonalRating(plr, mod, GetSlot()); // Update matchmaker rating itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); // Update personal played stats itr->WeekGames +=1; itr->SeasonGames +=1; // update the unit fields plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->WeekGames); plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->SeasonGames); return; } } } void ArenaTeam::OfflineMemberLost(uint64 guid, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange) { // Called for offline player after ending rated arena match! for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) { if (itr->Guid == guid) { // update personal rating int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false); itr->ModifyPersonalRating(NULL, mod, GetSlot()); // update matchmaker rating itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); // update personal played stats itr->WeekGames += 1; itr->SeasonGames += 1; return; } } } void ArenaTeam::MemberWon(Player* plr, uint32 againstMatchmakerRating, int32 MatchmakerRatingChange) { // called for each participant after winning a match for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) { if (itr->Guid == plr->GetGUID()) { // update personal rating int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, true); itr->ModifyPersonalRating(plr, mod, GetSlot()); // update matchmaker rating itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); // update personal stats itr->WeekGames +=1; itr->SeasonGames +=1; itr->SeasonWins += 1; itr->WeekWins += 1; // update unit fields plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_WEEK, itr->WeekGames); plr->SetArenaTeamInfoField(GetSlot(), ARENA_TEAM_GAMES_SEASON, itr->SeasonGames); return; } } } void ArenaTeam::UpdateArenaPointsHelper(std::map<uint32, uint32>& playerPoints) { // Called after a match has ended and the stats are already modified // Helper function for arena point distribution (this way, when distributing, no actual calculation is required, just a few comparisons) // 10 played games per week is a minimum if (Stats.WeekGames < 10) return; // To get points, a player has to participate in at least 30% of the matches uint32 requiredGames = (uint32) ceil(Stats.WeekGames * 0.3); for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) { // The player participated in enough games, update his points uint32 pointsToAdd = 0; if (itr->WeekGames >= requiredGames) pointsToAdd = GetPoints(itr->PersonalRating); std::map<uint32, uint32>::iterator plr_itr = playerPoints.find(GUID_LOPART(itr->Guid)); if (plr_itr != playerPoints.end()) { // Check if there is already more points if (plr_itr->second < pointsToAdd) playerPoints[GUID_LOPART(itr->Guid)] = pointsToAdd; } else playerPoints[GUID_LOPART(itr->Guid)] = pointsToAdd; } } void ArenaTeam::SaveToDB() { // Save team and member stats to db // Called after a match has ended or when calculating arena_points SQLTransaction trans = CharacterDatabase.BeginTransaction(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_STATS); stmt->setUInt16(0, Stats.Rating); stmt->setUInt16(1, Stats.WeekGames); stmt->setUInt16(2, Stats.WeekWins); stmt->setUInt16(3, Stats.SeasonGames); stmt->setUInt16(4, Stats.SeasonWins); stmt->setUInt32(5, Stats.Rank); stmt->setUInt32(6, GetId()); trans->Append(stmt); for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_ARENA_TEAM_MEMBER); stmt->setUInt16(0, itr->PersonalRating); stmt->setUInt16(1, itr->WeekGames); stmt->setUInt16(2, itr->WeekWins); stmt->setUInt16(3, itr->SeasonGames); stmt->setUInt16(4, itr->SeasonWins); stmt->setUInt32(5, GetId()); stmt->setUInt32(6, GUID_LOPART(itr->Guid)); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_CHARACTER_ARENA_STATS); stmt->setUInt32(0, GUID_LOPART(itr->Guid)); stmt->setUInt8(1, GetSlot()); stmt->setUInt16(2, itr->MatchMakerRating); trans->Append(stmt); } CharacterDatabase.CommitTransaction(trans); } void ArenaTeam::FinishWeek() { // Reset team stats Stats.WeekGames = 0; Stats.WeekWins = 0; // Reset member stats for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) { itr->WeekGames = 0; itr->WeekWins = 0; } } bool ArenaTeam::IsFighting() const { for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) if (Player* player = sObjectMgr->GetPlayer(itr->Guid)) if (player->GetMap()->IsBattleArena()) return true; return false; } ArenaTeamMember* ArenaTeam::GetMember(const std::string& name) { for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) if (itr->Name == name) return &(*itr); return NULL; } ArenaTeamMember* ArenaTeam::GetMember(const uint64& guid) { for (MemberList::iterator itr = Members.begin(); itr != Members.end(); ++itr) if (itr->Guid == guid) return &(*itr); return NULL; }
SeTM/MythCore
src/server/game/Battlegrounds/ArenaTeam.cpp
C++
gpl-2.0
31,107
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: trial_of_the_crusader SD%Complete: ??% SDComment: based on /dev/rsa SDCategory: Crusader Coliseum EndScriptData */ // Known bugs: // - They should be floating but they aren't respecting the floor =( // - Hardcoded bullets spawner #include "ScriptPCH.h" #include "trial_of_the_crusader.h" enum Yells { SAY_AGGRO = -1649040, SAY_DEATH = -1649041, SAY_BERSERK = -1649042, EMOTE_SHIELD = -1649043, SAY_SHIELD = -1649044, SAY_KILL1 = -1649045, SAY_KILL2 = -1649046, EMOTE_LIGHT_VORTEX = -1649047, SAY_LIGHT_VORTEX = -1649048, EMOTE_DARK_VORTEX = -1649049, SAY_DARK_VORTEX = -1649050, }; enum Equipment { EQUIP_MAIN_1 = 9423, EQUIP_MAIN_2 = 37377, }; enum Summons { NPC_UNLEASHED_DARK = 34628, NPC_UNLEASHED_LIGHT = 34630, // Future Development NPC_BULLET_CONTROLLER = 34743, // Npc controller for all bullets NPC_BULLET_STALKER_DARK = 34704, // Npc spawner for dark bullets NPC_BULLET_STALKER_LIGHT = 34720, // Npc spawner for light bullets }; enum BossSpells { SPELL_CONTROLLER_PERIODIC = 66149, // Future Development SPELL_LIGHT_TWIN_SPIKE = 66075, SPELL_LIGHT_SURGE = 65766, SPELL_LIGHT_SHIELD = 65858, SPELL_LIGHT_TWIN_PACT = 65876, SPELL_LIGHT_VORTEX = 66046, SPELL_LIGHT_TOUCH = 67297, SPELL_DARK_TWIN_SPIKE = 66069, SPELL_DARK_SURGE = 65768, SPELL_DARK_SHIELD = 65874, SPELL_DARK_TWIN_PACT = 65875, SPELL_POWER_TWINS = 65879, SPELL_DARK_VORTEX = 66058, SPELL_DARK_TOUCH = 67282, SPELL_TWIN_POWER = 65916, SPELL_LIGHT_ESSENCE = 65686, SPELL_DARK_ESSENCE = 65684, SPELL_BERSERK = 64238, SPELL_NONE = 0, SPELL_EMPOWERED_DARK = 65724, SPELL_EMPOWERED_LIGHT = 65748, SPELL_UNLEASHED_DARK = 65808, SPELL_UNLEASHED_LIGHT = 65795, SPELL_TWIN_EMPATHY_1 = 66132, SPELL_TWIN_EMPATHY_2 = 66133, SPELL_POWERING_UP = 67590, SPELL_SURGE_OF_SPEED = 65828, }; #define SPELL_DARK_ESSENCE_HELPER RAID_MODE<uint32>(65684, 67176, 67177, 67178) #define SPELL_LIGHT_ESSENCE_HELPER RAID_MODE<uint32>(65686, 67222, 67223, 67224) #define SPELL_POWERING_UP_HELPER RAID_MODE(67590, 67602, 67603, 67604) #define SPELL_EMPOWERED_DARK_HELPER RAID_MODE<uint32>(65724,67213,67214,67215) #define SPELL_EMPOWERED_LIGHT_HELPER RAID_MODE<uint32>(65748, 67216, 67217, 67218) enum Actions { ACTION_VORTEX, ACTION_PACT }; /*###### ## boss_twin_base ######*/ struct boss_twin_baseAI : public ScriptedAI { boss_twin_baseAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; SummonList Summons; AuraStateType m_uiAuraState; uint8 m_uiStage; bool m_bIsBerserk; uint8 m_uiWaveCount; uint32 m_uiWeapon; uint32 m_uiColorballsTimer; uint32 m_uiSpecialAbilityTimer; uint32 m_uiSpikeTimer; uint32 m_uiTouchTimer; uint32 m_uiBerserkTimer; int32 m_uiVortexSay; int32 m_uiVortexEmote; uint32 m_uiSisterNpcId; uint32 m_uiColorballNpcId; uint32 m_uiMyEmphatySpellId; uint32 m_uiEssenceNpcId; uint32 m_uiMyEssenceSpellId; uint32 m_uiOtherEssenceSpellId; uint32 m_uiEmpoweredWeaknessSpellId; uint32 m_uiSurgeSpellId; uint32 m_uiVortexSpellId; uint32 m_uiShieldSpellId; uint32 m_uiTwinPactSpellId; uint32 m_uiSpikeSpellId; uint32 m_uiTouchSpellId; Position HomeLocation; Position EssenceLocation[2]; void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->ModifyAuraState(m_uiAuraState, true); /* Uncomment this once that they are flying above the ground me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->SetFlying(true); */ m_bIsBerserk = false; m_uiWaveCount = 1; m_uiColorballsTimer = 15*IN_MILLISECONDS; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; m_uiSpikeTimer = 20*IN_MILLISECONDS; m_uiTouchTimer = urand(10, 15)*IN_MILLISECONDS; m_uiBerserkTimer = IsHeroic() ? 6*MINUTE*IN_MILLISECONDS : 10*MINUTE*IN_MILLISECONDS; Summons.DespawnAll(); } void JustReachedHome() { if (m_pInstance) { m_pInstance->SetData(TYPE_VALKIRIES, FAIL); } me->DespawnOrUnsummon(); } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 0: me->GetMotionMaster()->MovePoint(1, HomeLocation.GetPositionX(), HomeLocation.GetPositionY(), HomeLocation.GetPositionZ()); me->SetHomePosition(HomeLocation); break; case 1: me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_AGGRESSIVE); break; } } void KilledUnit(Unit* who) { if (who->GetTypeId() == TYPEID_PLAYER) { DoScriptText(urand(0, 1) ? SAY_KILL1 : SAY_KILL2, me); if (m_pInstance) m_pInstance->SetData(DATA_TRIBUTE_TO_IMMORTALITY_ELEGIBLE, 0); } } void JustSummoned(Creature* summoned) { switch (summoned->GetEntry()) { case NPC_UNLEASHED_DARK: case NPC_UNLEASHED_LIGHT: summoned->SetCorpseDelay(0); break; } Summons.Summon(summoned); } void SummonedCreatureDespawn(Creature* summoned) { switch (summoned->GetEntry()) { case NPC_LIGHT_ESSENCE: m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_LIGHT_ESSENCE_HELPER); m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_POWERING_UP_HELPER); break; case NPC_DARK_ESSENCE: m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_DARK_ESSENCE_HELPER); m_pInstance->DoRemoveAurasDueToSpellOnPlayers(SPELL_POWERING_UP_HELPER); break; } Summons.Despawn(summoned); } void SummonColorballs(uint8 quantity) { float x0 = ToCCommonLoc[1].GetPositionX(), y0 = ToCCommonLoc[1].GetPositionY(), r = 47.0f; float y = y0; for (uint8 i = 0; i < quantity; i++) { float x = float(urand(uint32(x0 - r), uint32(x0 + r))); if (urand(0, 1)) y = y0 + sqrt(pow(r, 2) - pow((x-x0), 2)); else y = y0 - sqrt(pow(r, 2) - pow((x-x0), 2)); me->SummonCreature(m_uiColorballNpcId, x, y, me->GetPositionZ(), TEMPSUMMON_CORPSE_DESPAWN); } } void JustDied(Unit* /*killer*/) { DoScriptText(SAY_DEATH, me); if (m_pInstance) { if (Creature* pSister = GetSister()) { if (!pSister->isAlive()) { m_pInstance->SetData(TYPE_VALKIRIES, DONE); Summons.DespawnAll(); } else m_pInstance->SetData(TYPE_VALKIRIES, SPECIAL); } } Summons.DespawnAll(); } // Called when sister pointer needed Creature* GetSister() { return Unit::GetCreature((*me), m_pInstance->GetData64(m_uiSisterNpcId)); } void EnterCombat(Unit* /*who*/) { me->SetInCombatWithZone(); if (m_pInstance) { if (Creature* pSister = GetSister()) me->AddAura(m_uiMyEmphatySpellId, pSister); m_pInstance->SetData(TYPE_VALKIRIES, IN_PROGRESS); } if (me->isAlive()) { me->SummonCreature(m_uiEssenceNpcId, EssenceLocation[0].GetPositionX(), EssenceLocation[0].GetPositionY(), EssenceLocation[0].GetPositionZ()); me->SummonCreature(m_uiEssenceNpcId, EssenceLocation[1].GetPositionX(), EssenceLocation[1].GetPositionY(), EssenceLocation[1].GetPositionZ()); } DoScriptText(SAY_AGGRO, me); DoCast(me, m_uiSurgeSpellId); } void DoAction(const int32 action) { switch (action) { case ACTION_VORTEX: m_uiStage = me->GetEntry() == NPC_LIGHTBANE ? 2 : 1; break; case ACTION_PACT: m_uiStage = me->GetEntry() == NPC_LIGHTBANE ? 1 : 2; DoCast(me, SPELL_TWIN_POWER); break; } } void EnableDualWield(bool mode) { SetEquipmentSlots(false, m_uiWeapon, mode ? m_uiWeapon : EQUIP_UNEQUIP, EQUIP_UNEQUIP); me->SetCanDualWield(mode); me->UpdateDamagePhysical(mode ? OFF_ATTACK : BASE_ATTACK); } void UpdateAI(const uint32 uiDiff) { if (!m_pInstance || !UpdateVictim()) return; switch (m_uiStage) { case 0: break; case 1: // Vortex if (m_uiSpecialAbilityTimer <= uiDiff) { if (Creature* pSister = GetSister()) pSister->AI()->DoAction(ACTION_VORTEX); DoScriptText(m_uiVortexEmote, me); DoScriptText(m_uiVortexSay, me); DoCastAOE(m_uiVortexSpellId); m_uiStage = 0; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; } else m_uiSpecialAbilityTimer -= uiDiff; break; case 2: // Shield+Pact if (m_uiSpecialAbilityTimer <= uiDiff) { DoScriptText(EMOTE_SHIELD, me); DoScriptText(SAY_SHIELD, me); if (Creature* pSister = GetSister()) { pSister->AI()->DoAction(ACTION_PACT); pSister->CastSpell(pSister, SPELL_POWER_TWINS, false); } DoCast(me, m_uiShieldSpellId); DoCast(me, m_uiTwinPactSpellId); m_uiStage = 0; m_uiSpecialAbilityTimer = MINUTE*IN_MILLISECONDS; } else m_uiSpecialAbilityTimer -= uiDiff; break; default: break; } if (m_uiSpikeTimer <= uiDiff) { DoCastVictim(m_uiSpikeSpellId); m_uiSpikeTimer = 20*IN_MILLISECONDS; } else m_uiSpikeTimer -= uiDiff; if (IsHeroic() && m_uiTouchTimer <= uiDiff) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 200, true, m_uiOtherEssenceSpellId)) me->CastCustomSpell(m_uiTouchSpellId, SPELLVALUE_MAX_TARGETS, 1, target, false); m_uiTouchTimer = urand(10, 15)*IN_MILLISECONDS; } else m_uiTouchTimer -= uiDiff; if (m_uiColorballsTimer <= uiDiff) { if (m_uiWaveCount >= 2) { SummonColorballs(12); m_uiWaveCount = 0; } else { SummonColorballs(2); m_uiWaveCount++; } m_uiColorballsTimer = 15*IN_MILLISECONDS; } else m_uiColorballsTimer -= uiDiff; if (!m_bIsBerserk && m_uiBerserkTimer <= uiDiff) { DoCast(me, SPELL_BERSERK); DoScriptText(SAY_BERSERK, me); m_bIsBerserk = true; } else m_uiBerserkTimer -= uiDiff; DoMeleeAttackIfReady(); } }; /*###### ## boss_fjola ######*/ class boss_fjola : public CreatureScript { public: boss_fjola() : CreatureScript("boss_fjola") { } CreatureAI* GetAI(Creature* creature) const { return new boss_fjolaAI(creature); } struct boss_fjolaAI : public boss_twin_baseAI { boss_fjolaAI(Creature* creature) : boss_twin_baseAI(creature) {} void Reset() { boss_twin_baseAI::Reset(); SetEquipmentSlots(false, EQUIP_MAIN_1, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); m_uiStage = 0; m_uiWeapon = EQUIP_MAIN_1; m_uiAuraState = AURA_STATE_UNKNOWN22; m_uiVortexEmote = EMOTE_LIGHT_VORTEX; m_uiVortexSay = SAY_LIGHT_VORTEX; m_uiSisterNpcId = NPC_DARKBANE; m_uiColorballNpcId = NPC_UNLEASHED_LIGHT; m_uiEssenceNpcId = NPC_LIGHT_ESSENCE; m_uiMyEmphatySpellId = SPELL_TWIN_EMPATHY_1; m_uiMyEssenceSpellId = SPELL_LIGHT_ESSENCE_HELPER; m_uiOtherEssenceSpellId = SPELL_DARK_ESSENCE_HELPER; m_uiEmpoweredWeaknessSpellId = SPELL_EMPOWERED_DARK_HELPER; m_uiSurgeSpellId = SPELL_LIGHT_SURGE; m_uiVortexSpellId = SPELL_LIGHT_VORTEX; m_uiShieldSpellId = SPELL_LIGHT_SHIELD; m_uiTwinPactSpellId = SPELL_LIGHT_TWIN_PACT; m_uiTouchSpellId = SPELL_LIGHT_TOUCH; m_uiSpikeSpellId = SPELL_LIGHT_TWIN_SPIKE; HomeLocation = ToCCommonLoc[8]; EssenceLocation[0] = TwinValkyrsLoc[2]; EssenceLocation[1] = TwinValkyrsLoc[3]; if (m_pInstance) { m_pInstance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_START_TWINS_FIGHT); } } void EnterCombat(Unit* who) { boss_twin_baseAI::EnterCombat(who); if (m_pInstance) { m_pInstance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_START_TWINS_FIGHT); } } }; }; /*###### ## boss_eydis ######*/ class boss_eydis : public CreatureScript { public: boss_eydis() : CreatureScript("boss_eydis") { } CreatureAI* GetAI(Creature* creature) const { return new boss_eydisAI(creature); } struct boss_eydisAI : public boss_twin_baseAI { boss_eydisAI(Creature* creature) : boss_twin_baseAI(creature) {} void Reset() { boss_twin_baseAI::Reset(); SetEquipmentSlots(false, EQUIP_MAIN_2, EQUIP_UNEQUIP, EQUIP_NO_CHANGE); m_uiStage = 1; m_uiWeapon = EQUIP_MAIN_2; m_uiAuraState = AURA_STATE_UNKNOWN19; m_uiVortexEmote = EMOTE_DARK_VORTEX; m_uiVortexSay = SAY_DARK_VORTEX; m_uiSisterNpcId = NPC_LIGHTBANE; m_uiColorballNpcId = NPC_UNLEASHED_DARK; m_uiEssenceNpcId = NPC_DARK_ESSENCE; m_uiMyEmphatySpellId = SPELL_TWIN_EMPATHY_2; m_uiMyEssenceSpellId = SPELL_DARK_ESSENCE_HELPER; m_uiOtherEssenceSpellId = SPELL_LIGHT_ESSENCE_HELPER; m_uiEmpoweredWeaknessSpellId = SPELL_EMPOWERED_LIGHT_HELPER; m_uiSurgeSpellId = SPELL_DARK_SURGE; m_uiVortexSpellId = SPELL_DARK_VORTEX; m_uiShieldSpellId = SPELL_DARK_SHIELD; m_uiTwinPactSpellId = SPELL_DARK_TWIN_PACT; m_uiTouchSpellId = SPELL_DARK_TOUCH; m_uiSpikeSpellId = SPELL_DARK_TWIN_SPIKE; HomeLocation = ToCCommonLoc[9]; EssenceLocation[0] = TwinValkyrsLoc[0]; EssenceLocation[1] = TwinValkyrsLoc[1]; } }; }; #define ESSENCE_REMOVE 0 #define ESSENCE_APPLY 1 class mob_essence_of_twin : public CreatureScript { public: mob_essence_of_twin() : CreatureScript("mob_essence_of_twin") { } struct mob_essence_of_twinAI : public ScriptedAI { mob_essence_of_twinAI(Creature* creature) : ScriptedAI(creature) { } uint32 GetData(uint32 data) { uint32 spellReturned = 0; switch (me->GetEntry()) { case NPC_LIGHT_ESSENCE: spellReturned = data == ESSENCE_REMOVE? SPELL_DARK_ESSENCE_HELPER : SPELL_LIGHT_ESSENCE_HELPER; break; case NPC_DARK_ESSENCE: spellReturned = data == ESSENCE_REMOVE? SPELL_LIGHT_ESSENCE_HELPER : SPELL_DARK_ESSENCE_HELPER; break; default: break; } return spellReturned; } }; CreatureAI* GetAI(Creature* creature) const { return new mob_essence_of_twinAI(creature); }; bool OnGossipHello(Player* player, Creature* creature) { player->RemoveAurasDueToSpell(creature->GetAI()->GetData(ESSENCE_REMOVE)); player->CastSpell(player, creature->GetAI()->GetData(ESSENCE_APPLY), true); player->CLOSE_GOSSIP_MENU(); return true; } }; struct mob_unleashed_ballAI : public ScriptedAI { mob_unleashed_ballAI(Creature* creature) : ScriptedAI(creature) { m_pInstance = (InstanceScript*)creature->GetInstanceScript(); } InstanceScript* m_pInstance; uint32 m_uiRangeCheckTimer; void MoveToNextPoint() { float x0 = ToCCommonLoc[1].GetPositionX(), y0 = ToCCommonLoc[1].GetPositionY(), r = 47.0f; float y = y0; float x = float(urand(uint32(x0 - r), uint32(x0 + r))); if (urand(0, 1)) y = y0 + sqrt(pow(r, 2) - pow((x-x0), 2)); else y = y0 - sqrt(pow(r, 2) - pow((x-x0), 2)); me->GetMotionMaster()->MovePoint(0, x, y, me->GetPositionZ()); } void Reset() { me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_OOC_NOT_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE); me->SetReactState(REACT_PASSIVE); me->AddUnitMovementFlag(MOVEMENTFLAG_LEVITATING); me->SetFlying(true); SetCombatMovement(false); MoveToNextPoint(); m_uiRangeCheckTimer = IN_MILLISECONDS; } void MovementInform(uint32 uiType, uint32 uiId) { if (uiType != POINT_MOTION_TYPE) return; switch (uiId) { case 0: if (urand(0, 3) == 0) MoveToNextPoint(); else me->DisappearAndDie(); break; } } }; class mob_unleashed_dark : public CreatureScript { public: mob_unleashed_dark() : CreatureScript("mob_unleashed_dark") { } CreatureAI* GetAI(Creature* creature) const { return new mob_unleashed_darkAI(creature); } struct mob_unleashed_darkAI : public mob_unleashed_ballAI { mob_unleashed_darkAI(Creature* creature) : mob_unleashed_ballAI(creature) {} void UpdateAI(const uint32 uiDiff) { if (m_uiRangeCheckTimer < uiDiff) { if (Unit* target = me->SelectNearestTarget(2.0f)) if (target->GetTypeId() == TYPEID_PLAYER && target->isAlive()) { DoCastAOE(SPELL_UNLEASHED_DARK); me->GetMotionMaster()->MoveIdle(); me->DespawnOrUnsummon(500); } m_uiRangeCheckTimer = IN_MILLISECONDS; } else m_uiRangeCheckTimer -= uiDiff; } void SpellHitTarget(Unit* who, const SpellInfo* /*spell*/) { if (who->HasAura(SPELL_DARK_ESSENCE_HELPER)) who->CastSpell(who, SPELL_POWERING_UP, true); } }; }; class mob_unleashed_light : public CreatureScript { public: mob_unleashed_light() : CreatureScript("mob_unleashed_light") { } CreatureAI* GetAI(Creature* creature) const { return new mob_unleashed_lightAI(creature); } struct mob_unleashed_lightAI : public mob_unleashed_ballAI { mob_unleashed_lightAI(Creature* creature) : mob_unleashed_ballAI(creature) {} void UpdateAI(const uint32 uiDiff) { if (m_uiRangeCheckTimer < uiDiff) { if (Unit* target = me->SelectNearestTarget(2.0f)) if (target->GetTypeId() == TYPEID_PLAYER && target->isAlive()) { DoCastAOE(SPELL_UNLEASHED_LIGHT); me->GetMotionMaster()->MoveIdle(); me->DespawnOrUnsummon(500); } m_uiRangeCheckTimer = IN_MILLISECONDS; } else m_uiRangeCheckTimer -= uiDiff; } void SpellHitTarget(Unit* who, const SpellInfo* /*spell*/) { if (who->HasAura(SPELL_LIGHT_ESSENCE_HELPER)) who->CastSpell(who, SPELL_POWERING_UP, true); } }; }; class spell_powering_up : public SpellScriptLoader { public: spell_powering_up() : SpellScriptLoader("spell_powering_up") { } class spell_powering_up_AuraScript : public AuraScript { PrepareAuraScript(spell_powering_up_AuraScript); void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (Unit* target = GetTarget()) { if (Aura* pAura = target->GetAura(GetId())) { if (pAura->GetStackAmount() == 100) { if(target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2206, EFFECT_1)) target->CastSpell(target, SPELL_EMPOWERED_DARK, true); if(target->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2845, EFFECT_1)) target->CastSpell(target, SPELL_EMPOWERED_LIGHT, true); target->RemoveAurasDueToSpell(GetId()); } } } } void Register() { OnEffectApply += AuraEffectApplyFn(spell_powering_up_AuraScript::OnApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_powering_up_AuraScript(); } class spell_powering_up_SpellScript : public SpellScript { public: PrepareSpellScript(spell_powering_up_SpellScript) uint32 spellId; bool Validate(SpellEntry const* /*spellEntry*/) { spellId = sSpellMgr->GetSpellIdForDifficulty(SPELL_SURGE_OF_SPEED, GetCaster()); if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void HandleScriptEffect(SpellEffIndex /*effIndex*/) { if (Unit* target = GetTargetUnit()) if (urand(0, 99) < 15) target->CastSpell(target, spellId, true); } void Register() { OnEffect += SpellEffectFn(spell_powering_up_SpellScript::HandleScriptEffect, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); } }; SpellScript* GetSpellScript() const { return new spell_powering_up_SpellScript(); } }; class spell_valkyr_essences : public SpellScriptLoader { public: spell_valkyr_essences() : SpellScriptLoader("spell_valkyr_essences") { } class spell_valkyr_essences_AuraScript : public AuraScript { PrepareAuraScript(spell_valkyr_essences_AuraScript); uint32 spellId; bool Load() { spellId = sSpellMgr->GetSpellIdForDifficulty(SPELL_SURGE_OF_SPEED, GetCaster()); if (!sSpellMgr->GetSpellInfo(spellId)) return false; return true; } void Absorb(AuraEffect* /*aurEff*/, DamageInfo & /*dmgInfo*/, uint32 & /*absorbAmount*/) { if (urand(0, 99) < 5) GetTarget()->CastSpell(GetTarget(), spellId, true); } void Register() { OnEffectAbsorb += AuraEffectAbsorbFn(spell_valkyr_essences_AuraScript::Absorb, EFFECT_0); } }; AuraScript* GetAuraScript() const { return new spell_valkyr_essences_AuraScript(); } }; class spell_power_of_the_twins : public SpellScriptLoader { public: spell_power_of_the_twins() : SpellScriptLoader("spell_power_of_the_twins") { } class spell_power_of_the_twins_AuraScript : public AuraScript { PrepareAuraScript(spell_power_of_the_twins_AuraScript); bool Load() { return GetCaster()->GetTypeId() == TYPEID_UNIT; } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) { if (Creature* Valk = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(GetCaster()->GetEntry()))) CAST_AI(boss_twin_baseAI, Valk->AI())->EnableDualWield(true); } } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) { if (Creature* Valk = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(GetCaster()->GetEntry()))) CAST_AI(boss_twin_baseAI, Valk->AI())->EnableDualWield(false); } } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_power_of_the_twins_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_power_of_the_twins_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_MOD_DAMAGE_PERCENT_DONE, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } }; AuraScript* GetAuraScript() const { return new spell_power_of_the_twins_AuraScript(); } }; void AddSC_boss_twin_valkyr() { new boss_fjola(); new boss_eydis(); new mob_unleashed_light(); new mob_unleashed_dark(); new mob_essence_of_twin(); new spell_powering_up(); new spell_valkyr_essences(); new spell_power_of_the_twins(); }
Bootz/MyCore4Kata
src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp
C++
gpl-2.0
27,901
/*************************************************************************** * Copyright (C) 2008-2014 by Andrzej Rybczak * * electricityispower@gmail.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "statusbar.h" #include <boost/algorithm/string/split.hpp> #include "mutable_song.h" namespace MPD {// std::string MutableSong::getArtist(unsigned idx) const { return getTag(MPD_TAG_ARTIST, [this, idx](){ return Song::getArtist(idx); }, idx); } std::string MutableSong::getTitle(unsigned idx) const { return getTag(MPD_TAG_TITLE, [this, idx](){ return Song::getTitle(idx); }, idx); } std::string MutableSong::getAlbum(unsigned idx) const { return getTag(MPD_TAG_ALBUM, [this, idx](){ return Song::getAlbum(idx); }, idx); } std::string MutableSong::getAlbumArtist(unsigned idx) const { return getTag(MPD_TAG_ALBUM_ARTIST, [this, idx](){ return Song::getAlbumArtist(idx); }, idx); } std::string MutableSong::getTrack(unsigned idx) const { std::string track = getTag(MPD_TAG_TRACK, [this, idx](){ return Song::getTrack(idx); }, idx); if ((track.length() == 1 && track[0] != '0') || (track.length() > 3 && track[1] == '/')) return "0"+track; else return track; } std::string MutableSong::getDate(unsigned idx) const { return getTag(MPD_TAG_DATE, [this, idx](){ return Song::getDate(idx); }, idx); } std::string MutableSong::getGenre(unsigned idx) const { return getTag(MPD_TAG_GENRE, [this, idx](){ return Song::getGenre(idx); }, idx); } std::string MutableSong::getComposer(unsigned idx) const { return getTag(MPD_TAG_COMPOSER, [this, idx](){ return Song::getComposer(idx); }, idx); } std::string MutableSong::getPerformer(unsigned idx) const { return getTag(MPD_TAG_PERFORMER, [this, idx](){ return Song::getPerformer(idx); }, idx); } std::string MutableSong::getDisc(unsigned idx) const { return getTag(MPD_TAG_DISC, [this, idx](){ return Song::getDisc(idx); }, idx); } std::string MutableSong::getComment(unsigned idx) const { return getTag(MPD_TAG_COMMENT, [this, idx](){ return Song::getComment(idx); }, idx); } void MutableSong::setArtist(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_ARTIST, Song::getArtist(idx), value, idx); } void MutableSong::setTitle(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_TITLE, Song::getTitle(idx), value, idx); } void MutableSong::setAlbum(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_ALBUM, Song::getAlbum(idx), value, idx); } void MutableSong::setAlbumArtist(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_ALBUM_ARTIST, Song::getAlbumArtist(idx), value, idx); } void MutableSong::setTrack(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_TRACK, Song::getTrack(idx), value, idx); } void MutableSong::setDate(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_DATE, Song::getDate(idx), value, idx); } void MutableSong::setGenre(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_GENRE, Song::getGenre(idx), value, idx); } void MutableSong::setComposer(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_COMPOSER, Song::getComposer(idx), value, idx); } void MutableSong::setPerformer(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_PERFORMER, Song::getPerformer(idx), value, idx); } void MutableSong::setDisc(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_DISC, Song::getDisc(idx), value, idx); } void MutableSong::setComment(const std::string &value, unsigned idx) { replaceTag(MPD_TAG_COMMENT, Song::getComment(idx), value, idx); } const std::string &MutableSong::getNewName() const { return m_name; } void MutableSong::setNewName(const std::string &value) { if (getName() == value) m_name.clear(); else m_name = value; } unsigned MutableSong::getDuration() const { if (m_duration > 0) return m_duration; else return Song::getDuration(); } time_t MutableSong::getMTime() const { if (m_mtime > 0) return m_mtime; else return Song::getMTime(); } void MutableSong::setDuration(unsigned int duration) { m_duration = duration; } void MutableSong::setMTime(time_t mtime) { m_mtime = mtime; } void MutableSong::setTags(SetFunction set, const std::string &value, const std::string &delimiter) { std::vector<std::string> tags; boost::iter_split(tags, value, boost::first_finder(delimiter)); size_t i = 0; for (; i < tags.size(); ++i) (this->*set)(tags[i], i); // set next tag to be empty, so tags with bigger indexes won't be read (this->*set)("", i); } bool MutableSong::isModified() const { return !m_name.empty() || !m_tags.empty(); } void MutableSong::clearModifications() { m_name.clear(); m_tags.clear(); } void MutableSong::replaceTag(mpd_tag_type tag_type, std::string orig_value, const std::string &value, unsigned idx) { Tag tag(tag_type, idx); if (value == orig_value) { auto it = m_tags.find(tag); if (it != m_tags.end()) m_tags.erase(it); } else m_tags[tag] = value; } }
dpayne/ncmpcpp-colorful
src/mutable_song.cpp
C++
gpl-2.0
6,225
<?php /** * Get, validate, and validate Entry search term request variable. * * @since 10.4.8 * * @category WordPress\Plugin * @package Connections Business Directory * @subpackage Connections\Request\Entry Search Term * @author Steven A. Zahm * @license GPL-2.0+ * @copyright Copyright (c) 2021, Steven A. Zahm * @link https://connections-pro.com/ */ namespace Connections_Directory\Request; /** * Class Entry_Search_Term * * @package Connections_Directory\Request */ final class Entry_Search_Term extends Search { /** * The request variable key. * * @since 10.4.8 * * @var string */ protected $key = 'cn-s'; }
Connections-Business-Directory/Connections
includes/Request/Entry_Search_Term.php
PHP
gpl-2.0
664
/* * Copyright (C) 2003-2009 The Music Player Daemon Project * http://www.musicpd.org * * 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. */ /* * Imported from AudioCompress by J. Shagam <fluffy@beesbuzz.biz> */ #ifndef MPD_COMPRESS_H #define MPD_COMPRESS_H /* These are copied from the AudioCompress config.h, mainly because CompressDo * needs GAINSHIFT defined. The rest are here so they can be used as defaults * to pass to CompressCfg(). -- jat */ #define ANTICLIP 0 /* Strict clipping protection */ #define TARGET 25000 /* Target level */ #define GAINMAX 32 /* The maximum amount to amplify by */ #define GAINSHIFT 10 /* How fine-grained the gain is */ #define GAINSMOOTH 8 /* How much inertia ramping has*/ #define BUCKETS 400 /* How long of a history to store */ void CompressCfg(int monitor, int anticlip, int target, int maxgain, int smooth, unsigned buckets); void CompressDo(void *data, unsigned int numSamples); void CompressFree(void); #endif
azuwis/mpd
src/compress.h
C
gpl-2.0
1,660
/* global console */ import MarkerManager from 'ghost/mixins/marker-manager'; import PostModel from 'ghost/models/post'; import boundOneWay from 'ghost/utils/bound-one-way'; var watchedProps, EditorControllerMixin; // this array will hold properties we need to watch // to know if the model has been changed (`controller.isDirty`) watchedProps = ['scratch', 'titleScratch', 'model.isDirty', 'tags.[]']; PostModel.eachAttribute(function (name) { watchedProps.push('model.' + name); }); EditorControllerMixin = Ember.Mixin.create(MarkerManager, { needs: ['post-tags-input', 'post-settings-menu'], init: function () { var self = this; this._super(); window.onbeforeunload = function () { return self.get('isDirty') ? self.unloadDirtyMessage() : null; }; }, /** * By default, a post will not change its publish state. * Only with a user-set value (via setSaveType action) * can the post's status change. */ willPublish: boundOneWay('isPublished'), // Make sure editor starts with markdown shown isPreview: false, // set by the editor route and `isDirty`. useful when checking // whether the number of tags has changed for `isDirty`. previousTagNames: null, tagNames: Ember.computed('tags.@each.name', function () { return this.get('tags').mapBy('name'); }), // compares previousTagNames to tagNames tagNamesEqual: function () { var tagNames = this.get('tagNames'), previousTagNames = this.get('previousTagNames'), hashCurrent, hashPrevious; // beware! even if they have the same length, // that doesn't mean they're the same. if (tagNames.length !== previousTagNames.length) { return false; } // instead of comparing with slow, nested for loops, // perform join on each array and compare the strings hashCurrent = tagNames.join(''); hashPrevious = previousTagNames.join(''); return hashCurrent === hashPrevious; }, // a hook created in editor-base-route's setupController modelSaved: function () { var model = this.get('model'); // safer to updateTags on save in one place // rather than in all other places save is called model.updateTags(); // set previousTagNames to current tagNames for isDirty check this.set('previousTagNames', this.get('tagNames')); // `updateTags` triggers `isDirty => true`. // for a saved model it would otherwise be false. // if the two "scratch" properties (title and content) match the model, then // it's ok to set isDirty to false if (this.get('titleScratch') === model.get('title') && this.get('scratch') === model.get('markdown')) { this.set('isDirty', false); } }, // an ugly hack, but necessary to watch all the model's properties // and more, without having to be explicit and do it manually isDirty: Ember.computed.apply(Ember, watchedProps.concat(function (key, value) { if (arguments.length > 1) { return value; } var model = this.get('model'), markdown = this.get('markdown'), title = this.get('title'), titleScratch = this.get('titleScratch'), scratch = this.getMarkdown().withoutMarkers, changedAttributes; if (!this.tagNamesEqual()) { return true; } if (titleScratch !== title) { return true; } // since `scratch` is not model property, we need to check // it explicitly against the model's markdown attribute if (markdown !== scratch) { return true; } // models created on the client always return `isDirty: true`, // so we need to see which properties have actually changed. if (model.get('isNew')) { changedAttributes = Ember.keys(model.changedAttributes()); if (changedAttributes.length) { return true; } return false; } // even though we use the `scratch` prop to show edits, // which does *not* change the model's `isDirty` property, // `isDirty` will tell us if the other props have changed, // as long as the model is not new (model.isNew === false). return model.get('isDirty'); })), // used on window.onbeforeunload unloadDirtyMessage: function () { return '==============================\n\n' + '嘿,老兄!好像你还在编辑博文吧,' + '而且博文内容也还没有保存哦!' + '\n\n建议保存先!\n\n' + '=============================='; }, // TODO: This has to be moved to the I18n localization file. // This structure is supposed to be close to the i18n-localization which will be used soon. messageMap: { errors: { post: { published: { published: '更新失败。', draft: '保存失败。' }, draft: { published: '发布失败。', draft: '保存失败。' } } }, success: { post: { published: { published: '已更新。', draft: '已保存。' }, draft: { published: '已发布!', draft: '已保存。' } } } }, showSaveNotification: function (prevStatus, status, delay) { var message = this.messageMap.success.post[prevStatus][status]; this.notifications.showSuccess(message, {delayed: delay}); }, showErrorNotification: function (prevStatus, status, errors, delay) { var message = this.messageMap.errors.post[prevStatus][status]; message += '<br />' + errors[0].message; this.notifications.showError(message, {delayed: delay}); }, shouldFocusTitle: Ember.computed.alias('model.isNew'), shouldFocusEditor: Ember.computed.not('model.isNew'), actions: { save: function (options) { var status = this.get('willPublish') ? 'published' : 'draft', prevStatus = this.get('status'), isNew = this.get('isNew'), autoSaveId = this.get('autoSaveId'), timedSaveId = this.get('timedSaveId'), self = this, psmController = this.get('controllers.post-settings-menu'), promise; options = options || {}; if (autoSaveId) { Ember.run.cancel(autoSaveId); this.set('autoSaveId', null); } if (timedSaveId) { Ember.run.cancel(timedSaveId); this.set('timedSaveId', null); } self.notifications.closePassive(); // ensure an incomplete tag is finalised before save this.get('controllers.post-tags-input').send('addNewTag'); // Set the properties that are indirected // set markdown equal to what's in the editor, minus the image markers. this.set('markdown', this.getMarkdown().withoutMarkers); this.set('status', status); // Set a default title if (!this.get('titleScratch')) { this.set('titleScratch', '(Untitled)'); } this.set('title', this.get('titleScratch')); this.set('meta_title', psmController.get('metaTitleScratch')); this.set('meta_description', psmController.get('metaDescriptionScratch')); if (!this.get('slug')) { // Cancel any pending slug generation that may still be queued in the // run loop because we need to run it before the post is saved. Ember.run.cancel(psmController.get('debounceId')); psmController.generateAndSetSlug('slug'); } promise = Ember.RSVP.resolve(psmController.get('lastPromise')).then(function () { return self.get('model').save(options).then(function (model) { if (!options.silent) { self.showSaveNotification(prevStatus, model.get('status'), isNew ? true : false); } return model; }); }).catch(function (errors) { if (!options.silent) { self.showErrorNotification(prevStatus, self.get('status'), errors); } self.set('status', prevStatus); return Ember.RSVP.reject(errors); }); psmController.set('lastPromise', promise); return promise; }, setSaveType: function (newType) { if (newType === 'publish') { this.set('willPublish', true); } else if (newType === 'draft') { this.set('willPublish', false); } else { console.warn('Received invalid save type; ignoring.'); } }, // set from a `sendAction` on the codemirror component, // so that we get a reference for handling uploads. setCodeMirror: function (codemirrorComponent) { var codemirror = codemirrorComponent.get('codemirror'); this.set('codemirrorComponent', codemirrorComponent); this.set('codemirror', codemirror); }, // fired from the gh-markdown component when an image upload starts disableCodeMirror: function () { this.get('codemirrorComponent').disableCodeMirror(); }, // fired from the gh-markdown component when an image upload finishes enableCodeMirror: function () { this.get('codemirrorComponent').enableCodeMirror(); }, // Match the uploaded file to a line in the editor, and update that line with a path reference // ensuring that everything ends up in the correct place and format. handleImgUpload: function (e, resultSrc) { var editor = this.get('codemirror'), line = this.findLine(Ember.$(e.currentTarget).attr('id')), lineNumber = editor.getLineNumber(line), // jscs:disable match = line.text.match(/\([^\n]*\)?/), // jscs:enable replacement = '(http://)'; if (match) { // simple case, we have the parenthesis editor.setSelection( {line: lineNumber, ch: match.index + 1}, {line: lineNumber, ch: match.index + match[0].length - 1} ); } else { // jscs:disable match = line.text.match(/\]/); // jscs:enable if (match) { editor.replaceRange( replacement, {line: lineNumber, ch: match.index + 1}, {line: lineNumber, ch: match.index + 1} ); editor.setSelection( {line: lineNumber, ch: match.index + 2}, {line: lineNumber, ch: match.index + replacement.length} ); } } editor.replaceSelection(resultSrc); }, togglePreview: function (preview) { this.set('isPreview', preview); }, autoSave: function () { if (this.get('model.isDraft')) { var autoSaveId, timedSaveId; timedSaveId = Ember.run.throttle(this, 'send', 'save', {silent: true, disableNProgress: true}, 60000, false); this.set('timedSaveId', timedSaveId); autoSaveId = Ember.run.debounce(this, 'send', 'save', {silent: true, disableNProgress: true}, 3000); this.set('autoSaveId', autoSaveId); } }, autoSaveNew: function () { if (this.get('isNew')) { this.send('save', {silent: true, disableNProgress: true}); } } } }); export default EditorControllerMixin;
androidesk/adesk-blog
core/client/mixins/editor-base-controller.js
JavaScript
gpl-2.0
12,530
/* * * Clock initialization for OMAP4 * * (C) Copyright 2010 * Texas Instruments, <www.ti.com> * * Aneesh V <aneesh@ti.com> * * Based on previous work by: * Santosh Shilimkar <santosh.shilimkar@ti.com> * Rajendra Nayak <rnayak@ti.com> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/omap_common.h> #include <asm/gpio.h> #include <asm/arch/clocks.h> #include <asm/arch/sys_proto.h> #include <asm/utils.h> #include <asm/omap_gpio.h> #ifndef CONFIG_SPL_BUILD /* * printing to console doesn't work unless * this code is executed from SPL */ #define printf(fmt, args...) #define puts(s) #endif struct omap4_prcm_regs *const prcm = (struct omap4_prcm_regs *)0x4A004100; const u32 sys_clk_array[8] = { 12000000, /* 12 MHz */ 13000000, /* 13 MHz */ 16800000, /* 16.8 MHz */ 19200000, /* 19.2 MHz */ 26000000, /* 26 MHz */ 27000000, /* 27 MHz */ 38400000, /* 38.4 MHz */ }; /* * The M & N values in the following tables are created using the * following tool: * tools/omap/clocks_get_m_n.c * Please use this tool for creating the table for any new frequency. */ /* dpll locked at 1400 MHz MPU clk at 700 MHz(OPP100) - DCC OFF */ static const struct dpll_params mpu_dpll_params_1400mhz[NUM_SYS_CLKS] = { {175, 2, 1, -1, -1, -1, -1, -1}, /* 12 MHz */ {700, 12, 1, -1, -1, -1, -1, -1}, /* 13 MHz */ {125, 2, 1, -1, -1, -1, -1, -1}, /* 16.8 MHz */ {401, 10, 1, -1, -1, -1, -1, -1}, /* 19.2 MHz */ {350, 12, 1, -1, -1, -1, -1, -1}, /* 26 MHz */ {700, 26, 1, -1, -1, -1, -1, -1}, /* 27 MHz */ {638, 34, 1, -1, -1, -1, -1, -1} /* 38.4 MHz */ }; /* dpll locked at 1584 MHz - MPU clk at 792 MHz(OPP Turbo 4430) */ static const struct dpll_params mpu_dpll_params_1600mhz[NUM_SYS_CLKS] = { {200, 2, 1, -1, -1, -1, -1, -1}, /* 12 MHz */ {800, 12, 1, -1, -1, -1, -1, -1}, /* 13 MHz */ {619, 12, 1, -1, -1, -1, -1, -1}, /* 16.8 MHz */ {125, 2, 1, -1, -1, -1, -1, -1}, /* 19.2 MHz */ {400, 12, 1, -1, -1, -1, -1, -1}, /* 26 MHz */ {800, 26, 1, -1, -1, -1, -1, -1}, /* 27 MHz */ {125, 5, 1, -1, -1, -1, -1, -1} /* 38.4 MHz */ }; /* dpll locked at 1200 MHz - MPU clk at 600 MHz */ static const struct dpll_params mpu_dpll_params_1200mhz[NUM_SYS_CLKS] = { {50, 0, 1, -1, -1, -1, -1, -1}, /* 12 MHz */ {600, 12, 1, -1, -1, -1, -1, -1}, /* 13 MHz */ {250, 6, 1, -1, -1, -1, -1, -1}, /* 16.8 MHz */ {125, 3, 1, -1, -1, -1, -1, -1}, /* 19.2 MHz */ {300, 12, 1, -1, -1, -1, -1, -1}, /* 26 MHz */ {200, 8, 1, -1, -1, -1, -1, -1}, /* 27 MHz */ {125, 7, 1, -1, -1, -1, -1, -1} /* 38.4 MHz */ }; static const struct dpll_params core_dpll_params_1600mhz[NUM_SYS_CLKS] = { {200, 2, 1, 5, 8, 4, 6, 5}, /* 12 MHz */ {800, 12, 1, 5, 8, 4, 6, 5}, /* 13 MHz */ {619, 12, 1, 5, 8, 4, 6, 5}, /* 16.8 MHz */ {125, 2, 1, 5, 8, 4, 6, 5}, /* 19.2 MHz */ {400, 12, 1, 5, 8, 4, 6, 5}, /* 26 MHz */ {800, 26, 1, 5, 8, 4, 6, 5}, /* 27 MHz */ {125, 5, 1, 5, 8, 4, 6, 5} /* 38.4 MHz */ }; static const struct dpll_params core_dpll_params_es1_1524mhz[NUM_SYS_CLKS] = { {127, 1, 1, 5, 8, 4, 6, 5}, /* 12 MHz */ {762, 12, 1, 5, 8, 4, 6, 5}, /* 13 MHz */ {635, 13, 1, 5, 8, 4, 6, 5}, /* 16.8 MHz */ {635, 15, 1, 5, 8, 4, 6, 5}, /* 19.2 MHz */ {381, 12, 1, 5, 8, 4, 6, 5}, /* 26 MHz */ {254, 8, 1, 5, 8, 4, 6, 5}, /* 27 MHz */ {496, 24, 1, 5, 8, 4, 6, 5} /* 38.4 MHz */ }; static const struct dpll_params core_dpll_params_es2_1600mhz_ddr200mhz[NUM_SYS_CLKS] = { {200, 2, 2, 5, 8, 4, 6, 5}, /* 12 MHz */ {800, 12, 2, 5, 8, 4, 6, 5}, /* 13 MHz */ {619, 12, 2, 5, 8, 4, 6, 5}, /* 16.8 MHz */ {125, 2, 2, 5, 8, 4, 6, 5}, /* 19.2 MHz */ {400, 12, 2, 5, 8, 4, 6, 5}, /* 26 MHz */ {800, 26, 2, 5, 8, 4, 6, 5}, /* 27 MHz */ {125, 5, 2, 5, 8, 4, 6, 5} /* 38.4 MHz */ }; static const struct dpll_params per_dpll_params_1536mhz[NUM_SYS_CLKS] = { {64, 0, 8, 6, 12, 9, 4, 5}, /* 12 MHz */ {768, 12, 8, 6, 12, 9, 4, 5}, /* 13 MHz */ {320, 6, 8, 6, 12, 9, 4, 5}, /* 16.8 MHz */ {40, 0, 8, 6, 12, 9, 4, 5}, /* 19.2 MHz */ {384, 12, 8, 6, 12, 9, 4, 5}, /* 26 MHz */ {256, 8, 8, 6, 12, 9, 4, 5}, /* 27 MHz */ {20, 0, 8, 6, 12, 9, 4, 5} /* 38.4 MHz */ }; static const struct dpll_params iva_dpll_params_1862mhz[NUM_SYS_CLKS] = { {931, 11, -1, -1, 4, 7, -1, -1}, /* 12 MHz */ {931, 12, -1, -1, 4, 7, -1, -1}, /* 13 MHz */ {665, 11, -1, -1, 4, 7, -1, -1}, /* 16.8 MHz */ {727, 14, -1, -1, 4, 7, -1, -1}, /* 19.2 MHz */ {931, 25, -1, -1, 4, 7, -1, -1}, /* 26 MHz */ {931, 26, -1, -1, 4, 7, -1, -1}, /* 27 MHz */ {412, 16, -1, -1, 4, 7, -1, -1} /* 38.4 MHz */ }; /* ABE M & N values with sys_clk as source */ static const struct dpll_params abe_dpll_params_sysclk_196608khz[NUM_SYS_CLKS] = { {49, 5, 1, 1, -1, -1, -1, -1}, /* 12 MHz */ {68, 8, 1, 1, -1, -1, -1, -1}, /* 13 MHz */ {35, 5, 1, 1, -1, -1, -1, -1}, /* 16.8 MHz */ {46, 8, 1, 1, -1, -1, -1, -1}, /* 19.2 MHz */ {34, 8, 1, 1, -1, -1, -1, -1}, /* 26 MHz */ {29, 7, 1, 1, -1, -1, -1, -1}, /* 27 MHz */ {64, 24, 1, 1, -1, -1, -1, -1} /* 38.4 MHz */ }; /* ABE M & N values with 32K clock as source */ static const struct dpll_params abe_dpll_params_32k_196608khz = { 750, 0, 1, 1, -1, -1, -1, -1 }; static const struct dpll_params usb_dpll_params_1920mhz[NUM_SYS_CLKS] = { {80, 0, 2, -1, -1, -1, -1, -1}, /* 12 MHz */ {960, 12, 2, -1, -1, -1, -1, -1}, /* 13 MHz */ {400, 6, 2, -1, -1, -1, -1, -1}, /* 16.8 MHz */ {50, 0, 2, -1, -1, -1, -1, -1}, /* 19.2 MHz */ {480, 12, 2, -1, -1, -1, -1, -1}, /* 26 MHz */ {320, 8, 2, -1, -1, -1, -1, -1}, /* 27 MHz */ {25, 0, 2, -1, -1, -1, -1, -1} /* 38.4 MHz */ }; void setup_post_dividers(u32 *const base, const struct dpll_params *params) { struct dpll_regs *const dpll_regs = (struct dpll_regs *)base; /* Setup post-dividers */ if (params->m2 >= 0) writel(params->m2, &dpll_regs->cm_div_m2_dpll); if (params->m3 >= 0) writel(params->m3, &dpll_regs->cm_div_m3_dpll); if (params->m4 >= 0) writel(params->m4, &dpll_regs->cm_div_m4_dpll); if (params->m5 >= 0) writel(params->m5, &dpll_regs->cm_div_m5_dpll); if (params->m6 >= 0) writel(params->m6, &dpll_regs->cm_div_m6_dpll); if (params->m7 >= 0) writel(params->m7, &dpll_regs->cm_div_m7_dpll); } /* * Lock MPU dpll * * Resulting MPU frequencies: * 4430 ES1.0 : 600 MHz * 4430 ES2.x : 792 MHz (OPP Turbo) * 4460 : 920 MHz (OPP Turbo) - DCC disabled */ const struct dpll_params *get_mpu_dpll_params(void) { u32 omap_rev, sysclk_ind; omap_rev = omap_revision(); sysclk_ind = get_sys_clk_index(); if (omap_rev == OMAP4430_ES1_0) return &mpu_dpll_params_1200mhz[sysclk_ind]; else if (omap_rev < OMAP4460_ES1_0) return &mpu_dpll_params_1600mhz[sysclk_ind]; else return &mpu_dpll_params_1400mhz[sysclk_ind]; } const struct dpll_params *get_core_dpll_params(void) { u32 sysclk_ind = get_sys_clk_index(); switch (omap_revision()) { case OMAP4430_ES1_0: return &core_dpll_params_es1_1524mhz[sysclk_ind]; case OMAP4430_ES2_0: case OMAP4430_SILICON_ID_INVALID: /* safest */ return &core_dpll_params_es2_1600mhz_ddr200mhz[sysclk_ind]; default: return &core_dpll_params_1600mhz[sysclk_ind]; } } const struct dpll_params *get_per_dpll_params(void) { u32 sysclk_ind = get_sys_clk_index(); return &per_dpll_params_1536mhz[sysclk_ind]; } const struct dpll_params *get_iva_dpll_params(void) { u32 sysclk_ind = get_sys_clk_index(); return &iva_dpll_params_1862mhz[sysclk_ind]; } const struct dpll_params *get_usb_dpll_params(void) { u32 sysclk_ind = get_sys_clk_index(); return &usb_dpll_params_1920mhz[sysclk_ind]; } const struct dpll_params *get_abe_dpll_params(void) { #ifdef CONFIG_SYS_OMAP_ABE_SYSCK u32 sysclk_ind = get_sys_clk_index(); return &abe_dpll_params_sysclk_196608khz[sysclk_ind]; #else return &abe_dpll_params_32k_196608khz; #endif } /* * Setup the voltages for vdd_mpu, vdd_core, and vdd_iva * We set the maximum voltages allowed here because Smart-Reflex is not * enabled in bootloader. Voltage initialization in the kernel will set * these to the nominal values after enabling Smart-Reflex */ void scale_vcores(void) { u32 volt, omap_rev; omap_vc_init(PRM_VC_I2C_CHANNEL_FREQ_KHZ); omap_rev = omap_revision(); /* * Scale Voltage rails: * 1. VDD_CORE * 3. VDD_MPU * 3. VDD_IVA */ if (omap_rev < OMAP4460_ES1_0) { /* * OMAP4430: * VDD_CORE = TWL6030 VCORE3 * VDD_MPU = TWL6030 VCORE1 * VDD_IVA = TWL6030 VCORE2 */ volt = 1200; do_scale_vcore(SMPS_REG_ADDR_VCORE3, volt); /* * note on VDD_MPU: * Setting a high voltage for Nitro mode as smart reflex is not * enabled. We use the maximum possible value in the AVS range * because the next higher voltage in the discrete range * (code >= 0b111010) is way too high. */ volt = 1325; do_scale_vcore(SMPS_REG_ADDR_VCORE1, volt); volt = 1200; do_scale_vcore(SMPS_REG_ADDR_VCORE2, volt); } else { /* * OMAP4460: * VDD_CORE = TWL6030 VCORE1 * VDD_MPU = TPS62361 * VDD_IVA = TWL6030 VCORE2 */ volt = 1200; do_scale_vcore(SMPS_REG_ADDR_VCORE1, volt); /* TPS62361 */ volt = 1203; do_scale_tps62361(TPS62361_VSEL0_GPIO, TPS62361_REG_ADDR_SET1, volt); /* VCORE 2 - supplies vdd_iva */ volt = 1200; do_scale_vcore(SMPS_REG_ADDR_VCORE2, volt); } } u32 get_offset_code(u32 offset) { u32 offset_code, step = 12660; /* 12.66 mV represented in uV */ if (omap_revision() == OMAP4430_ES1_0) offset -= PHOENIX_SMPS_BASE_VOLT_STD_MODE_UV; else offset -= PHOENIX_SMPS_BASE_VOLT_STD_MODE_WITH_OFFSET_UV; offset_code = (offset + step - 1) / step; /* The code starts at 1 not 0 */ return ++offset_code; } /* * Enable essential clock domains, modules and * do some additional special settings needed */ void enable_basic_clocks(void) { u32 *const clk_domains_essential[] = { &prcm->cm_l4per_clkstctrl, &prcm->cm_l3init_clkstctrl, &prcm->cm_memif_clkstctrl, &prcm->cm_l4cfg_clkstctrl, 0 }; u32 *const clk_modules_hw_auto_essential[] = { &prcm->cm_memif_emif_1_clkctrl, &prcm->cm_memif_emif_2_clkctrl, &prcm->cm_l4cfg_l4_cfg_clkctrl, &prcm->cm_wkup_gpio1_clkctrl, &prcm->cm_l4per_gpio2_clkctrl, &prcm->cm_l4per_gpio3_clkctrl, &prcm->cm_l4per_gpio4_clkctrl, &prcm->cm_l4per_gpio5_clkctrl, &prcm->cm_l4per_gpio6_clkctrl, &prcm->cm_l3init_usbphy_clkctrl, &prcm->cm_clksel_usb_60mhz, &prcm->cm_l3init_hsusbtll_clkctrl, 0 }; u32 *const clk_modules_explicit_en_essential[] = { &prcm->cm_wkup_gptimer1_clkctrl, &prcm->cm_l3init_hsmmc1_clkctrl, &prcm->cm_l3init_hsmmc2_clkctrl, &prcm->cm_l4per_gptimer2_clkctrl, &prcm->cm_wkup_wdtimer2_clkctrl, &prcm->cm_l4per_uart3_clkctrl, &prcm->cm_l3init_hsusbhost_clkctrl, 0 }; /* Enable optional additional functional clock for GPIO4 */ setbits_le32(&prcm->cm_l4per_gpio4_clkctrl, GPIO4_CLKCTRL_OPTFCLKEN_MASK); /* Enable 96 MHz clock for MMC1 & MMC2 */ setbits_le32(&prcm->cm_l3init_hsmmc1_clkctrl, HSMMC_CLKCTRL_CLKSEL_MASK); setbits_le32(&prcm->cm_l3init_hsmmc2_clkctrl, HSMMC_CLKCTRL_CLKSEL_MASK); /* Select 32KHz clock as the source of GPTIMER1 */ setbits_le32(&prcm->cm_wkup_gptimer1_clkctrl, GPTIMER1_CLKCTRL_CLKSEL_MASK); /* Enable optional 48M functional clock for USB PHY */ setbits_le32(&prcm->cm_l3init_usbphy_clkctrl, USBPHY_CLKCTRL_OPTFCLKEN_PHY_48M_MASK); do_enable_clocks(clk_domains_essential, clk_modules_hw_auto_essential, clk_modules_explicit_en_essential, 1); } void enable_basic_uboot_clocks(void) { u32 *const clk_domains_essential[] = { 0 }; u32 *const clk_modules_hw_auto_essential[] = { &prcm->cm_l3init_hsusbotg_clkctrl, &prcm->cm_l3init_usbphy_clkctrl, 0 }; u32 *const clk_modules_explicit_en_essential[] = { &prcm->cm_l4per_mcspi1_clkctrl, &prcm->cm_l4per_i2c1_clkctrl, &prcm->cm_l4per_i2c2_clkctrl, &prcm->cm_l4per_i2c3_clkctrl, &prcm->cm_l4per_i2c4_clkctrl, 0 }; do_enable_clocks(clk_domains_essential, clk_modules_hw_auto_essential, clk_modules_explicit_en_essential, 1); } /* * Enable non-essential clock domains, modules and * do some additional special settings needed */ void enable_non_essential_clocks(void) { u32 *const clk_domains_non_essential[] = { &prcm->cm_mpu_m3_clkstctrl, &prcm->cm_ivahd_clkstctrl, &prcm->cm_dsp_clkstctrl, &prcm->cm_dss_clkstctrl, &prcm->cm_sgx_clkstctrl, &prcm->cm1_abe_clkstctrl, &prcm->cm_c2c_clkstctrl, &prcm->cm_cam_clkstctrl, &prcm->cm_dss_clkstctrl, &prcm->cm_sdma_clkstctrl, 0 }; u32 *const clk_modules_hw_auto_non_essential[] = { &prcm->cm_l3_2_gpmc_clkctrl, &prcm->cm_l3instr_l3_3_clkctrl, &prcm->cm_l3instr_l3_instr_clkctrl, &prcm->cm_l3instr_intrconn_wp1_clkctrl, &prcm->cm_l3init_hsi_clkctrl, &prcm->cm_l3init_hsusbtll_clkctrl, 0 }; u32 *const clk_modules_explicit_en_non_essential[] = { &prcm->cm1_abe_aess_clkctrl, &prcm->cm1_abe_pdm_clkctrl, &prcm->cm1_abe_dmic_clkctrl, &prcm->cm1_abe_mcasp_clkctrl, &prcm->cm1_abe_mcbsp1_clkctrl, &prcm->cm1_abe_mcbsp2_clkctrl, &prcm->cm1_abe_mcbsp3_clkctrl, &prcm->cm1_abe_slimbus_clkctrl, &prcm->cm1_abe_timer5_clkctrl, &prcm->cm1_abe_timer6_clkctrl, &prcm->cm1_abe_timer7_clkctrl, &prcm->cm1_abe_timer8_clkctrl, &prcm->cm1_abe_wdt3_clkctrl, &prcm->cm_l4per_gptimer9_clkctrl, &prcm->cm_l4per_gptimer10_clkctrl, &prcm->cm_l4per_gptimer11_clkctrl, &prcm->cm_l4per_gptimer3_clkctrl, &prcm->cm_l4per_gptimer4_clkctrl, &prcm->cm_l4per_hdq1w_clkctrl, &prcm->cm_l4per_mcbsp4_clkctrl, &prcm->cm_l4per_mcspi2_clkctrl, &prcm->cm_l4per_mcspi3_clkctrl, &prcm->cm_l4per_mcspi4_clkctrl, &prcm->cm_l4per_mmcsd3_clkctrl, &prcm->cm_l4per_mmcsd4_clkctrl, &prcm->cm_l4per_mmcsd5_clkctrl, &prcm->cm_l4per_uart1_clkctrl, &prcm->cm_l4per_uart2_clkctrl, &prcm->cm_l4per_uart4_clkctrl, &prcm->cm_wkup_keyboard_clkctrl, &prcm->cm_wkup_wdtimer2_clkctrl, &prcm->cm_cam_iss_clkctrl, &prcm->cm_cam_fdif_clkctrl, &prcm->cm_dss_dss_clkctrl, &prcm->cm_sgx_sgx_clkctrl, &prcm->cm_l3init_hsusbhost_clkctrl, 0 }; /* Enable optional functional clock for ISS */ setbits_le32(&prcm->cm_cam_iss_clkctrl, ISS_CLKCTRL_OPTFCLKEN_MASK); /* Enable all optional functional clocks of DSS */ setbits_le32(&prcm->cm_dss_dss_clkctrl, DSS_CLKCTRL_OPTFCLKEN_MASK); do_enable_clocks(clk_domains_non_essential, clk_modules_hw_auto_non_essential, clk_modules_explicit_en_non_essential, 0); /* Put camera module in no sleep mode */ clrsetbits_le32(&prcm->cm_cam_clkstctrl, MODULE_CLKCTRL_MODULEMODE_MASK, CD_CLKCTRL_CLKTRCTRL_NO_SLEEP << MODULE_CLKCTRL_MODULEMODE_SHIFT); }
zhanleewo/u-boot-smdk6410
arch/arm/cpu/armv7/omap4/clocks.c
C
gpl-2.0
15,390
/* * Clase: MethodsSplitRules.java * Descripción: Clase en la que se declaran los métodos utilizado en el * programa que extrae la reglas del archivo de salida de * algoritmos de árboles clasificadores. * Fecha de inicio: 25 mayo 2015. */ package splitrulesclassifiertree; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringReader; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTextArea; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author Merino Merino Jesús Fernando * @author Santiago López José Luís */ public class MethodsSplitRules { public void separarReglas(JTextArea jTexArea, String nomArchSalida){ String str; int lin=0; BufferedReader reader = new BufferedReader( new StringReader(jTexArea.getText())); File f; f = new File(nomArchSalida); try { FileWriter w = new FileWriter(f); BufferedWriter bw = new BufferedWriter(w); PrintWriter wr = new PrintWriter(bw); while ((str = reader.readLine()) != null) { if (str.length() > 0 && lin <= 10){ wr.write("R"+(lin+1)+":\n"+str); } lin++; } wr.close(); /*Cerrando archivo de escritura*/ bw.close(); /*Cerrando apertura de archivo*/ JOptionPane.showMessageDialog(null, "La reglas se han extraído correctamente.", "Reglas extraídas", JOptionPane.INFORMATION_MESSAGE); } catch(IOException e) { System.err.println("Error econtrado: "+e.getMessage()); } } public void recorrerTextArea(JTextArea jTexArea, String nomArchSalida){ String str; int lin=0; BufferedReader reader = new BufferedReader( new StringReader(jTexArea.getText())); File f; f = new File(nomArchSalida); try { FileWriter w = new FileWriter(f); BufferedWriter bw = new BufferedWriter(w); PrintWriter wr = new PrintWriter(bw); while ((str = reader.readLine()) != null) { if (str.length() > 0 && lin <= 10){ wr.write("R"+(lin+1)+":\n"+str); } lin++; } wr.close(); /*Cerrando archivo de escritura*/ bw.close(); /*Cerrando apertura de archivo*/ JOptionPane.showMessageDialog(null, "La reglas se han extraído correctamente.", "Reglas extraídas", JOptionPane.INFORMATION_MESSAGE); } catch(IOException e) { System.err.println("Error econtrado: "+e.getMessage()); } } /** * Método que devuelve la ruta de un archivo, sin el nombre del archivo, es * decir, únicamente la ruta. * * @param ruta * @return String */ public String getPathFile(String ruta){ /*Método que devuleve el ruta del archivo abierto sin el nombre del mismo*/ int i; String rutaArch=""; for(i=ruta.length()-1;i>=0;i--){ if(ruta.charAt(i)==System.getProperty("file.separator").charAt(0)){ rutaArch = ruta.substring(0, i); break; } } return rutaArch; } /** * Abre una ventana de dialogo para guardar un archivo. * * @param rutaArch * @return String */ public String getNameFileToSave(String rutaArch){ String nomArchSalida=""; JFileChooser jFGuardar = new JFileChooser() { @Override public void approveSelection() { File f = getSelectedFile(); if (f.exists()) { int result = JOptionPane.showConfirmDialog(null, "¿Reemplazar el archivo existente?", "El archivo ya existe", JOptionPane.YES_NO_CANCEL_OPTION); switch (result) { case JOptionPane.YES_OPTION: super.approveSelection(); return; case JOptionPane.NO_OPTION: return; case JOptionPane.CLOSED_OPTION: cancelSelection(); return; case JOptionPane.CANCEL_OPTION: cancelSelection(); return; } } super.approveSelection(); } }; jFGuardar.setDialogTitle("Guardar en: "+getPathFile(rutaArch)); jFGuardar.setCurrentDirectory(new File(getPathFile(rutaArch))); jFGuardar.setFileFilter(new FileNameExtensionFilter("Archivos de texto (.txt).", "txt")); jFGuardar.setAcceptAllFileFilterUsed(false); jFGuardar.setSelectedFile(new File("Reglas_"+getNameFileFromPath(rutaArch))); int actionDialog = jFGuardar.showSaveDialog(null); if( actionDialog == JFileChooser.APPROVE_OPTION ){ nomArchSalida = jFGuardar.getCurrentDirectory()+System.getProperty("file.separator") +getNameFileWithoutExt(jFGuardar.getSelectedFile().getName())+".txt"; } return nomArchSalida; } /** * Devuelve el nombre del archivo con extensión, pero sin la ruta del mismo. * * @param ruta * @return String */ public String getNameFileFromPath(String ruta){ /*Método que devuleve el nombre del archivo abierto a partir de la ruta completa*/ int i; String nomArch=""; for(i=ruta.length()-1;i>=0;i--){ if(ruta.charAt(i)==System.getProperty("file.separator").charAt(0)){ nomArch = ruta.substring(i+1, ruta.length()); break; } } return nomArch; } /** * Devuelve el nombre del archivo ingresado por el usuario, sin contemplar * la extensión del mismo. * * @param nomArchIngrUser * @return String */ public String getNameFileWithoutExt(String nomArchIngrUser){ /*Método que devuleve el nombre del archivo a guardar sin extensión*/ int i; boolean sinExt = false; String nomArch=""; for(i=nomArchIngrUser.length()-1;i>=0;i--){ if(nomArchIngrUser.charAt(i)=='.'){ nomArch = nomArchIngrUser.substring(0, i); sinExt = true; break; } } if(!sinExt){ nomArch = nomArchIngrUser; } return nomArch; } /** * Abre una ventana de dialogo para abrir un archivo, devulve la ruta y * nombre del archivo que se haya seleccionado. * * @param jFchAbrirArch * @param rutaArch * @return String */ public String openFileWithDialogue(javax.swing.JFileChooser jFchAbrirArch, String rutaArch){ String rutaActualArch = ""; if(rutaArch.equals("")){ jFchAbrirArch.setCurrentDirectory(new File(System.getProperty("user.home"))); jFchAbrirArch.setDialogTitle("Abrir en: "+System.getProperty("user.home")); }else{ rutaActualArch = rutaArch; jFchAbrirArch.setCurrentDirectory(new File(getPathFile(rutaArch))); jFchAbrirArch.setDialogTitle("Abrir en: "+getPathFile(rutaArch)); } jFchAbrirArch.setAcceptAllFileFilterUsed(false); int returnVal = jFchAbrirArch.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = jFchAbrirArch.getSelectedFile(); rutaActualArch = file.getAbsolutePath(); } return rutaActualArch; } /** * Visualiza el contenido del archivo que recibe, en un JTextArea. * * @param mostrarTex * @param rutaArch */ public void addTextToJTextArea(javax.swing.JTextArea mostrarTex, String rutaArch){ File file = new File(rutaArch); try { mostrarTex.read( new FileReader(file.getAbsolutePath()), null); } catch (IOException ex) { System.out.println("Problemas al acceder al archivo "+ex.getMessage()); } } /** * Devuelve el número de líneas que contiene el archivo que recibe. * * @param nombreArch * @return Int */ public int countNumLineFile(String nombreArch){ File fichero = new File(nombreArch); int numLine = 0; try { BufferedReader fich = new BufferedReader(new FileReader(nombreArch)); //Usamos la clase BufferReadeader para tener acceso a un metodo propio (readLine()) y asi mediante un contador contar las lineas. String linea; try { //En este caso la condicion final del while corresponde a null, para indicar el final de linea while((linea = fich.readLine()) != null){ numLine++; } System.out.println("El número de líneas :" + numLine); } catch (IOException e) { System.out.println("Error: "+e.getMessage()); } } catch (FileNotFoundException e) { System.out.println("Error: "+e.getMessage()); } return numLine; } /** * Revisa cada línea del archivo de reglas separada, para encontrar el nivel * máximo que contenga. * * @param archivo * @return Int */ public int getMaxLevelFile(String archivo){ int nivel = 0; try (BufferedReader lee1 = new BufferedReader(new FileReader(archivo))) { String linea; int i = 0; while((linea = lee1.readLine())!=null){ i++; if (linea.charAt(0)=='|'){ if(getLevelString(linea) > nivel){ nivel = getLevelString(linea); } } } }catch(IOException e){ System.out.println("Ha ocurrido un error:"); } return nivel; } /** * Obtiene el nivel desplazado por una regla, contando el número de barras * que contenga la cadena. * * @param cadena * @return Int */ public int getLevelString(String cadena){ int j, nivel=0; for(j=0;j<cadena.length();j++){ if(cadena.charAt(j)=='|'){ nivel++; } } return nivel; } /** * Método que devuelve el número de la línea donde comienzan las reglas en * el archivo. * * @param archivo * @return String */ public int getBeginRuleFile(String archivo){ int numLin=0; try (BufferedReader lee1 = new BufferedReader(new FileReader(archivo))) { String linea; while((linea = lee1.readLine())!=null){ if(linea.length()>0){ if (linea.charAt(0)=='|'){ break; } } numLin++; } }catch(IOException e){ System.err.println("Ha ocurrido un error: "+e.getMessage()); } return numLin-1; } public void deleteFile(String archEliminar){ try { File archAEliminar = new File(archEliminar); archAEliminar.delete(); } catch (Exception e) { System.out.println("Error: "+e.getMessage()); } // end try } // end Eliminar /** * Método que devuelve una variable boolean verdadera, cuando el archivo a * cumple con ciertas características que se pide para ser un archivo de * resultados de algoritmos clasificadores. * * @param directorio * @return boolean verdadero si el archivo es válido, falso en caso contrario */ public boolean validateFileBeforeOpen(String directorio) { String anterior; String actual=""; int cont=0; boolean band=false; File archivo; FileReader fr = null; BufferedReader br; try { // Apertura del fichero y creacion de BufferedReader para poder // hacer una lectura comoda (disponer del metodo readLine()). archivo = new File (directorio); fr = new FileReader (archivo); br = new BufferedReader(fr); // Lectura del fichero String linea; while((linea=br.readLine())!=null && band!=true){ if(cont==0){ actual=linea; cont++; }else{ anterior=actual; actual=linea; if(anterior.length()!=0 && actual.length()!=0){ band = compareStrings(anterior, actual); } } } } catch(Exception e){ System.err.println("Error: "+e.getMessage()); }finally{ // En el finally cerramos el fichero, para asegurarnos // que se cierra tanto si todo va bien como si salta // una excepcion. try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ System.err.println("Error: "+e2.getMessage()); } } return band; } /** * Método que compara dos cadenas, la primera cadena en su posición 0 debe ser * letra y la segunda en su posición 0 debe ser barra '|' para que el método * retorne verdadero. * * @param c1 * @param c2 * @return booleano */ public boolean compareStrings(String c1, String c2){ boolean band=false; int s1, s2; s1=c1.charAt(0); s2=c2.charAt(0); if(Character.isLetter(s1)){ if(s2=='|'){ band=true; } } return band; } /** * Método que separa el conjunto de reglas del archivo original, creando un * archivo temporal en la misma ruta en la que se encuentra el archivo * original. * * @param rutaArchOrig * @param numLine */ public void createTempFileRules(String rutaArchOrig, int numLine) { int cont=0; boolean band=true; String cadena=""; File archivo; FileReader fr; BufferedReader br; File archTemp; archTemp = new File(getPathFile(rutaArchOrig)+System.getProperty("file.separator")+"tempRules.txt"); try { // Apertura del fichero y creacion de BufferedReader para poder // hacer una lectura comoda (disponer del metodo readLine()). archivo = new File(rutaArchOrig); fr = new FileReader(archivo); br = new BufferedReader(fr); // Lectura del fichero String linea; FileWriter fwArchTemp = new FileWriter(archTemp); BufferedWriter bwArchTemp; bwArchTemp = new BufferedWriter(fwArchTemp); try (PrintWriter wrArchTemp = new PrintWriter(bwArchTemp)) { while((linea=br.readLine())!=null && band!=false){ //Creación del archivo temporal if(cont>=numLine){ if(linea.length()!=0){ wrArchTemp.println(""+linea); }else{ band=false; } } cont++; } wrArchTemp.close(); /*Cerrando archivo de escritura*/ } bwArchTemp.close(); /*Cerrando apertura de archivo*/ fr.close(); br.close(); System.out.println("Archivo temporal creado..."); } catch(Exception e){ System.err.println("Error: "+e.getMessage()); } } /** * Define arreglos para almacenar los niveles, el nombre, signo terminal y * el estado de cada línea del archivo. * * @param fileRuta * @param pathFileOpen * @param nomArchSalida */ public void crearMatrizNivel(String fileRuta, String pathFileOpen, String nomArchSalida){ //NUMERO DE LINEAS DEL ARCHIVO int longitud = countNumLineFile(fileRuta); //INDICE DE LINEA ACTUAL int cont = 0; //VECTOR DE NIVEL DE LINEA 0 - 1 - 2 - 3 -...-N int[] nivel = new int[longitud]; //VECTOR DE STRING DE LINEAS DEL ARCHIVO SIN "|" String[] cadena = new String[longitud]; //VECTOR DE STRING "NUM" O ")" SEGÚN SEA EL CASO String[] signoTerminal = new String[longitud]; //VECTOR QUE LLEVA EL CONTROL DE CONDICIONES ACOMPLETADAS int[] control = new int[longitud]; //BANDERA PARA EL CONTROL DE LINEAS NO VACIAS boolean band = false; File archivo = null; FileReader fr = null; BufferedReader br = null; try { // Apertura del fichero y creacion de BufferedReader para poder // hacer una lectura comoda (disponer del metodo readLine()). archivo = new File (fileRuta); fr = new FileReader (archivo); br = new BufferedReader(fr); // Lectura del fichero String linea; while((linea=br.readLine())!=null && band!=true){ if(linea.length()!=0){ asignarValor(linea, nivel, cadena, signoTerminal, control, cont); cont++; }else{ band=true; } } } catch(Exception e){ System.err.println(e.getMessage()); }finally{ try{ if( null != fr ){ fr.close(); } }catch (Exception e2){ System.err.println(e2.getMessage()); } } //MÉTODO QUE OBTIENE LAS CONDICIONES obtenerCondiciones(nivel, cadena, signoTerminal, control, longitud, nomArchSalida, pathFileOpen); } /** * Método que inicia el proceso de invoación a otros vectores. * * @param line * @param control * @param vec * @param cad * @param signo * @param posicion */ public void asignarValor(String line, int vec[], String cad[], String signo[], int control[], int posicion){ //SE DEFINE EL NIVEL DE LINEA vec[posicion]=getLevelString(line); //SE ELIMINAN LAS "|" DE LA LINEA cad[posicion]=quitarBarra(line); //SE DEFINE SI ES NUMERO O PARENTESIS signo[posicion]=signoFinal(line); //SE ASIGNA UN 0 AL ARRAY CONTROL, PUESTO QUE NO //A SIDO UTILIZADA DICHA POSICIÓN DEL ARCHIVO control[posicion]=0; } /** * Elimina las barras de cada línea y asigna la cadena a un arreglo de * cadenas. * * @param cad * @return String */ public String quitarBarra(String cad){ String newCad=""; for(int i=0; i<cad.length(); i++){ if(cad.charAt(i)!='|' && cad.charAt(i)!=' '){ newCad=newCad+cad.charAt(i); } } return newCad; } /** * Asigna un símbolo "N" o ")" al arreglo de cadenas para indicar. * * @param cad * @return String */ public String signoFinal(String cad){ String signo = ""; if(cad.charAt(cad.length()-1)==')'){ signo = ")"; }else{ signo = "N"; } return signo; } /** * Análisis y obtención de condiciones * * @param nivel * @param cadena * @param signoTerminal * @param control * @param longitud * @param pathFileOpen * @param nomArchSalida */ public void obtenerCondiciones(int nivel[], String cadena[], String signoTerminal[], int control[], int longitud, String nomArchSalida, String pathFileOpen){ //VARIABLES PARA CREAR Y ESCRIBIR EN UN ARCHIVO FileWriter fichero = null; PrintWriter pw; //CADENA QUE CONCATENA LA CONDICION, LA GUARDA EN EL ARCHIVO //Y LIMPIA SU CONTENIDO String condicion; //CONTROL DEL NIVEL DONDE SE ENCONTRO EL SIGNO ")" int nivelCondition; //SI SE LLEGA AL NIVEL 0, ENTONCES LA BANDERA CAMBIARÁ A TRUE Y //TERMINA EL CICLO DE REGRESIÓN boolean band=false; //INDICE DEL NÚMERO DE REGLA int rule=0; //INTENTA CREAR Y ESCRIBIR EN EL ARCHIVO try { //CREA UN NUEVO ARCHIVO CON EL NOMBRE ENCONTRADO EN LA VARIABLE //nonArchSalida fichero = new FileWriter(nomArchSalida); //CREA UN OBJETO PARA REALIZAR LA ESCRITURA EN EL ARCHIVO pw = new PrintWriter(fichero); //SE ESCRIBE UN TÍTULO DENTRO DEL ARCHIVO pw.println("== Run Information ==\n" + "Rules get from file: "+pathFileOpen+"\n" + "Num of rules: "+getNumberRules(signoTerminal, longitud)); pw.println("\n*** Set of conditions ***\n"); //RECORRE EL ARREGLO signoTerminal[i] for(int i=0; i<longitud; i++){ //VERIFICA SI EXISTE UN SIGNO TERMINAL ")" if(signoTerminal[i].equals(")")){ //INICIALIZA EN CADENA VACIA LA VARIABLE condicion condicion = ""; //SI LA POSICIÓN i DEL VECTOR SIGNO ")" ES 0 //QUIERE DECIR QUE NO SE HA HECHO LA CONDICIÓN if(control[i]!=1){ //En proceso de actualización } } } JOptionPane.showMessageDialog(null, "El archivo de reglas ha sido exportado satisfactoriamente.", "Reglas exportadas", JOptionPane.INFORMATION_MESSAGE); }catch (Exception e) { System.out.println(e.getMessage()); } finally { try { if (null != fichero) fichero.close(); } catch (Exception e2) { System.out.println(e2.getMessage()); } } } /** * Método para obtener el número de condiciones del archivo. * * @param signo * @param longitud * @return Int */ public int getNumberRules(String signo[], int longitud){ int numConditions=0; for(int i=0; i<longitud; i++){ if(signo[i].equals(")")){ numConditions++; } } return numConditions; } /** * Método para obtener solo la condicion y no la clase X * * @param cadena * @return String */ public String getCondicion(String cadena){ String condicion=""; boolean band=false; for(int i=0; i<cadena.length() && band!=true; i++){ if(cadena.charAt(i)!=':'){ condicion=condicion+cadena.charAt(i); }else{ band=true; } } return condicion; } /** * Método para obtener solamente la clase X y no la condición. * * @param cadena * @return String */ public String getClase(String cadena){ String clase=""; boolean bandCp = true; if(getPosCharacter(cadena, "/")==-1){ String antCad = cadena.substring(getPosCharacter(cadena, ":")+1, getPosCharacter(cadena, "(")+1); String contCad = cadena.substring(getPosCharacter(cadena, "(")+1, cadena.length()-3); double entero = Double.parseDouble(contCad); int ent = (int) getCifraRedon(entero, 1); clase = antCad + Integer.toString(ent) + ")"; }else{ String antCad = cadena.substring(getPosCharacter(cadena, ":")+1, getPosCharacter(cadena, "(")+1); String priNum = cadena.substring(getPosCharacter(cadena, "(")+1, getPosCharacter(cadena, "/")); String segNum = cadena.substring(getPosCharacter(cadena, "/")+1, cadena.length()-3); double num1 = Double.parseDouble(priNum); double num2 = Double.parseDouble(segNum); clase = antCad+Integer.toString(getConvDouToInt(getCifraRedon(num1, 1)))+ "/"+Integer.toString(getConvDouToInt(getCifraRedon(num2, 1)))+")"; } /* for(int i=0; i<cadena.length(); i++){ if(cadena.charAt(i)=='.'){ bandCp = false; } if(cadena.charAt(i)=='/' || cadena.charAt(i)==')' ){ bandCp = true; } if(bandCp){ clase=clase+cadena.charAt(i); } }*/ return clase; } public int getConvDouToInt(double numero){ return (int) numero; } public double getCifraRedon(double numero, int deciRed){ int cifras=(int) Math.pow(10,0); return Math.rint(numero*cifras)/cifras; } public int getPosCharacter(String cadena, String sim){ int i, pos=-1; for(i=0;i<cadena.length();i++){ if(cadena.charAt(i)==sim.charAt(0)){ pos = i; break; } } return pos; } }
jesusferm/SplitRules
src/splitrulesclassifiertree/MethodsSplitRules.java
Java
gpl-2.0
25,899
/* Title: Advanced Ray Tracer File Name: Main.cpp Copyright © 2015 Original authors: Brockton Roth Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. 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/>. References: https://github.com/LWJGL/lwjgl3-wiki/wiki/2.6.1.-Ray-tracing-with-OpenGL-Compute-Shaders-(Part-I) Description: This program serves to demonstrate the concept of ray tracing. This builds off a previous Intermediate Ray Tracer, adding in reflections. There are four point lights, specular and diffuse lighting, and shadows. It is important to note that the light positions and triangles being rendered are all hardcoded in the shader itself. Usually, you would pass those values into the Fragment Shader via a Uniform Buffer. WARNING: Framerate may suffer depending on your hardware. This is a normal problem with Ray Tracing. If it runs too slowly, try removing the second cube from the triangles array in the Fragment Shader (and also adjusting NUM_TRIANGLES accordingly). There are many optimization techniques out there, but ultimately Ray Tracing is not typically used for Real-Time rendering. */ #include "glew\glew.h" #include "glfw\glfw3.h" #include "glm\glm.hpp" #include "glm\gtc\matrix_transform.hpp" #include "glm\gtc\type_ptr.hpp" #include <iostream> #include <string> #include <fstream> #include <vector> // This is your reference to your shader program. // This will be assigned with glCreateProgram(). // This program will run on your GPU. GLuint program; // These are your references to your actual compiled shaders GLuint vertex_shader; GLuint fragment_shader; // These are your uniform variables. GLuint eye; // Specifies camera location // The rays are the four corner rays of the camera view. See: https://camo.githubusercontent.com/21a84a8b21d6a4bc98b9992e8eaeb7d7acb1185d/687474703a2f2f63646e2e6c776a676c2e6f72672f7475746f7269616c732f3134313230385f676c736c5f636f6d707574652f726179696e746572706f6c6174696f6e2e706e67 GLuint ray00; GLuint ray01; GLuint ray10; GLuint ray11; // A variable used to describe the position of the camera. glm::vec3 cameraPos; // A reference to your Vertex Buffer Object, Vertex Array Object, Shader Storage Buffer Object, and the uniform float for radius in your compute shader. GLuint vbo; GLuint vao; // A reference to our window. GLFWwindow* window; // Variables you will need to calculate FPS. int frame; double time; double timebase; int fps; // This function takes in variables that define the perspective view of the camera, then outputs the four corner rays of the camera's view. // It takes in a vec3 eye, which is the position of the camera. // It also takes vec3 center, the position the camera's view is centered on. // Then it will takes a vec3 up which is a vector that defines the upward direction. (So if you point it down, the camera view will be upside down.) // Then it takes a float defining the verticle field of view angle. It also takes a float defining the ratio of the screen (in this case, 800/600 pixels). // The last four parameters are actually just variables for this function to output data into. They should be pointers to pre-defined vec4 variables. // For a visual reference, see this image: https://camo.githubusercontent.com/21a84a8b21d6a4bc98b9992e8eaeb7d7acb1185d/687474703a2f2f63646e2e6c776a676c2e6f72672f7475746f7269616c732f3134313230385f676c736c5f636f6d707574652f726179696e746572706f6c6174696f6e2e706e67 void calcCameraRays(glm::vec3 eye, glm::vec3 center, glm::vec3 up, float fov, float ratio, glm::vec4* r00, glm::vec4* r01, glm::vec4* r10, glm::vec4* r11) { // Grab a ray from the camera position toward where the camera is to be centered on. glm::vec3 centerRay = center - eye; // w: Vector from center toward eye // u: Vector pointing directly right relative to the camera. // v: Vector pointing directly upward relative to the camera. // Create a w vector which is the opposite of that ray. glm::vec3 w = -centerRay; // Get the rightward (relative to camera) pointing vector by crossing up with w. glm::vec3 u = glm::cross(up, w); // Get the upward (relative to camera) pointing vector by crossing the rightward vector with your w vector. glm::vec3 v = glm::cross(w, u); // Each ray starts based off of the center ray. Then we will rotate them over the *r00 = glm::vec4(centerRay, 1.0f); *r01 = *r00; *r10 = *r00; *r11 = *r00; // We create these two helper variables, as when we rotate the ray about it's relative Y axis (v), we will then need to rotate it about it's relative X axis (u). // This means that u has to be rotated by v too, otherwise the rotation will not be accurate. When the ray is rotated about v, so then are it's relative axes. glm::vec4 uRotateLeft = glm::vec4(u, 1.0f) * glm::rotate(glm::mat4(), glm::radians(-fov * ratio / 2.0f), v); glm::vec4 uRotateRight = glm::vec4(u, 1.0f) * glm::rotate(glm::mat4(), glm::radians(fov * ratio / 2.0f), v); // Now we simply take the ray and rotate it in each direction to create our four corner rays. *r00 = *r00 * glm::rotate(glm::mat4(), glm::radians(-fov * ratio / 2.0f), v) * glm::rotate(glm::mat4(), glm::radians(fov / 2.0f), glm::vec3(uRotateLeft.x, uRotateLeft.y, uRotateLeft.z)); *r01 = *r01 * glm::rotate(glm::mat4(), glm::radians(-fov * ratio / 2.0f), v) * glm::rotate(glm::mat4(), glm::radians(-fov / 2.0f), glm::vec3(uRotateLeft.x, uRotateLeft.y, uRotateLeft.z)); *r10 = *r10 * glm::rotate(glm::mat4(), glm::radians(fov * ratio / 2.0f), v) * glm::rotate(glm::mat4(), glm::radians(fov / 2.0f), glm::vec3(uRotateRight.x, uRotateRight.y, uRotateRight.z)); *r11 = *r11 * glm::rotate(glm::mat4(), glm::radians(fov * ratio / 2.0f), v) * glm::rotate(glm::mat4(), glm::radians(-fov / 2.0f), glm::vec3(uRotateRight.x, uRotateRight.y, uRotateRight.z)); } // This runs once a frame, before renderScene void update() { // Used for FPS time = glfwGetTime(); // Every second, basically. if (time - timebase > 1) { // Calculate the FPS and set the window title to display it. fps = frame / (time - timebase); timebase = time; frame = 0; std::string s = "FPS: " + std::to_string(fps); glfwSetWindowTitle(window, s.c_str()); } // For rotating the camera, we convert it to a vec4 and then do a rotation about the Y axis. glm::vec4 tempPos = glm::vec4(cameraPos, 1.0f) * glm::rotate(glm::mat4(1.0f), glm::radians(1.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Then we convert back to a vec3. cameraPos = glm::vec3(tempPos.x, tempPos.y, tempPos.z); // These are our four corner ray variables. glm::vec4 r00; glm::vec4 r01; glm::vec4 r10; glm::vec4 r11; // Call the function we created to calculate the corner rays. calcCameraRays(cameraPos, glm::vec3(0.0f, 0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), 60.0f, 800.0f / 600.0f, &r00, &r01, &r10, &r11); // Now set the uniform variables in the shader to match our camera variables (cameraPos = eye, then four corner rays) glUniform3f(eye, cameraPos.x, cameraPos.y, cameraPos.z); glUniform3f(ray00, r00.x, r00.y, r00.z); glUniform3f(ray01, r01.x, r01.y, r01.z); glUniform3f(ray10, r10.x, r10.y, r10.z); glUniform3f(ray11, r11.x, r11.y, r11.z); } // This function runs every frame void renderScene() { // Clear the color buffer and the depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the screen to black glClearColor(0.0, 0.0, 0.0, 1.0); // Bind the vao glBindVertexArray(vao); // Draw 4 vertices from the buffer as GL_TRIANGLE_FAN which will draw triangles fanning out from the first vertex. // There are several different drawing modes, GL_TRIANGLES takes every 3 vertices and makes them a triangle. // For reference, GL_TRIANGLE_STRIP would take each additional vertex after the first 3 and consider that a // triangle with the previous 2 vertices (so you could make 2 triangles with 4 vertices, 3 with 5, etc.) // The second parameter is the start index of the array, and the third parameter is the number of vertices to draw. glDrawArrays(GL_TRIANGLE_FAN, 0, 4); // In this case, we are drawing 4 vertices because that will draw a flat quad. With Ray Tracing, the Fragment Shader will do most of the work, drawing every pixel // by tracing a ray. } // This method reads the text from a file. // Realistically, we wouldn't want plain text shaders hardcoded in, we'd rather read them in from a separate file so that the shader code is separated. std::string readShader(std::string fileName) { std::string shaderCode; std::string line; // We choose ifstream and std::ios::in because we are opening the file for input into our program. // If we were writing to the file, we would use ofstream and std::ios::out. std::ifstream file(fileName, std::ios::in); // This checks to make sure that we didn't encounter any errors when getting the file. if (!file.good()) { std::cout << "Can't read file: " << fileName.data() << std::endl; // Return so we don't error out. return ""; } // ifstream keeps an internal "get" position determining the location of the element to be read next // seekg allows you to modify this location, and tellg allows you to get this location // This location is stored as a streampos member type, and the parameters passed in must be of this type as well // seekg parameters are (offset, direction) or you can just use an absolute (position). // The offset parameter is of the type streamoff, and the direction is of the type seekdir (an enum which can be ios::beg, ios::cur, or ios::end referring to the beginning, // current position, or end of the stream). file.seekg(0, std::ios::end); // Moves the "get" position to the end of the file. shaderCode.resize((unsigned int)file.tellg()); // Resizes the shaderCode string to the size of the file being read, given that tellg will give the current "get" which is at the end of the file. file.seekg(0, std::ios::beg); // Moves the "get" position to the start of the file. // File streams contain two member functions for reading and writing binary data (read, write). The read function belongs to ifstream, and the write function belongs to ofstream. // The parameters are (memoryBlock, size) where memoryBlock is of type char* and represents the address of an array of bytes are to be read from/written to. // The size parameter is an integer that determines the number of characters to be read/written from/to the memory block. file.read(&shaderCode[0], shaderCode.size()); // Reads from the file (starting at the "get" position which is currently at the start of the file) and writes that data to the beginning // of the shaderCode variable, up until the full size of shaderCode. This is done with binary data, which is why we must ensure that the sizes are all correct. file.close(); // Now that we're done, close the file and return the shaderCode. return shaderCode; } // This method will consolidate some of the shader code we've written to return a GLuint to the compiled shader. // It only requires the shader source code and the shader type. GLuint createShader(std::string sourceCode, GLenum shaderType) { // glCreateShader, creates a shader given a type (such as GL_VERTEX_SHADER) and returns a GLuint reference to that shader. GLuint shader = glCreateShader(shaderType); const char *shader_code_ptr = sourceCode.c_str(); // We establish a pointer to our shader code string const int shader_code_size = sourceCode.size(); // And we get the size of that string. // glShaderSource replaces the source code in a shader object // It takes the reference to the shader (a GLuint), a count of the number of elements in the string array (in case you're passing in multiple strings), a pointer to the string array // that contains your source code, and a size variable determining the length of the array. glShaderSource(shader, 1, &shader_code_ptr, &shader_code_size); glCompileShader(shader); // This just compiles the shader, given the source code. GLint isCompiled = 0; // Check the compile status to see if the shader compiled correctly. glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled); if (isCompiled == GL_FALSE) { char infolog[1024]; glGetShaderInfoLog(shader, 1024, NULL, infolog); // Print the compile error. std::cout << "The shader failed to compile with the error:" << std::endl << infolog << std::endl; // Provide the infolog in whatever manor you deem best. // Exit with failure. glDeleteShader(shader); // Don't leak the shader. // NOTE: I almost always put a break point here, so that instead of the program continuing with a deleted/failed shader, it stops and gives me a chance to look at what may // have gone wrong. You can check the console output to see what the error was, and usually that will point you in the right direction. } return shader; } // Initialization code void init() { glewExperimental = GL_TRUE; // Initializes the glew library glewInit(); // Read in the shader code from a file. std::string vertShader = readShader("VertexShader.glsl"); std::string fragShader = readShader("FragmentShader.glsl"); // createShader consolidates all of the shader compilation code vertex_shader = createShader(vertShader, GL_VERTEX_SHADER); fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER); // A shader is a program that runs on your GPU instead of your CPU. In this sense, OpenGL refers to your groups of shaders as "programs". // Using glCreateProgram creates a shader program and returns a GLuint reference to it. program = glCreateProgram(); glAttachShader(program, vertex_shader); // This attaches our vertex shader to our program. glAttachShader(program, fragment_shader); // This attaches our fragment shader to our program. // This links the program, using the vertex and fragment shaders to create executables to run on the GPU. glLinkProgram(program); // End of shader and program creation // Tell our code to use the program glUseProgram(program); // Enables the depth test, which you will want in most cases. You can disable this in the render loop if you need to. glEnable(GL_DEPTH_TEST); // We are drawing a quad, what this means is that we're drawing two triangles to create a rectangle that covers the entire view area. // Thus, we're only passing in 4 vertices in a triangle fan to the vertex shader. It will then call the pixel shader and draw the pixel at it's appropriate coordinate. glm::vec2 quadVerts[4]; quadVerts[0] = glm::vec2(1.0, -1.0); quadVerts[1] = glm::vec2(-1.0, -1.0); quadVerts[2] = glm::vec2(-1.0, 1.0); quadVerts[3] = glm::vec2(1.0, 1.0); // No reason to bother with a Z parameter, as the quad will fill up the entire screen, facing the camera directly, making depth irrelevant. // Generate your vertex array object name. glGenVertexArrays(1, &vao); // Bind the vertex array object glBindVertexArray(vao); // This generates buffer object names // The first parameter is the number of buffer objects, and the second parameter is a pointer to an array of buffer objects (yes, before this call, vbo was an empty variable) // (In this example, there's only one buffer object.) glGenBuffers(1, &vbo); // Binds a named buffer object to the specified buffer binding point. Give it a target (GL_ARRAY_BUFFER) to determine where to bind the buffer. // There are several different target parameters, GL_ARRAY_BUFFER is for vertex attributes, feel free to Google the others to find out what else there is. // The second paramter is the buffer object reference. If no buffer object with the given name exists, it will create one. // Buffer object names are unsigned integers (like vbo). Zero is a reserved value, and there is no default buffer for each target (targets, like GL_ARRAY_BUFFER). // Passing in zero as the buffer name (second parameter) will result in unbinding any buffer bound to that target, and frees up the memory. glBindBuffer(GL_ARRAY_BUFFER, vbo); // Creates and initializes a buffer object's data. // First parameter is the target, second parameter is the size of the buffer, third parameter is a pointer to the data that will copied into the buffer, and fourth parameter is the // expected usage pattern of the data. Possible usage patterns: GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, // GL_DYNAMIC_READ, or GL_DYNAMIC_COPY // Stream means that the data will be modified once, and used only a few times at most. Static means that the data will be modified once, and used a lot. Dynamic means that the data // will be modified repeatedly, and used a lot. Draw means that the data is modified by the application, and used as a source for GL drawing. Read means the data is modified by // reading data from GL, and used to return that data when queried by the application. Copy means that the data is modified by reading from the GL, and used as a source for drawing. glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 4, &quadVerts[0], GL_STATIC_DRAW); // GL_ARRAY_BUFFER is for vertices in an array, all drawing commands of glDrawArrays will use vertices from that buffer. // By default, all client-side capabilities are disabled, including all generic vertex attribute arrays. // When enabled, the values in a generic vertex attribute array will be accessed and used for rendering when calls are made to vertex array commands (like glDrawArrays/glDrawElements) // A GL_INVALID_VALUE will be generated if the index parameter is greater than or equal to GL_MAX_VERTEX_ATTRIBS glEnableVertexAttribArray(0); // Defines an array of generic vertex attribute data. Takes an index, a size specifying the number of components (in this case, floats)(has a max of 4) // The third parameter, type, can be GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, or GL_FLOAT // The fourth parameter specifies whether to normalize fixed-point data values, the fifth parameter is the stride which is the offset (in bytes) between generic vertex attributes // The fifth parameter is a pointer to the first component of the first generic vertex attribute in the array. If a named buffer object is bound to GL_ARRAY_BUFFER (and it is, in this case) // then the pointer parameter is treated as a byte offset into the buffer object's data. glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)0); // You'll note sizeof(glm::vec2) is our stride, because each vertex is that size. // This gets us a reference to the uniform variables in the vertex shader, which are called by the same name here as in the shader. // We're using these variables to define the camera. The eye is the camera position, and teh rays are the four corner rays of what the camera sees. // Only 2 parameters required: A reference to the shader program and the name of the uniform variable within the shader code. eye = glGetUniformLocation(program, "eye"); ray00 = glGetUniformLocation(program, "ray00"); ray01 = glGetUniformLocation(program, "ray01"); ray10 = glGetUniformLocation(program, "ray10"); ray11 = glGetUniformLocation(program, "ray11"); // This is where we'll set up our camera location at. cameraPos = glm::vec3(4.0f, 8.0f, 8.0f); // These are four corner ray variables to store the output from our calcCameraRays function. glm::vec4 r00; glm::vec4 r01; glm::vec4 r10; glm::vec4 r11; // Call our function to calculate the four corner rays. We're choosing to make the point the camera centeras on at 0, 0.5, 0. // Our FoV angle is 60 degrees and our ratio is 800/600 which is just the pixel ratio. calcCameraRays(cameraPos, glm::vec3(0.0f, 0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), 60.0f, 800.0f/600.0f, &r00, &r01, &r10, &r11); // Now set the uniform variables in the shader to match our camera variables (cameraPos = eye, then four corner rays) glUniform3f(eye, cameraPos.x, cameraPos.y, cameraPos.z); glUniform3f(ray00, r00.x, r00.y, r00.z); glUniform3f(ray01, r01.x, r01.y, r01.z); glUniform3f(ray10, r10.x, r10.y, r10.z); glUniform3f(ray11, r11.x, r11.y, r11.z); // This is not necessary, but I prefer to handle my vertices in the clockwise order. glFrontFace defines which face of the triangles you're drawing is the front. // Essentially, if you draw your vertices in counter-clockwise order, by default (in OpenGL) the front face will be facing you/the screen. If you draw them clockwise, the front face // will face away from you. By passing in GL_CW to this function, we are saying the opposite, and now the front face will face you if you draw in the clockwise order. // If you don't use this, just reverse the order of the vertices in your array when you define them so that you draw the points in a counter-clockwise order. glFrontFace(GL_CW); } int main(int argc, char **argv) { // FPS variables. frame = 0; time = 0.0; timebase = 0.0; fps = 0; // Initializes the GLFW library glfwInit(); // Creates a window given (width, height, title, monitorPtr, windowPtr). // Don't worry about the last two, as they have to do with controlling which monitor to display on and having a reference to other windows. Leaving them as nullptr is fine. window = glfwCreateWindow(800, 600, "Basic Ray Tracer", nullptr, nullptr); // Makes the OpenGL context current for the created window. glfwMakeContextCurrent(window); // Sets the number of screen updates to wait before swapping the buffers. glfwSwapInterval(1); // Initializes most things needed before the main loop init(); // Enter the main loop. while (!glfwWindowShouldClose(window)) { // Call to the update function; should always be before rendering. update(); // Call the render function. renderScene(); // Swaps the back buffer to the front buffer // Remember, you're rendering to the back buffer, then once rendering is complete, you're moving the back buffer to the front so it can be displayed. glfwSwapBuffers(window); frame++; // For framerate checking. // Checks to see if any events are pending and then processes them. glfwPollEvents(); } // After the program is over, cleanup your data! glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); glDeleteProgram(program); // Note: If at any point you stop using a "program" or shaders, you should free the data up then and there. glDeleteBuffers(1, &vbo); glDeleteVertexArrays(1, &vao); // Frees up GLFW memory glfwTerminate(); return 0; }
MrNex/Game-Programming-Examples
GLFW/Intro to Graphics/AdvancedRayTracer/AdvancedRayTracer/Main.cpp
C++
gpl-2.0
23,175
<!DOCTYPE html> <html> <head> <!-- CSS --> <link rel="stylesheet" href="/assets/css/main.css"> <title> L33t H4ck3r Login &middot; Michael's Normcore Blog </title> <!-- Metadata --> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True" /> <meta name="MobileOptimized" content="320" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" href="/favicon.png"> <!-- Theme Color for Chrome on Android Lollipop --> <meta name="theme-color" content="#52be80"> </head> <body> <!-- Header --> <div class="animated fadeIn top-level-header "> </div> <div class="header-image" style="background-image: url(' /assets/images/cover.jpg ');"> &nbsp; </div> <div class="toplevel-content"> <div class="container"> <div class="middle top-menu"> <a class="menu-item fadeInDown animated" href="/">blog</a> <a class="menu-item fadeInDown animated" href="/tags">archive</a> <a class="menu-item fadeInDown animated" href="/portfolio">projects</a> <a class="menu-item fadeInDown animated" href="/about">me</a> </div> <div class="middle"> <div class="article animated fadeIn "> <div class="post-title-container"> <h1 class="post-title"><b>L33t H4ck3r Login</b></h1> <p></p> <div class="post-list-tags"> <a href="/tag/code"> <span class="tag new badge">code</span> </a> <a href="/tag/funny"> <span class="tag new badge">funny</span> </a> </div> </div> <p>Everyone wants to be a hacker these days, but to be truly l33t, you gotta have a cool retro setup from boot time to shut down. So during finals I decided to make a login theme that accurately captures what it would be like if <a href="https://en.wikipedia.org/wiki/Johnny_Mnemonic_(film)">Johnny Mnemonic</a> owned my laptop.</p> <p>I use <code class="highlighter-rouge">lightdm</code>, and since <a href="https://www.youtube.com/watch?v=FQM5fU7V-MM">old habits die hard</a> I decided to poke around and see how to make a login theme for it. Since it was <em>finals week</em> I didn’t want to waste time learning GTK or SDL, and luckily I found <code class="highlighter-rouge">lightdm-webkit2-greeter</code> on the <a href="https://aur.archlinux.org/packages/lightdm-webkit2-greeter/">AUR</a>. After a little bit of being locked out of my desktop, I finally got it:</p> <div class="article-img"> <div class="center"> <a href="/media/2016-01-31-hackerz/hackerz-demo.gif" target="_blank"> <img src="/media/2016-01-31-hackerz/hackerz-demo.gif" alt="My new computer login screen!" /> </a> </div> <blockquote style="border-left: 10px solid #D5D5D5;">My new computer login screen!</blockquote> </div> <p>All the code is available on its <a href="https://github.com/illegalprime/hackerz">github repo</a>. To set this up all you need to do is install this greeter, edit <code class="highlighter-rouge">/etc/lightdm/lightdm.conf</code> to contain:</p> <div class="language-ini highlighter-rouge"><pre class="highlight"><code><span class="nn">[Seat:*]</span> <span class="py">greeter-session</span> <span class="p">=</span> <span class="s">lightdm-webkit2-greeter</span> </code></pre> </div> <p>Place the theme in the themes folder for this greeter,</p> <div class="language-bash highlighter-rouge"><pre class="highlight"><code>git clone <span class="s1">'https://github.com/illegalprime/hackerz.git'</span> /usr/share/lightdm-webkit/themes/hackerz </code></pre> </div> <p>and finally edit <code class="highlighter-rouge">/etc/lightdm/lightdm-webkit2-greeter.conf</code>:</p> <div class="language-ini highlighter-rouge"><pre class="highlight"><code><span class="nn">[greeter]</span> <span class="py">webkit-theme</span> <span class="p">=</span> <span class="s">hackerz</span> </code></pre> </div> <p>If you want to make your own cool theme, there’s not much docs out there, but you can take a look at <a href="https://github.com/illegalprime/hackerz">my code</a> for some guidance, if the API is still the same when you’re reading this.</p> <br/> <div class="post-footer"> <p> — Michael </p> <div class="social"> <a href="/feed.xml"><i class="fa fa-rss" aria-hidden="true"></i></a> <a href="https://github.com/illegalprime/"> <i class="fa fa-github" aria-hidden="true"></i> </a> <a href="https://matrix.to/#/@illegalprime:matrix.org"> <i class="fa fa-comments" aria-hidden="true"></i> </a> </div> </div> <hr> <br/> <!-- Disqus Comments Box --> <h2><b>Say It Loud! Leave a comment below:</b></h2> <div id="disqus_thread"></div> <script> var disqus_config = function () { this.page.url = "https://oddoreden.com/2016/01/31/hackerz/"; this.page.identifier = "_2016_01_31_hackerz_"; }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//icanteden.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Enable JavaScript to view comments.</noscript> </div> </div> </div> </div> <footer> </footer> </body> </html>
illegalprime/illegalprime.github.io
2016/01/31/hackerz/index.html
HTML
gpl-2.0
5,742
<{include file="db:xcgal_header.html"}> <table align="center" width="100%" cellspacing="1" cellpadding="0" class="outer"> <tr> <th colspan="7"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="statlink"><b><a href="index.php"><{$gallery}></a> &gt; <a href="<{$thumb_tgt}>" title="<{$album_title}>"><{$album_title}></a>&nbsp;</b></span></td> </tr> </table> </th> </tr> <tr> <th align="center" valign="middle" class="navmenu" width="48"> <a href="<{$thumb_tgt}>" class="navmenu_pic" title="<{$thumb_title}>"><img src="images/folder.gif" width="16" height="16" align="middle" border="0" alt="<{$thumb_title}>"/></a> </th> <th align="center" valign="middle" class="navmenu" width="48"> <a href="javascript:;" onClick="blocking('picinfo','yes', 'block'); return false;" title="<{$pic_info_title}>"><img src="images/info.gif" width="16" height="16" border="0" align="middle" alt="<{$pic_info_title}>"/></a> </th> <th align="center" valign="middle" class="navmenu" width="48"> <a href="<{$slideshow_tgt}>" title="<{$slideshow_title}>"><img src="images/slideshow.gif" width="16" height="16" border="0" align="middle" alt="<{$slideshow_title}>"/></a> </th> <th align="center" valign="middle" class="navmenu"> <{$pic_pos}> </th> <th align="center" valign="middle" class="navmenu" width="48"> <a href="<{$ecard_tgt}>" title="<{$ecard_title}>"><img src="images/ecard.gif" width="16" height="16" border="0" align="middle" alt="<{$ecard_title}>"/></a> </th> <th align="center" valign="middle" class="navmenu" width="48"> <a href="<{$prev_tgt}>" class="navmenu_pic" title="<{$prev_title}>"><img src="images/prev.gif" width="16" height="16" border="0" align="middle" alt="<{$prev_title}>"/></a> </th> <th align="center" valign="middle" class="navmenu" width="48"> <a href="<{$next_tgt}>" class="navmenu_pic" title="<{$next_title}>"><img src="images/next.gif" width="16" height="16" border="0" align="middle" alt="<{$next_title}>"/></a> </th> </tr> </table> <table align="center" width="100%" cellspacing="1" cellpadding="0" class="outer"> <tr> <td align="center" class="odd" height="100"> <table class="outer" cellspacing="2" cellpadding="0" style="border: 1px solid #000000; background-color: #FFFFFF; margin-top: 30px; margin-bottom: 30px;width: auto;"> <tr> <td> <{if $file_type=='image'}> <{if $reduced==1}> <a href="javascript:;" onClick="MM_openBrWindow('displayimage.php?pid=<{$pid}>&amp;fullsize=1','<{$uniqid_rand}>','scrollbars=yes,toolbar=yes,status=yes,resizable=yes,width=<{$winsizeX}>,height=<{$winsizeY}>');"> <img src="<{$picture_url}>" <{$image_size}> class="image" border="0" alt="<{$lang_view_fs}>" /><br /> </a> <{else}> <img src="<{$picture_url}>" <{$image_size}> class="image" border="0" alt=""/><br /> <{/if}> <{else}> <object <{$image_size}>><param name="<{$file_type}>" value="<{$picture_url}>"><embed <{$image_size}> src="<{$picture_url}>"></embed></object> <{/if}> <{if $lang_del_pic !=''}> <form action="delete.php" style="padding: 0px;margin: 0px" method="post"><input type="hidden" name="id" value="<{$pid}>" /><input type="submit" name="picture" value="<{$lang_del_pic}>" class="button" style="width: 100%" onclick="return confirm('<{$lang_confirm_del}>');" /></form> <{/if}> </td> </tr> </table> <table cellpadding="0" cellspacing="0"> <{if $pic_title!=''}> <tr> <th> <{$pic_title}> </th> </tr> <{/if}> <{if $pic_caption !=''}> <tr> <td style="text-align: left;"> <div style="margin: 3px 10px 10px 10px;"><{$pic_caption}></div> </td> </tr> <{/if}> </table> <!-- END img_desc --> </td> </tr> </table> <table align="center" width="100%" cellspacing="1" cellpadding="0" class="outer"> <tr> <td colspan="6" class="head"><b><{$lang_rate_this_pic}>&nbsp;</b> <{$votes}></td> </tr> <tr> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=0" title="<{$lang_rubbish}>"><img src="images/rating0.gif" alt="<{$lang_rubbish}>" border="0"/><br /></a></td> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=1" title="<{$lang_poor}>"><img src="images/rating1.gif" alt="<{$lang_poor}>" border="0"/><br /></a></td> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=2" title="<{$lang_fair}>"><img src="images/rating2.gif" alt="<{$lang_fair}>" border="0"/><br /></a></td> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=3" title="<{$lang_good}>"><img src="images/rating3.gif" alt="<{$lang_good}>" border="0"/><br /></a></td> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=4" title="<{$lang_excellent}>"><img src="images/rating4.gif" alt="<{$lang_excellent}>" border="0"/><br /></a></td> <td class="even" width="17%" align="center"><a href="ratepic.php?pic=<{$pid}>&amp;rate=5" title="<{$lang_great}>"><img src="images/rating5.gif" alt="<{$lang_great}>" border="0"/><br /></a></td> </tr> </table> <div id="picinfo" style="display: <{$picinfo}>;"> <table align="center" width="100%" cellspacing="1" cellpadding="0" class="outer"> <tr><td colspan="2" class="head"><b><{$lang_picinfo_title}></b></td></tr> <{foreach item=info from=$infos}> <tr><td class="<{cycle name="keys" values="even,odd"}>" valign="top" nowrap><{$info.key}>:</td><td class="<{cycle name="values" values="even,odd"}>"><{$info.value}></td></tr> <{/foreach}> </table> </div> <div style="text-align: center; padding: 3px; margin:3px;"> <{$commentsnav}> <{$lang_notice}> </div> <div style="margin:3px; padding: 3px;"> <!-- start comments loop --> <{if $comment_mode == "flat"}> <{include file="db:system_comments_flat.html"}> <{elseif $comment_mode == "thread"}> <{include file="db:system_comments_thread.html"}> <{elseif $comment_mode == "nest"}> <{include file="db:system_comments_nest.html"}> <{/if}> <!-- end comments loop --> </div> <{include file="db:xcgal_footer.html"}>
ImpressCMS/impresscms-module-xcgallery
templates/xcgal_display.html
HTML
gpl-2.0
6,934
<?php /** * Copyright 2009 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. * * * @brief Checkout By Amazon Instant Order Processing Notification entry point. * @catagory Checkout By Amazon - Instant Order Processing Notification * */ include ('config.php'); $cbaiopn = new CBAIOPNProcessor(); // Read merchant configurations. $cbaiopn->Initialize(); // Authenticates the request. $cbaiopn->AuthenticateRequest(); //Validate the Notification data $cbaiopn->ValidateNotificationData(); //Process the request xml. To be extended by merchant. $cbaiopn->ProcessRequestXML(); ?>
nitesh146/Motleymart
plugins/system/qtcamazon_easycheckout/lib/iopn_processing/CBAIOPN.php
PHP
gpl-2.0
1,117
<?php /** * Class List_Comment */ class List_Comment { /** * @var string $title The title of the list of comments (e.g. X thoughts on %post%) */ private $title; /** * @var string $list The HTML list of the comments. */ private $list; /** * @var string $pagination The HTML pagination for the comments. */ private $pagination; /** * @var string $form The form used to reply to comments on the parent level. */ private $form; /** * @var string $closed_form The message added for screen readers when new comments can not be added * (e.g. the comments are closed). */ private $closed_form; /** * List_Comment constructor. */ public function __construct() { if ( have_comments() ) { $commentsTotal = get_comments_number(); $commentCountTitle = _nx( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', $commentsTotal, 'comments title', 'honeylizard'); $this->title = sprintf($commentCountTitle, number_format_i18n($commentsTotal), get_the_title()); $this->list = wp_list_comments([ 'avatar_size' => 50, 'style' => 'ol', 'max_depth' => 3, 'callback' => 'honeylizard_comment', 'echo' => false, ]); $this->pagination = get_the_comments_pagination([ 'prev_text' => __('&laquo; Previous Comments', 'honeylizard'), 'next_text' => __('Next Comments &raquo;', 'honeylizard'), ]); } else if( ! have_comments() && comments_open() && post_type_supports(get_post_type(), 'comments') ) { $this->title = __('No thoughts on this yet.', 'honeylizard'); } // If comments are closed and there are comments, let's leave a little note, shall we? if ( comments_open() && post_type_supports(get_post_type(), 'comments') ) { $this->form = Wordpress::getPostCommentsForm(); $this->form = str_replace('id="cancel-comment-reply-link"', 'id="cancel-comment-reply-link" class="button-link"', $this->form); } else { $view_variables = [ 'closed_message' => __('Comments are closed.', 'honeylizard'), ]; $view = new View('comments/closed', $view_variables); $this->closed_form = $view->render(); } } /** * Displays the list of comments along with the title of the list, and a pagination navigation. * * @return string */ public function renderView() { $comments_icon = get_template_directory_uri() . '/lib/vendor/glyphicons/glyphicons-245-conversation.png'; $comments_title_html = Wordpress::getIconHtml($comments_icon, __('Comments: ', 'honeylizard')); $view_variables = [ 'title' => $comments_title_html . ' ' . $this->title, 'navigation' => $this->pagination, 'list' => $this->list, 'form' => $this->closed_form . $this->form, ]; $view = new View('comments/list', $view_variables); $html = $view->render(); return $html; } }
honeylizard/honeylizard-theme
lib/classes/List_Comment.php
PHP
gpl-2.0
2,874
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("cartographer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("cartographer")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e474fa99-7026-4e2c-9a47-c9df1de991fa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
cody/cartographer
Properties/AssemblyInfo.cs
C#
gpl-2.0
1,400
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * PF_INET6 protocol dispatch tables. * * Version: $Id: protocol.c,v 1.1.1.1 2004/06/19 05:03:03 ashieh Exp $ * * Authors: Pedro Roque <roque@di.fc.ul.pt> * * 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. */ /* * Changes: * * Vince Laviano (vince@cs.stanford.edu) 16 May 2001 * - Removed unused variable 'inet6_protocol_base' * - Modified inet6_del_protocol() to correctly maintain copy bit. */ #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/sched.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/brlock.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> struct inet6_protocol *inet6_protos[MAX_INET_PROTOS]; void inet6_add_protocol(struct inet6_protocol *prot) { unsigned char hash; struct inet6_protocol *p2; hash = prot->protocol & (MAX_INET_PROTOS - 1); br_write_lock_bh(BR_NETPROTO_LOCK); prot->next = inet6_protos[hash]; inet6_protos[hash] = prot; prot->copy = 0; /* * Set the copy bit if we need to. */ p2 = (struct inet6_protocol *) prot->next; while(p2 != NULL) { if (p2->protocol == prot->protocol) { prot->copy = 1; break; } p2 = (struct inet6_protocol *) p2->next; } br_write_unlock_bh(BR_NETPROTO_LOCK); } /* * Remove a protocol from the hash tables. */ int inet6_del_protocol(struct inet6_protocol *prot) { struct inet6_protocol *p; struct inet6_protocol *lp = NULL; unsigned char hash; hash = prot->protocol & (MAX_INET_PROTOS - 1); br_write_lock_bh(BR_NETPROTO_LOCK); if (prot == inet6_protos[hash]) { inet6_protos[hash] = (struct inet6_protocol *) inet6_protos[hash]->next; br_write_unlock_bh(BR_NETPROTO_LOCK); return(0); } p = (struct inet6_protocol *) inet6_protos[hash]; if (p != NULL && p->protocol == prot->protocol) lp = p; while(p != NULL) { /* * We have to worry if the protocol being deleted is * the last one on the list, then we may need to reset * someone's copied bit. */ if (p->next != NULL && p->next == prot) { /* * if we are the last one with this protocol and * there is a previous one, reset its copy bit. */ if (prot->copy == 0 && lp != NULL) lp->copy = 0; p->next = prot->next; br_write_unlock_bh(BR_NETPROTO_LOCK); return(0); } if (p->next != NULL && p->next->protocol == prot->protocol) lp = p->next; p = (struct inet6_protocol *) p->next; } br_write_unlock_bh(BR_NETPROTO_LOCK); return(-1); }
romanalexander/Trickles
net/ipv6/protocol.c
C
gpl-2.0
3,024
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.layout; /** Builder class for javafx.scene.layout.StackPane @see javafx.scene.layout.StackPane @deprecated This class is deprecated and will be removed in the next version * @since JavaFX 2.0 */ @javax.annotation.Generated("Generated by javafx.builder.processor.BuilderProcessor") @Deprecated public class StackPaneBuilder<B extends javafx.scene.layout.StackPaneBuilder<B>> extends javafx.scene.layout.PaneBuilder<B> { protected StackPaneBuilder() { } /** Creates a new instance of StackPaneBuilder. */ @SuppressWarnings({"deprecation", "rawtypes", "unchecked"}) public static javafx.scene.layout.StackPaneBuilder<?> create() { return new javafx.scene.layout.StackPaneBuilder(); } private boolean __set; public void applyTo(javafx.scene.layout.StackPane x) { super.applyTo(x); if (__set) x.setAlignment(this.alignment); } private javafx.geometry.Pos alignment; /** Set the value of the {@link javafx.scene.layout.StackPane#getAlignment() alignment} property for the instance constructed by this builder. */ @SuppressWarnings("unchecked") public B alignment(javafx.geometry.Pos x) { this.alignment = x; __set = true; return (B) this; } /** Make an instance of {@link javafx.scene.layout.StackPane} based on the properties set on this builder. */ public javafx.scene.layout.StackPane build() { javafx.scene.layout.StackPane x = new javafx.scene.layout.StackPane(); applyTo(x); return x; } }
maiklos-mirrors/jfx78
modules/builders/src/main/java/javafx/scene/layout/StackPaneBuilder.java
Java
gpl-2.0
2,873
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
kiarash14/UPbumper
plugins/admin.lua
Lua
gpl-2.0
6,248
<?php /** * Functions * * Core functionality and initial theme setup * * @package WordPress * @subpackage Foundation, for WordPress * @since Foundation, for WordPress 4.0 */ /** * Initiate Foundation, for WordPress */ if ( ! function_exists( 'foundation_setup' ) ) : function foundation_setup() { // Content Width if ( ! isset( $content_width ) ) $content_width = 900; // Language Translations load_theme_textdomain( 'foundation', get_template_directory() . '/languages' ); // Custom Editor Style Support add_editor_style(); // Support for Featured Images add_theme_support( 'post-thumbnails' ); // Automatic Feed Links & Post Formats add_theme_support( 'automatic-feed-links' ); add_theme_support( 'post-formats', array( 'aside', 'image', 'link', 'quote', 'status' ) ); // Custom Background add_theme_support( 'custom-background', array( 'default-color' => 'fff', ) ); // Custom Header add_theme_support( 'custom-header', array( 'default-text-color' => '#000', 'header-text' => true, 'height' => '200', 'uploads' => true, ) ); } add_action( 'after_setup_theme', 'foundation_setup' ); endif; /** * Enqueue Scripts and Styles for Front-End */ if ( ! function_exists( 'foundation_assets' ) ) : function foundation_assets() { if (!is_admin()) { /** * Deregister jQuery in favour of ZeptoJS * jQuery will be used as a fallback if ZeptoJS is not compatible * @see foundation_compatibility & http://foundation.zurb.com/docs/javascript.html */ wp_deregister_script('jquery'); // Load JavaScripts wp_enqueue_script( 'foundation', get_template_directory_uri() . '/js/foundation.min.js', null, '4.0', true ); wp_enqueue_script( 'modernizr', get_template_directory_uri().'/js/vendor/custom.modernizr.js', null, '2.1.0'); if ( is_singular() ) wp_enqueue_script( "comment-reply" ); // Load Stylesheets wp_enqueue_style( 'normalize', get_template_directory_uri().'/css/normalize.css' ); wp_enqueue_style( 'foundation', get_template_directory_uri().'/css/foundation.min.css' ); wp_enqueue_style( 'app', get_stylesheet_uri(), array('foundation') ); // Load Google Fonts API wp_enqueue_style( 'google-fonts', 'http://fonts.googleapis.com/css?family=Open+Sans:400,300' ); } } add_action( 'wp_enqueue_scripts', 'foundation_assets' ); endif; /** * Initialise Foundation JS * @see: http://foundation.zurb.com/docs/javascript.html */ if ( ! function_exists( 'foundation_js_init' ) ) : function foundation_js_init () { echo '<script>$(document).foundation();</script>'; } add_action('wp_footer', 'foundation_js_init', 50); endif; /** * ZeptoJS and jQuery Fallback * @see: http://foundation.zurb.com/docs/javascript.html */ if ( ! function_exists( 'foundation_comptability' ) ) : function foundation_comptability () { echo "<script>"; echo "document.write('<script src=' +"; echo "('__proto__' in {} ? '" . get_template_directory_uri() . "/js/vendor/zepto" . "' : '" . get_template_directory_uri() . "/js/vendor/jquery" . "') +"; echo "'.js><\/script>')"; echo "</script>"; } add_action('wp_footer', 'foundation_comptability', 10); endif; /** * Register Navigation Menus */ if ( ! function_exists( 'foundation_menus' ) ) : // Register wp_nav_menus function foundation_menus() { register_nav_menus( array( 'header-menu' => __( 'Header Menu', 'foundation' ) ) ); } add_action( 'init', 'foundation_menus' ); endif; if ( ! function_exists( 'foundation_page_menu' ) ) : function foundation_page_menu() { $args = array( 'sort_column' => 'menu_order, post_title', 'menu_class' => 'large-12 columns', 'include' => '', 'exclude' => '', 'echo' => true, 'show_home' => false, 'link_before' => '', 'link_after' => '' ); wp_page_menu($args); } endif; /** * Navigation Menu Adjustments */ // Add class to navigation sub-menu class foundation_navigation extends Walker_Nav_Menu { function start_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"dropdown\">\n"; } function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { $id_field = $this->db_fields['id']; if ( !empty( $children_elements[ $element->$id_field ] ) ) { $element->classes[] = 'has-dropdown'; } Walker_Nav_Menu::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } } /** * Create pagination */ if ( ! function_exists( 'foundation_pagination' ) ) : function foundation_pagination() { global $wp_query; $big = 999999999; $links = paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'prev_next' => true, 'prev_text' => '&laquo;', 'next_text' => '&raquo;', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'type' => 'list' ) ); $pagination = str_replace('page-numbers','pagination',$links); echo $pagination; } endif; /** * Register Sidebars */ if ( ! function_exists( 'foundation_widgets' ) ) : function foundation_widgets() { // Sidebar Right register_sidebar( array( 'id' => 'foundation_sidebar_right', 'name' => __( 'Sidebar Right', 'foundation' ), 'description' => __( 'This sidebar is located on the right-hand side of each page.', 'foundation' ), 'before_widget' => '<div class="widget">', 'after_widget' => '</div></div>', 'before_title' => '<h5 class="widget-header">', 'after_title' => '</h5><div class="white-panel">', ) ); // Sidebar Footer Column One register_sidebar( array( 'id' => 'foundation_sidebar_footer_one', 'name' => __( 'Sidebar Footer One', 'foundation' ), 'description' => __( 'This sidebar is located in column one of your theme footer.', 'foundation' ), 'before_widget' => '<div class="large-3 columns">', 'after_widget' => '</div>', 'before_title' => '<h5>', 'after_title' => '</h5>', ) ); // Sidebar Footer Column Two register_sidebar( array( 'id' => 'foundation_sidebar_footer_two', 'name' => __( 'Sidebar Footer Two', 'foundation' ), 'description' => __( 'This sidebar is located in column two of your theme footer.', 'foundation' ), 'before_widget' => '<div class="large-3 columns">', 'after_widget' => '</div>', 'before_title' => '<h5>', 'after_title' => '</h5>', ) ); // Sidebar Footer Column Three register_sidebar( array( 'id' => 'foundation_sidebar_footer_three', 'name' => __( 'Sidebar Footer Three', 'foundation' ), 'description' => __( 'This sidebar is located in column three of your theme footer.', 'foundation' ), 'before_widget' => '<div class="large-3 columns">', 'after_widget' => '</div>', 'before_title' => '<h5>', 'after_title' => '</h5>', ) ); // Sidebar Footer Column Four register_sidebar( array( 'id' => 'foundation_sidebar_footer_four', 'name' => __( 'Sidebar Footer Four', 'foundation' ), 'description' => __( 'This sidebar is located in column four of your theme footer.', 'foundation' ), 'before_widget' => '<div class="large-3 columns">', 'after_widget' => '</div>', 'before_title' => '<h5>', 'after_title' => '</h5>', ) ); } add_action( 'widgets_init', 'foundation_widgets' ); endif; /** * Custom Avatar Classes */ if ( ! function_exists( 'foundation_avatar_css' ) ) : function foundation_avatar_css($class) { $class = str_replace("class='avatar", "class='author_gravatar left ", $class) ; return $class; } add_filter('get_avatar','foundation_avatar_css'); endif; /** * Custom Post Excerpt */ if ( ! function_exists( 'foundation_excerpt' ) ) : function foundation_excerpt($text) { global $post; if ( '' == $text ) { $text = get_the_content(''); $text = apply_filters('the_content', $text); $text = str_replace('\]\]\>', ']]&gt;', $text); $text = preg_replace('@<script[^>]*?>.*?</script>@si', '', $text); $text = strip_tags($text, '<p>'); $excerpt_length = 80; $words = explode(' ', $text, $excerpt_length + 1); if (count($words)> $excerpt_length) { array_pop($words); array_push($words, '<br><br><a href="'.get_permalink($post->ID) .'" class="georgia">' . __('Continue Reading', 'foundation') . '</a>'); $text = implode(' ', $words); } } return $text; } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'foundation_excerpt'); endif; /** * Comments Template */ if ( ! function_exists( 'foundation_comment' ) ) : function foundation_comment( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; switch ( $comment->comment_type ) : case 'pingback' : case 'trackback' : // Display trackbacks differently than normal comments. ?> <li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>"> <p><?php _e( 'Pingback:', 'foundation' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( '(Edit)', 'foundation' ), '<span>', '</span>' ); ?></p> <?php break; default : global $post; ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>"> <article id="comment-<?php comment_ID(); ?>" class="comment"> <header> <?php echo "<span class='th alignleft' style='margin-right:1rem;'>"; echo get_avatar( $comment, 44 ); echo "</span>"; printf( '%2$s %1$s', get_comment_author_link(), ( $comment->user_id === $post->post_author ) ? '<span class="label">' . __( 'Post Author', 'foundation' ) . '</span>' : '' ); printf( '<br><a href="%1$s"><time datetime="%2$s">%3$s</time></a>', esc_url( get_comment_link( $comment->comment_ID ) ), get_comment_time( 'c' ), sprintf( __( '%1$s at %2$s', 'foundation' ), get_comment_date(), get_comment_time() ) ); ?> </header> <?php if ( '0' == $comment->comment_approved ) : ?> <p><?php _e( 'Your comment is awaiting moderation.', 'foundation' ); ?></p> <?php endif; ?> <section> <?php comment_text(); ?> </section><!-- .comment-content --> <div class="reply"> <?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'foundation' ), 'after' => ' &darr; <br><br>', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </div> </article> <?php break; endswitch; } endif; /** * Remove Class from Sticky Post */ if ( ! function_exists( 'foundation_remove_sticky' ) ) : function foundation_remove_sticky($classes) { $classes = array_diff($classes, array("sticky")); return $classes; } add_filter('post_class','foundation_remove_sticky'); endif; /** * Custom Foundation Title Tag * @see http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_title */ function foundation_title( $title, $sep ) { global $paged, $page; if ( is_feed() ) return $title; // Add the site name. $title .= get_bloginfo( 'name' ); // Add the site description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) $title = "$title $sep $site_description"; // Add a page number if necessary. if ( $paged >= 2 || $page >= 2 ) $title = "$title $sep " . sprintf( __( 'Page %s', 'foundation' ), max( $paged, $page ) ); return $title; } add_filter( 'wp_title', 'foundation_title', 10, 2 ); /** * Retrieve Shortcodes * @see: http://fwp.drewsymo.com/shortcodes/ */ $foundation_shortcodes = trailingslashit( get_template_directory() ) . 'inc/shortcodes.php'; if (file_exists($foundation_shortcodes)) { require( $foundation_shortcodes ); } function pr($d){ echo '<pre>'.print_r($d,true).'</pre>'; } ?>
seanwooj/Forage
wp-content/themes/forage/functions.php
PHP
gpl-2.0
11,813
/* Copyright (C) 1997-2001 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // cl_inv.c -- client inventory screen #include "client.h" /* ================ CL_ParseInventory ================ */ void CL_ParseInventory (void) { int32_t i; for (i=0 ; i<MAX_ITEMS ; i++) cl.inventory[i] = MSG_ReadShort (&net_message); } /* ================ Inv_DrawString ================ */ void Hud_DrawString (int32_t x, int32_t y, const char *string, int32_t alpha, qboolean isStatusBar); void Inv_DrawString (int32_t x, int32_t y, char *string) { Hud_DrawString(x, y, string, 255, false); } void SetStringHighBit (char *s) { while (*s) *s++ |= 128; } /* ================ CL_DrawInventory ================ */ #define DISPLAY_ITEMS 17 void CL_DrawInventory (void) { int32_t i; int32_t num, selected_num, item; int32_t index[MAX_ITEMS]; char string[1024]; int32_t x, y; char *bind; int32_t selected; int32_t top; selected = cl.frame.playerstate.stats[STAT_SELECTED_ITEM]; num = 0; selected_num = 0; for (i=0; i<MAX_ITEMS; i++) { if (i==selected) selected_num = num; if (cl.inventory[i]) { index[num] = i; num++; } } // determine scroll point top = selected_num - DISPLAY_ITEMS/2; if (num - top < DISPLAY_ITEMS) top = num - DISPLAY_ITEMS; if (top < 0) top = 0; //x = (viddef.width-256)/2; //y = (viddef.height-240)/2; // x = viddef.width/2 - scaledHud(128); // y = viddef.height/2 - scaledHud(120); x = SCREEN_WIDTH/2 - 128; y = SCREEN_HEIGHT/2 - 116; // R_DrawScaledPic (x, y+scaledHud(8), HudScale(), hud_alpha->value, "inventory"); // y += scaledHud(24); // x += scaledHud(24); // Inv_DrawString (x, y, S_COLOR_BOLD"hotkey ### item"); // Inv_DrawString (x, y+scaledHud(8), S_COLOR_BOLD"------ --- ----"); // y += scaledHud(16); SCR_DrawPic (x, y, 256, 192, ALIGN_CENTER, "inventory", hud_alpha->value); x += 24; y += 20; SCR_DrawString (x, y, ALIGN_CENTER, S_COLOR_BOLD"hotkey ### item", 255); y += 8; SCR_DrawString (x, y, ALIGN_CENTER, S_COLOR_BOLD"------ --- ----", 255); x += 16; y += 8; for (i=top; i<num && i < top+DISPLAY_ITEMS; i++) { item = index[i]; // search for a binding bind = ""; if (cl.inventorykey[item] >= 0) { bind = Key_KeynumToString(cl.inventorykey[item]); } // Knightmare- BIG UGLY HACK for connected to server using old protocol // Changed config strings require different parsing if ( LegacyProtocol() ) { if (item != selected) { Com_sprintf (string, sizeof(string), " "S_COLOR_BOLD S_COLOR_ALT"%3s %3i %7s", bind, cl.inventory[item], cl.configstrings[OLD_CS_ITEMS+item] ); } else // draw a blinky cursor by the selected item { Com_sprintf (string, sizeof(string), S_COLOR_BOLD">"S_COLOR_ITALIC"%3s %3i %7s", bind, cl.inventory[item], cl.configstrings[OLD_CS_ITEMS+item] ); } } else { if (item != selected) { Com_sprintf (string, sizeof(string), " "S_COLOR_BOLD S_COLOR_ALT"%3s %3i %7s", bind, cl.inventory[item], cl.configstrings[CS_ITEMS+item] ); } else // draw a blinky cursor by the selected item { Com_sprintf (string, sizeof(string), S_COLOR_BOLD">"S_COLOR_ITALIC"%3s %3i %7s", bind, cl.inventory[item], cl.configstrings[CS_ITEMS+item] ); } } // Inv_DrawString (x, y, string); // y += scaledHud(8); SCR_DrawString (x, y, ALIGN_CENTER, string, 255); y += 8; } }
Nephatrine/nephq2
client/cl_inv.c
C
gpl-2.0
4,065
/* * Copyright (C) 2008-2010 Nick Schermer <nick@xfce.org> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_MATH_H #include <math.h> #endif #include <gtk/gtk.h> #include <exo/exo.h> #include <libwnck/libwnck.h> #include <libxfce4panel/libxfce4panel.h> #include <common/panel-private.h> #include <common/panel-debug.h> #ifdef GDK_WINDOWING_X11 #include <X11/Xlib.h> #include <gdk/gdkx.h> #include <X11/extensions/shape.h> #endif #include "tasklist-widget.h" #define DEFAULT_BUTTON_SIZE (25) #define DEFAULT_MAX_BUTTON_LENGTH (200) #define DEFAULT_MENU_ICON_SIZE (16) #define DEFAULT_MIN_BUTTON_LENGTH (DEFAULT_MAX_BUTTON_LENGTH / 4) #define DEFAULT_ICON_LUCENCY (50) #define DEFAULT_ELLIPSIZE_MODE (PANGO_ELLIPSIZE_END) #define DEFAULT_MENU_MAX_WIDTH_CHARS (24) #define ARROW_BUTTON_SIZE (20) #define WIREFRAME_SIZE (5) /* same as xfwm4 */ #define DRAG_ACTIVATE_TIMEOUT (500) /* locking helpers for tasklist->locked */ #define xfce_taskbar_lock(tasklist) G_STMT_START { XFCE_TASKLIST (tasklist)->locked++; } G_STMT_END #define xfce_taskbar_unlock(tasklist) G_STMT_START { \ if (XFCE_TASKLIST (tasklist)->locked > 0) \ XFCE_TASKLIST (tasklist)->locked--; \ else \ panel_assert_not_reached (); \ } G_STMT_END #define xfce_taskbar_is_locked(tasklist) (XFCE_TASKLIST (tasklist)->locked > 0) #define xfce_tasklist_get_panel_plugin(tasklist) gtk_widget_get_ancestor (GTK_WIDGET (tasklist), XFCE_TYPE_PANEL_PLUGIN) #define xfce_tasklist_horizontal(tasklist) ((tasklist)->mode == XFCE_PANEL_PLUGIN_MODE_HORIZONTAL) #define xfce_tasklist_vertical(tasklist) ((tasklist)->mode == XFCE_PANEL_PLUGIN_MODE_VERTICAL) #define xfce_tasklist_deskbar(tasklist) ((tasklist)->mode == XFCE_PANEL_PLUGIN_MODE_DESKBAR) #define xfce_tasklist_filter_monitors(tasklist) (!(tasklist)->all_monitors && (tasklist)->n_monitors > 1) #define xfce_tasklist_geometry_set_invalid(tasklist) ((tasklist)->n_monitors = 0) enum { PROP_0, PROP_GROUPING, PROP_INCLUDE_ALL_WORKSPACES, PROP_INCLUDE_ALL_MONITORS, PROP_FLAT_BUTTONS, PROP_SWITCH_WORKSPACE_ON_UNMINIMIZE, PROP_SHOW_LABELS, PROP_SHOW_ONLY_MINIMIZED, PROP_SHOW_WIREFRAMES, PROP_SHOW_HANDLE, PROP_SORT_ORDER, PROP_WINDOW_SCROLLING, PROP_WRAP_WINDOWS, PROP_INCLUDE_ALL_BLINKING, PROP_MIDDLE_CLICK }; struct _XfceTasklistClass { GtkContainerClass __parent__; }; struct _XfceTasklist { GtkContainer __parent__; /* lock counter */ gint locked; /* the screen of this tasklist */ WnckScreen *screen; GdkScreen *gdk_screen; /* window children in the tasklist */ GList *windows; /* windows we monitor, but that are excluded from the tasklist */ GSList *skipped_windows; /* arrow button of the overflow menu */ GtkWidget *arrow_button; /* classgroups of all the windows in the taskbar */ GHashTable *class_groups; /* normal or iconbox style */ guint show_labels : 1; /* size of the panel pluin */ gint size; /* mode (orientation) of the tasklist */ XfcePanelPluginMode mode; /* relief of the tasklist buttons */ GtkReliefStyle button_relief; /* whether we show windows from all workspaces or * only the active workspace */ guint all_workspaces : 1; /* whether we switch to another workspace when we try to * unminimize a window on another workspace */ guint switch_workspace : 1; /* whether we only show monimized windows in the * tasklist */ guint only_minimized : 1; /* number of rows of window buttons */ gint nrows; /* switch window with the mouse wheel */ guint window_scrolling : 1; guint wrap_windows : 1; /* whether we show blinking windows from all workspaces * or only the active workspace */ guint all_blinking : 1; /* action to preform when middle clicking */ XfceTasklistMClick middle_click; /* whether we only show windows that are in the geometry of * the monitor the tasklist is on */ guint all_monitors : 1; guint n_monitors; guint my_monitor; GdkRectangle *all_monitors_geometry; /* whether we show wireframes when hovering a button in * the tasklist */ guint show_wireframes : 1; /* icon geometries update timeout */ guint update_icon_geometries_id; /* idle monitor geometry update */ guint update_monitor_geometry_id; /* button grouping mode */ XfceTasklistGrouping grouping; /* sorting order of the buttons */ XfceTasklistSortOrder sort_order; /* dummy properties */ guint show_handle : 1; #ifdef GDK_WINDOWING_X11 /* wireframe window */ Window wireframe_window; #endif /* gtk style properties */ gint max_button_length; gint min_button_length; gint max_button_size; PangoEllipsizeMode ellipsize_mode; gint minimized_icon_lucency; gint menu_icon_size; gint menu_max_width_chars; gint n_windows; }; typedef enum { CHILD_TYPE_WINDOW, CHILD_TYPE_GROUP, CHILD_TYPE_OVERFLOW_MENU, CHILD_TYPE_GROUP_MENU } XfceTasklistChildType; typedef struct _XfceTasklistChild XfceTasklistChild; struct _XfceTasklistChild { /* type of this button */ XfceTasklistChildType type; /* pointer to the tasklist */ XfceTasklist *tasklist; /* button widgets */ GtkWidget *button; GtkWidget *box; GtkWidget *icon; GtkWidget *label; /* drag motion window activate */ guint motion_timeout_id; guint motion_timestamp; /* unique id for sorting by insert time, * simply increased for each new button */ guint unique_id; /* last time this window was focused */ GTimeVal last_focused; /* list of windows in case of a group button */ GSList *windows; /* wnck information */ WnckWindow *window; WnckClassGroup *class_group; }; static const GtkTargetEntry source_targets[] = { { "application/x-wnck-window-id", 0, 0 } }; static void xfce_tasklist_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec); static void xfce_tasklist_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec); static void xfce_tasklist_finalize (GObject *object); static void xfce_tasklist_size_request (GtkWidget *widget, GtkRequisition *requisition); static void xfce_tasklist_size_allocate (GtkWidget *widget, GtkAllocation *allocation); static void xfce_tasklist_style_set (GtkWidget *widget, GtkStyle *previous_style); static void xfce_tasklist_realize (GtkWidget *widget); static void xfce_tasklist_unrealize (GtkWidget *widget); static gboolean xfce_tasklist_scroll_event (GtkWidget *widget, GdkEventScroll *event); static void xfce_tasklist_remove (GtkContainer *container, GtkWidget *widget); static void xfce_tasklist_forall (GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data); static GType xfce_tasklist_child_type (GtkContainer *container); static void xfce_tasklist_arrow_button_toggled (GtkWidget *button, XfceTasklist *tasklist); static void xfce_tasklist_connect_screen (XfceTasklist *tasklist); static void xfce_tasklist_disconnect_screen (XfceTasklist *tasklist); static void xfce_tasklist_gdk_screen_changed (GdkScreen *gdk_screen, XfceTasklist *tasklist); static void xfce_tasklist_active_window_changed (WnckScreen *screen, WnckWindow *previous_window, XfceTasklist *tasklist); static void xfce_tasklist_active_workspace_changed (WnckScreen *screen, WnckWorkspace *previous_workspace, XfceTasklist *tasklist); static void xfce_tasklist_window_added (WnckScreen *screen, WnckWindow *window, XfceTasklist *tasklist); static void xfce_tasklist_window_removed (WnckScreen *screen, WnckWindow *window, XfceTasklist *tasklist); static void xfce_tasklist_viewports_changed (WnckScreen *screen, XfceTasklist *tasklist); static void xfce_tasklist_skipped_windows_state_changed (WnckWindow *window, WnckWindowState changed_state, WnckWindowState new_state, XfceTasklist *tasklist); static void xfce_tasklist_sort (XfceTasklist *tasklist); static gboolean xfce_tasklist_update_icon_geometries (gpointer data); static void xfce_tasklist_update_icon_geometries_destroyed (gpointer data); /* wireframe */ #ifdef GDK_WINDOWING_X11 static void xfce_tasklist_wireframe_hide (XfceTasklist *tasklist); static void xfce_tasklist_wireframe_destroy (XfceTasklist *tasklist); static void xfce_tasklist_wireframe_update (XfceTasklist *tasklist, XfceTasklistChild *child); #endif /* tasklist buttons */ static inline gboolean xfce_tasklist_button_visible (XfceTasklistChild *child, WnckWorkspace *active_ws); static gint xfce_tasklist_button_compare (gconstpointer child_a, gconstpointer child_b, gpointer user_data); static GtkWidget *xfce_tasklist_button_proxy_menu_item (XfceTasklistChild *child, gboolean allow_wireframe); static void xfce_tasklist_button_activate (XfceTasklistChild *child, guint32 timestamp); static XfceTasklistChild *xfce_tasklist_button_new (WnckWindow *window, XfceTasklist *tasklist); /* tasklist group buttons */ static void xfce_tasklist_group_button_remove (XfceTasklistChild *group_child); static void xfce_tasklist_group_button_add_window (XfceTasklistChild *group_child, XfceTasklistChild *window_child); static XfceTasklistChild *xfce_tasklist_group_button_new (WnckClassGroup *class_group, XfceTasklist *tasklist); /* potential public functions */ static void xfce_tasklist_set_include_all_workspaces (XfceTasklist *tasklist, gboolean all_workspaces); static void xfce_tasklist_set_include_all_monitors (XfceTasklist *tasklist, gboolean all_monitors); static void xfce_tasklist_set_button_relief (XfceTasklist *tasklist, GtkReliefStyle button_relief); static void xfce_tasklist_set_show_labels (XfceTasklist *tasklist, gboolean show_labels); static void xfce_tasklist_set_show_only_minimized (XfceTasklist *tasklist, gboolean only_minimized); static void xfce_tasklist_set_show_wireframes (XfceTasklist *tasklist, gboolean show_wireframes); static void xfce_tasklist_set_grouping (XfceTasklist *tasklist, XfceTasklistGrouping grouping); G_DEFINE_TYPE (XfceTasklist, xfce_tasklist, GTK_TYPE_CONTAINER) static GtkIconSize menu_icon_size = GTK_ICON_SIZE_INVALID; static void xfce_tasklist_class_init (XfceTasklistClass *klass) { GObjectClass *gobject_class; GtkWidgetClass *gtkwidget_class; GtkContainerClass *gtkcontainer_class; gobject_class = G_OBJECT_CLASS (klass); gobject_class->get_property = xfce_tasklist_get_property; gobject_class->set_property = xfce_tasklist_set_property; gobject_class->finalize = xfce_tasklist_finalize; gtkwidget_class = GTK_WIDGET_CLASS (klass); gtkwidget_class->size_request = xfce_tasklist_size_request; gtkwidget_class->size_allocate = xfce_tasklist_size_allocate; gtkwidget_class->style_set = xfce_tasklist_style_set; gtkwidget_class->realize = xfce_tasklist_realize; gtkwidget_class->unrealize = xfce_tasklist_unrealize; gtkwidget_class->scroll_event = xfce_tasklist_scroll_event; gtkcontainer_class = GTK_CONTAINER_CLASS (klass); gtkcontainer_class->add = NULL; gtkcontainer_class->remove = xfce_tasklist_remove; gtkcontainer_class->forall = xfce_tasklist_forall; gtkcontainer_class->child_type = xfce_tasklist_child_type; g_object_class_install_property (gobject_class, PROP_GROUPING, g_param_spec_uint ("grouping", NULL, NULL, XFCE_TASKLIST_GROUPING_MIN, XFCE_TASKLIST_GROUPING_MAX + 1 /* TODO drop this later */, XFCE_TASKLIST_GROUPING_DEFAULT, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_INCLUDE_ALL_WORKSPACES, g_param_spec_boolean ("include-all-workspaces", NULL, NULL, FALSE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_INCLUDE_ALL_MONITORS, g_param_spec_boolean ("include-all-monitors", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_FLAT_BUTTONS, g_param_spec_boolean ("flat-buttons", NULL, NULL, FALSE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SWITCH_WORKSPACE_ON_UNMINIMIZE, g_param_spec_boolean ("switch-workspace-on-unminimize", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SHOW_LABELS, g_param_spec_boolean ("show-labels", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SHOW_ONLY_MINIMIZED, g_param_spec_boolean ("show-only-minimized", NULL, NULL, FALSE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SHOW_WIREFRAMES, g_param_spec_boolean ("show-wireframes", NULL, NULL, FALSE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SHOW_HANDLE, g_param_spec_boolean ("show-handle", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_SORT_ORDER, g_param_spec_uint ("sort-order", NULL, NULL, XFCE_TASKLIST_SORT_ORDER_MIN, XFCE_TASKLIST_SORT_ORDER_MAX, XFCE_TASKLIST_SORT_ORDER_DEFAULT, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_WINDOW_SCROLLING, g_param_spec_boolean ("window-scrolling", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_WRAP_WINDOWS, g_param_spec_boolean ("wrap-windows", NULL, NULL, FALSE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_INCLUDE_ALL_BLINKING, g_param_spec_boolean ("include-all-blinking", NULL, NULL, TRUE, EXO_PARAM_READWRITE)); g_object_class_install_property (gobject_class, PROP_MIDDLE_CLICK, g_param_spec_uint ("middle-click", NULL, NULL, XFCE_TASKLIST_MIDDLE_CLICK_MIN, XFCE_TASKLIST_MIDDLE_CLICK_MAX, XFCE_TASKLIST_MIDDLE_CLICK_DEFAULT, EXO_PARAM_READWRITE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_int ("max-button-length", NULL, "The maximum length of a window button", -1, G_MAXINT, DEFAULT_MAX_BUTTON_LENGTH, EXO_PARAM_READABLE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_int ("min-button-length", NULL, "The minumum length of a window button", 1, G_MAXINT, DEFAULT_MIN_BUTTON_LENGTH, EXO_PARAM_READABLE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_int ("max-button-size", NULL, "The maximum size of a window button", 1, G_MAXINT, DEFAULT_BUTTON_SIZE, EXO_PARAM_READABLE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_enum ("ellipsize-mode", NULL, "The ellipsize mode used for the button label", PANGO_TYPE_ELLIPSIZE_MODE, DEFAULT_ELLIPSIZE_MODE, EXO_PARAM_READABLE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_int ("minimized-icon-lucency", NULL, "Lucent percentage of minimized icons", 0, 100, DEFAULT_ICON_LUCENCY, EXO_PARAM_READABLE)); gtk_widget_class_install_style_property (gtkwidget_class, g_param_spec_int ("menu-max-width-chars", NULL, "Maximum chars in the overflow menu labels", 0, G_MAXINT, DEFAULT_MENU_MAX_WIDTH_CHARS, EXO_PARAM_READABLE)); menu_icon_size = gtk_icon_size_from_name ("panel-tasklist-menu"); if (menu_icon_size == GTK_ICON_SIZE_INVALID) menu_icon_size = gtk_icon_size_register ("panel-tasklist-menu", DEFAULT_MENU_ICON_SIZE, DEFAULT_MENU_ICON_SIZE); } static void xfce_tasklist_init (XfceTasklist *tasklist) { GTK_WIDGET_SET_FLAGS (tasklist, GTK_NO_WINDOW); tasklist->locked = 0; tasklist->screen = NULL; tasklist->windows = NULL; tasklist->skipped_windows = NULL; tasklist->mode = XFCE_PANEL_PLUGIN_MODE_HORIZONTAL; tasklist->nrows = 1; tasklist->all_workspaces = FALSE; tasklist->button_relief = GTK_RELIEF_NORMAL; tasklist->switch_workspace = TRUE; tasklist->only_minimized = FALSE; tasklist->show_labels = TRUE; tasklist->show_wireframes = FALSE; tasklist->show_handle = TRUE; tasklist->all_monitors = TRUE; tasklist->n_monitors = 0; tasklist->all_monitors_geometry = NULL; tasklist->window_scrolling = TRUE; tasklist->wrap_windows = FALSE; tasklist->all_blinking = TRUE; tasklist->middle_click = XFCE_TASKLIST_MIDDLE_CLICK_DEFAULT; xfce_tasklist_geometry_set_invalid (tasklist); #ifdef GDK_WINDOWING_X11 tasklist->wireframe_window = 0; #endif tasklist->update_icon_geometries_id = 0; tasklist->update_monitor_geometry_id = 0; tasklist->max_button_length = DEFAULT_MAX_BUTTON_LENGTH; tasklist->min_button_length = DEFAULT_MIN_BUTTON_LENGTH; tasklist->max_button_size = DEFAULT_BUTTON_SIZE; tasklist->minimized_icon_lucency = DEFAULT_ICON_LUCENCY; tasklist->ellipsize_mode = DEFAULT_ELLIPSIZE_MODE; tasklist->grouping = XFCE_TASKLIST_GROUPING_DEFAULT; tasklist->sort_order = XFCE_TASKLIST_SORT_ORDER_DEFAULT; tasklist->menu_icon_size = DEFAULT_MENU_ICON_SIZE; tasklist->menu_max_width_chars = DEFAULT_MENU_MAX_WIDTH_CHARS; tasklist->class_groups = g_hash_table_new_full (g_direct_hash, g_direct_equal, (GDestroyNotify) g_object_unref, (GDestroyNotify) xfce_tasklist_group_button_remove); /* widgets for the overflow menu */ /* TODO support drag-motion and drag-leave */ tasklist->arrow_button = xfce_arrow_button_new (GTK_ARROW_DOWN); gtk_widget_set_parent (tasklist->arrow_button, GTK_WIDGET (tasklist)); gtk_widget_set_name (tasklist->arrow_button, "panel-tasklist-arrow"); gtk_button_set_relief (GTK_BUTTON (tasklist->arrow_button), tasklist->button_relief); g_signal_connect (G_OBJECT (tasklist->arrow_button), "toggled", G_CALLBACK (xfce_tasklist_arrow_button_toggled), tasklist); gtk_widget_show (tasklist->arrow_button); } static void xfce_tasklist_get_property (GObject *object, guint prop_id, GValue *value, GParamSpec *pspec) { XfceTasklist *tasklist = XFCE_TASKLIST (object); switch (prop_id) { case PROP_GROUPING: g_value_set_uint (value, tasklist->grouping); break; case PROP_INCLUDE_ALL_WORKSPACES: g_value_set_boolean (value, tasklist->all_workspaces); break; case PROP_INCLUDE_ALL_MONITORS: g_value_set_boolean (value, tasklist->all_monitors); break; case PROP_FLAT_BUTTONS: g_value_set_boolean (value, !!(tasklist->button_relief == GTK_RELIEF_NONE)); break; case PROP_SWITCH_WORKSPACE_ON_UNMINIMIZE: g_value_set_boolean (value, tasklist->switch_workspace); break; case PROP_SHOW_LABELS: g_value_set_boolean (value, tasklist->show_labels); break; case PROP_SHOW_ONLY_MINIMIZED: g_value_set_boolean (value, tasklist->only_minimized); break; case PROP_SHOW_WIREFRAMES: g_value_set_boolean (value, tasklist->show_wireframes); break; case PROP_SHOW_HANDLE: g_value_set_boolean (value, tasklist->show_handle); break; case PROP_SORT_ORDER: g_value_set_uint (value, tasklist->sort_order); break; case PROP_WINDOW_SCROLLING: g_value_set_boolean (value, tasklist->window_scrolling); break; case PROP_WRAP_WINDOWS: g_value_set_boolean (value, tasklist->wrap_windows); break; case PROP_INCLUDE_ALL_BLINKING: g_value_set_boolean (value, tasklist->all_blinking); break; case PROP_MIDDLE_CLICK: g_value_set_uint (value, tasklist->middle_click); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void xfce_tasklist_set_property (GObject *object, guint prop_id, const GValue *value, GParamSpec *pspec) { XfceTasklist *tasklist = XFCE_TASKLIST (object); XfceTasklistSortOrder sort_order; switch (prop_id) { case PROP_GROUPING: xfce_tasklist_set_grouping (tasklist, g_value_get_uint (value)); break; case PROP_INCLUDE_ALL_WORKSPACES: xfce_tasklist_set_include_all_workspaces (tasklist, g_value_get_boolean (value)); break; case PROP_INCLUDE_ALL_MONITORS: xfce_tasklist_set_include_all_monitors (tasklist, g_value_get_boolean (value)); break; case PROP_FLAT_BUTTONS: xfce_tasklist_set_button_relief (tasklist, g_value_get_boolean (value) ? GTK_RELIEF_NONE : GTK_RELIEF_NORMAL); break; case PROP_SHOW_LABELS: xfce_tasklist_set_show_labels (tasklist, g_value_get_boolean (value)); break; case PROP_SWITCH_WORKSPACE_ON_UNMINIMIZE: tasklist->switch_workspace = g_value_get_boolean (value); break; case PROP_SHOW_ONLY_MINIMIZED: xfce_tasklist_set_show_only_minimized (tasklist, g_value_get_boolean (value)); break; case PROP_SHOW_WIREFRAMES: xfce_tasklist_set_show_wireframes (tasklist, g_value_get_boolean (value)); break; case PROP_SHOW_HANDLE: tasklist->show_handle = g_value_get_boolean (value); break; case PROP_SORT_ORDER: sort_order = g_value_get_uint (value); if (tasklist->sort_order != sort_order) { tasklist->sort_order = sort_order; xfce_tasklist_sort (tasklist); } break; case PROP_WINDOW_SCROLLING: tasklist->window_scrolling = g_value_get_boolean (value); break; case PROP_WRAP_WINDOWS: tasklist->wrap_windows = g_value_get_boolean (value); break; case PROP_INCLUDE_ALL_BLINKING: tasklist->all_blinking = g_value_get_boolean (value); break; case PROP_MIDDLE_CLICK: tasklist->middle_click= g_value_get_uint (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void xfce_tasklist_finalize (GObject *object) { XfceTasklist *tasklist = XFCE_TASKLIST (object); /* data that should already be freed when disconnecting the screen */ panel_return_if_fail (tasklist->windows == NULL); panel_return_if_fail (tasklist->skipped_windows == NULL); panel_return_if_fail (tasklist->screen == NULL); /* stop pending timeouts */ if (tasklist->update_icon_geometries_id != 0) g_source_remove (tasklist->update_icon_geometries_id); if (tasklist->update_monitor_geometry_id != 0) g_source_remove (tasklist->update_monitor_geometry_id); /* free the class group hash table */ g_hash_table_destroy (tasklist->class_groups); #ifdef GDK_WINDOWING_X11 /* destroy the wireframe window */ xfce_tasklist_wireframe_destroy (tasklist); #endif (*G_OBJECT_CLASS (xfce_tasklist_parent_class)->finalize) (object); } static void xfce_tasklist_size_request (GtkWidget *widget, GtkRequisition *requisition) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); gint rows, cols; gint n_windows; GtkRequisition child_req; gint length; GList *li; XfceTasklistChild *child; gint child_height = 0; for (li = tasklist->windows, n_windows = 0; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button)) { gtk_widget_size_request (child->button, &child_req); /* child_height = MAX (child_height, child_req.height); */ child_height = MAX (child_height, tasklist->size / tasklist->nrows); if (child->type == CHILD_TYPE_GROUP_MENU) continue; n_windows++; } } tasklist->n_windows = n_windows; if (n_windows == 0) { length = 0; } else { rows = MAX (tasklist->nrows, 1); if (tasklist->show_labels && tasklist->max_button_size > 0) { rows = MAX (rows, tasklist->size / tasklist->max_button_size); child_height = MIN (child_height, tasklist->max_button_size); } cols = n_windows / rows; if (cols * rows < n_windows) cols++; if (!tasklist->show_labels) length = (tasklist->size / rows) * cols; else if (tasklist->max_button_length != -1) length = cols * tasklist->max_button_length; else length = cols * DEFAULT_MAX_BUTTON_LENGTH; } /* set the requested sizes */ if (xfce_tasklist_deskbar (tasklist) && tasklist->show_labels) { requisition->height = child_height * n_windows; requisition->width = tasklist->size; } else if (xfce_tasklist_horizontal (tasklist)) { requisition->width = length; requisition->height = tasklist->size; } else { requisition->width = tasklist->size; requisition->height = length; } } static gint xfce_tasklist_size_sort_window (gconstpointer a, gconstpointer b) { const XfceTasklistChild *child_a = a; const XfceTasklistChild *child_b = b; glong diff; diff = child_a->last_focused.tv_sec - child_b->last_focused.tv_sec; if (diff != 0) return CLAMP (diff, -1, 1); diff = child_a->last_focused.tv_usec - child_b->last_focused.tv_usec; return CLAMP (diff, -1, 1); } static void xfce_tasklist_size_layout (XfceTasklist *tasklist, GtkAllocation *alloc, gint *n_rows, gint *n_cols, gint *arrow_position) { gint rows; gint min_button_length; gint cols; GSList *windows_scored = NULL, *lp; GList *li; XfceTasklistChild *child; gint max_button_length; gint n_buttons; gint n_buttons_target; /* if we're in deskbar mode, there are no columns */ if (xfce_tasklist_deskbar (tasklist) && tasklist->show_labels) rows = 1; else if (tasklist->show_labels && tasklist->max_button_size > 0) rows = MAX (tasklist->nrows, tasklist->size / tasklist->max_button_size); else rows = tasklist->nrows; if (rows < 1) rows = 1; cols = tasklist->n_windows / rows; if (cols * rows < tasklist->n_windows) cols++; if (xfce_tasklist_deskbar (tasklist) && tasklist->show_labels) min_button_length = MIN (alloc->height / tasklist->nrows, tasklist->max_button_size); else if (!tasklist->show_labels) min_button_length = alloc->height / tasklist->nrows; else min_button_length = tasklist->min_button_length; *arrow_position = -1; /* not visible */ /* unset overflow items, we decide about that again * later */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (child->type == CHILD_TYPE_OVERFLOW_MENU) child->type = CHILD_TYPE_WINDOW; } if (min_button_length * cols <= alloc->width) { /* all the windows seem to fit */ *n_rows = rows; *n_cols = cols; } else { /* we need to group something, first create a list with the * windows most suitable for grouping at the beginning that are * (should be) currently visible */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button)) { windows_scored = g_slist_insert_sorted (windows_scored, child, xfce_tasklist_size_sort_window); } } if (xfce_tasklist_deskbar (tasklist) || !tasklist->show_labels) max_button_length = min_button_length; else if (tasklist->max_button_length != -1) max_button_length = tasklist->max_button_length; else max_button_length = DEFAULT_MAX_BUTTON_LENGTH; n_buttons = tasklist->n_windows; /* Matches the existing behavior (with a bug fix) */ /* n_buttons_target = MIN ((alloc->width - ARROW_BUTTON_SIZE) / min_button_length * rows, * * (((alloc->width - ARROW_BUTTON_SIZE) / max_button_length) + 1) * rows); */ /* Perhaps a better behavior (tries to display more buttons on the panel, */ /* yet still within the specified limits) */ n_buttons_target = (alloc->width - ARROW_BUTTON_SIZE) / min_button_length * rows; #if 0 if (tasklist->grouping == XFCE_TASKLIST_GROUPING_AUTO) { /* try creating group buttons */ } #endif /* we now push the windows with the lowest score in the * overflow menu */ if (n_buttons > n_buttons_target) { panel_debug (PANEL_DEBUG_TASKLIST, "Putting %d windows in overflow menu", n_buttons - n_buttons_target); for (lp = windows_scored; n_buttons > n_buttons_target && lp != NULL; lp = lp->next, n_buttons--) { child = lp->data; if (child->type == CHILD_TYPE_WINDOW) child->type = CHILD_TYPE_OVERFLOW_MENU; } /* Try to position the arrow widget at the end of the allocation area * * if that's impossible (because buttons cannot be expanded enough) * * position it just after the buttons. */ *arrow_position = MIN (alloc->width - ARROW_BUTTON_SIZE, n_buttons_target * max_button_length / rows); } g_slist_free (windows_scored); cols = n_buttons / rows; if (cols * rows < n_buttons) cols++; *n_rows = rows; *n_cols = cols; } } static void xfce_tasklist_size_allocate (GtkWidget *widget, GtkAllocation *allocation) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); gint rows, cols; gint row; GtkAllocation area = *allocation; GList *li; XfceTasklistChild *child; gint i; GtkAllocation child_alloc; gboolean direction_rtl = gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL; gint w, x, y, h; gint area_x, area_width; gint arrow_position; GtkRequisition child_req; panel_return_if_fail (GTK_WIDGET_VISIBLE (tasklist->arrow_button)); /* set widget allocation */ widget->allocation = *allocation; /* swap integers with vertical orientation */ if (!xfce_tasklist_horizontal (tasklist)) TRANSPOSE_AREA (area); panel_return_if_fail (area.height == tasklist->size); /* TODO if we compare the allocation with the requisition we can * do a fast path to the child allocation, i think */ /* useless but hides compiler warning */ w = h = x = y = rows = cols = 0; xfce_tasklist_size_layout (tasklist, &area, &rows, &cols, &arrow_position); /* allocate the arrow button for the overflow menu */ child_alloc.width = ARROW_BUTTON_SIZE; child_alloc.height = area.height; if (arrow_position != -1) { child_alloc.x = area.x; child_alloc.y = area.y; if (!direction_rtl) child_alloc.x += arrow_position; else child_alloc.x += (area.width - arrow_position); area.width = arrow_position; /* position the arrow in the correct position */ if (!xfce_tasklist_horizontal (tasklist)) TRANSPOSE_AREA (child_alloc); } else { child_alloc.x = child_alloc.y = -9999; } gtk_widget_size_allocate (tasklist->arrow_button, &child_alloc); area_x = area.x; area_width = area.width; h = area.height / rows; /* allocate all the children */ for (li = tasklist->windows, i = 0; li != NULL; li = li->next) { child = li->data; /* skip hidden buttons */ if (!GTK_WIDGET_VISIBLE (child->button)) continue; if (G_LIKELY (child->type == CHILD_TYPE_WINDOW || child->type == CHILD_TYPE_GROUP)) { row = (i % rows); if (row == 0) { x = area_x; y = area.y; if (xfce_tasklist_deskbar (tasklist) && tasklist->show_labels) { /* fixed width is OK because area.width==w*cols */ w = MIN (area.height / tasklist->nrows, tasklist->max_button_size); } else if (tasklist->show_labels) { /* TODO, this is a work-around, something else goes wrong * with counting the windows... */ if (cols < 1) cols = 1; w = area_width / cols--; if (tasklist->max_button_length > 0 && w > tasklist->max_button_length) w = tasklist->max_button_length; } else /* buttons without labels */ { w = h; } area_width -= w; area_x += w; } child_alloc.y = y; child_alloc.x = x; child_alloc.width = MAX (w, 1); /* TODO this is a workaround */ child_alloc.height = h; y += h; if (direction_rtl) child_alloc.x = area.x + area.width - (child_alloc.x - area.x) - child_alloc.width; /* allocate the child */ if (!xfce_tasklist_horizontal (tasklist)) TRANSPOSE_AREA (child_alloc); /* increase the position counter */ i++; } else { gtk_widget_get_child_requisition (child->button, &child_req); /* move the button offscreen */ child_alloc.y = child_alloc.x = -9999; child_alloc.width = child_req.width; child_alloc.height = child_req.height; } gtk_widget_size_allocate (child->button, &child_alloc); } /* update icon geometries */ if (tasklist->update_icon_geometries_id == 0) tasklist->update_icon_geometries_id = g_idle_add_full (G_PRIORITY_LOW, xfce_tasklist_update_icon_geometries, tasklist, xfce_tasklist_update_icon_geometries_destroyed); } static void xfce_tasklist_style_set (GtkWidget *widget, GtkStyle *previous_style) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); gint max_button_length; gint max_button_size; gint min_button_length; gint w, h; /* let gtk update the widget style */ (*GTK_WIDGET_CLASS (xfce_tasklist_parent_class)->style_set) (widget, previous_style); /* read the style properties */ gtk_widget_style_get (GTK_WIDGET (tasklist), "max-button-length", &max_button_length, "min-button-length", &min_button_length, "ellipsize-mode", &tasklist->ellipsize_mode, "max-button-size", &max_button_size, "minimized-icon-lucency", &tasklist->minimized_icon_lucency, "menu-max-width-chars", &tasklist->menu_max_width_chars, NULL); if (gtk_icon_size_lookup (menu_icon_size, &w, &h)) tasklist->menu_icon_size = MIN (w, h); /* update the widget */ if (tasklist->max_button_length != max_button_length || tasklist->max_button_size != max_button_size || tasklist->min_button_length != min_button_length) { if (max_button_length > 0) { /* prevent abuse of the min/max button length */ tasklist->max_button_length = MAX (min_button_length, max_button_length); tasklist->min_button_length = MIN (min_button_length, max_button_length); } else { tasklist->max_button_length = max_button_length; tasklist->min_button_length = min_button_length; } tasklist->max_button_size = max_button_size; gtk_widget_queue_resize (widget); } } static void xfce_tasklist_realize (GtkWidget *widget) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); (*GTK_WIDGET_CLASS (xfce_tasklist_parent_class)->realize) (widget); /* we now have a screen */ xfce_tasklist_connect_screen (tasklist); } static void xfce_tasklist_unrealize (GtkWidget *widget) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); /* we're going to loose the screen */ xfce_tasklist_disconnect_screen (tasklist); (*GTK_WIDGET_CLASS (xfce_tasklist_parent_class)->unrealize) (widget); } static gboolean xfce_tasklist_scroll_event (GtkWidget *widget, GdkEventScroll *event) { XfceTasklist *tasklist = XFCE_TASKLIST (widget); XfceTasklistChild *child = NULL; GList *li, *lnew = NULL; if (!tasklist->window_scrolling) return TRUE; /* get the current active button */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (child->button))) break; } if (G_UNLIKELY (li == NULL)) return TRUE; switch (event->direction) { case GDK_SCROLL_UP: /* find previous button on the tasklist */ for (lnew = g_list_previous (li); lnew != NULL; lnew = lnew->prev) { child = lnew->data; if (child->window != NULL && GTK_WIDGET_VISIBLE (child->button)) break; } /* wrap if the first button is reached */ lnew = (lnew == NULL && tasklist->wrap_windows) ? g_list_last (li) : lnew; break; case GDK_SCROLL_DOWN: /* find the next button on the tasklist */ for (lnew = g_list_next (li); lnew != NULL; lnew = lnew->next) { child = lnew->data; if (child->window != NULL && GTK_WIDGET_VISIBLE (child->button)) break; } /* wrap if the last button is reached */ lnew = (lnew == NULL && tasklist->wrap_windows) ? g_list_first (li) : lnew; break; case GDK_SCROLL_LEFT: /* TODO */ break; case GDK_SCROLL_RIGHT: /* TODO */ break; } if (lnew != NULL) xfce_tasklist_button_activate (lnew->data, event->time); return TRUE; } static void xfce_tasklist_remove (GtkContainer *container, GtkWidget *widget) { XfceTasklist *tasklist = XFCE_TASKLIST (container); gboolean was_visible; XfceTasklistChild *child; GList *li; for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (child->button == widget) { tasklist->windows = g_list_delete_link (tasklist->windows, li); was_visible = GTK_WIDGET_VISIBLE (widget); gtk_widget_unparent (child->button); if (child->motion_timeout_id != 0) g_source_remove (child->motion_timeout_id); g_slice_free (XfceTasklistChild, child); /* queue a resize if needed */ if (G_LIKELY (was_visible)) gtk_widget_queue_resize (GTK_WIDGET (container)); break; } } } static void xfce_tasklist_forall (GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data) { XfceTasklist *tasklist = XFCE_TASKLIST (container); GList *children = tasklist->windows; XfceTasklistChild *child; if (include_internals) (* callback) (tasklist->arrow_button, callback_data); while (children != NULL) { child = children->data; children = children->next; (* callback) (child->button, callback_data); } } static GType xfce_tasklist_child_type (GtkContainer *container) { return GTK_TYPE_WIDGET; } static void xfce_tasklist_arrow_button_menu_destroy (GtkWidget *menu, XfceTasklist *tasklist) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (GTK_IS_TOGGLE_BUTTON (tasklist->arrow_button)); panel_return_if_fail (GTK_IS_WIDGET (menu)); gtk_widget_destroy (menu); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (tasklist->arrow_button), FALSE); #ifdef GDK_WINDOWING_X11 /* make sure the wireframe is hidden */ xfce_tasklist_wireframe_hide (tasklist); #endif } static void xfce_tasklist_arrow_button_toggled (GtkWidget *button, XfceTasklist *tasklist) { GList *li; XfceTasklistChild *child; GtkWidget *mi; GtkWidget *menu; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (GTK_IS_TOGGLE_BUTTON (button)); panel_return_if_fail (tasklist->arrow_button == button); if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (button))) { menu = gtk_menu_new (); g_signal_connect (G_OBJECT (menu), "selection-done", G_CALLBACK (xfce_tasklist_arrow_button_menu_destroy), tasklist); for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (child->type != CHILD_TYPE_OVERFLOW_MENU) continue; mi = xfce_tasklist_button_proxy_menu_item (child, TRUE); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); gtk_widget_show (mi); } gtk_menu_attach_to_widget (GTK_MENU (menu), button, NULL); gtk_menu_popup (GTK_MENU (menu), NULL, NULL, xfce_panel_plugin_position_menu, xfce_tasklist_get_panel_plugin (tasklist), 1, gtk_get_current_event_time ()); } } static void xfce_tasklist_connect_screen (XfceTasklist *tasklist) { GList *windows, *li; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == NULL); panel_return_if_fail (tasklist->gdk_screen == NULL); /* set the new screen */ tasklist->gdk_screen = gtk_widget_get_screen (GTK_WIDGET (tasklist)); tasklist->screen = wnck_screen_get (gdk_screen_get_number (tasklist->gdk_screen)); /* add all existing windows on this screen */ windows = wnck_screen_get_windows (tasklist->screen); for (li = windows; li != NULL; li = li->next) xfce_tasklist_window_added (tasklist->screen, li->data, tasklist); /* monitor gdk changes */ g_signal_connect (G_OBJECT (tasklist->gdk_screen), "monitors-changed", G_CALLBACK (xfce_tasklist_gdk_screen_changed), tasklist); g_signal_connect (G_OBJECT (tasklist->gdk_screen), "size-changed", G_CALLBACK (xfce_tasklist_gdk_screen_changed), tasklist); /* monitor screen changes */ g_signal_connect (G_OBJECT (tasklist->screen), "active-window-changed", G_CALLBACK (xfce_tasklist_active_window_changed), tasklist); g_signal_connect (G_OBJECT (tasklist->screen), "active-workspace-changed", G_CALLBACK (xfce_tasklist_active_workspace_changed), tasklist); g_signal_connect (G_OBJECT (tasklist->screen), "window-opened", G_CALLBACK (xfce_tasklist_window_added), tasklist); g_signal_connect (G_OBJECT (tasklist->screen), "window-closed", G_CALLBACK (xfce_tasklist_window_removed), tasklist); g_signal_connect (G_OBJECT (tasklist->screen), "viewports-changed", G_CALLBACK (xfce_tasklist_viewports_changed), tasklist); /* update the viewport if not all monitors are shown */ xfce_tasklist_gdk_screen_changed (tasklist->gdk_screen, tasklist); } static void xfce_tasklist_disconnect_screen (XfceTasklist *tasklist) { GSList *li, *lnext; GList *wi, *wnext; XfceTasklistChild *child; guint n; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (WNCK_IS_SCREEN (tasklist->screen)); panel_return_if_fail (GDK_IS_SCREEN (tasklist->gdk_screen)); /* disconnect monitor signals */ n = g_signal_handlers_disconnect_matched (G_OBJECT (tasklist->screen), G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, tasklist); panel_return_if_fail (n == 5); /* disconnect geometry changed signals */ g_signal_handlers_disconnect_by_func (G_OBJECT (tasklist->gdk_screen), G_CALLBACK (xfce_tasklist_gdk_screen_changed), tasklist); /* delete all known class groups (and their buttons) */ g_hash_table_remove_all (tasklist->class_groups); /* disconnect from all skipped windows */ for (li = tasklist->skipped_windows; li != NULL; li = lnext) { lnext = li->next; panel_return_if_fail (wnck_window_is_skip_tasklist (WNCK_WINDOW (li->data))); xfce_tasklist_window_removed (tasklist->screen, li->data, tasklist); } /* remove all the windows */ for (wi = tasklist->windows; wi != NULL; wi = wnext) { wnext = wi->next; child = wi->data; /* do a fake window remove */ panel_return_if_fail (child->type != CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_WINDOW (child->window)); xfce_tasklist_window_removed (tasklist->screen, child->window, tasklist); } panel_assert (tasklist->windows == NULL); panel_assert (tasklist->skipped_windows == NULL); tasklist->screen = NULL; tasklist->gdk_screen = NULL; } static void xfce_tasklist_gdk_screen_changed (GdkScreen *gdk_screen, XfceTasklist *tasklist) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (GDK_IS_SCREEN (gdk_screen)); panel_return_if_fail (tasklist->gdk_screen == gdk_screen); if (!tasklist->all_monitors) { /* update the monitor geometry */ xfce_tasklist_update_monitor_geometry (tasklist); } } static void xfce_tasklist_active_window_changed (WnckScreen *screen, WnckWindow *previous_window, XfceTasklist *tasklist) { WnckWindow *active_window; GList *li; XfceTasklistChild *child; panel_return_if_fail (WNCK_IS_SCREEN (screen)); panel_return_if_fail (previous_window == NULL || WNCK_IS_WINDOW (previous_window)); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == screen); /* get the new active window */ active_window = wnck_screen_get_active_window (screen); /* lock the taskbar */ xfce_taskbar_lock (tasklist); for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; /* update timestamp for window */ if (child->window == active_window) g_get_current_time (&child->last_focused); /* set the toggle button state */ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (child->button), !!(child->window == active_window)); } /* release the lock */ xfce_taskbar_unlock (tasklist); } static void xfce_tasklist_active_workspace_changed (WnckScreen *screen, WnckWorkspace *previous_workspace, XfceTasklist *tasklist) { GList *li; WnckWorkspace *active_ws; XfceTasklistChild *child; panel_return_if_fail (WNCK_IS_SCREEN (screen)); panel_return_if_fail (previous_workspace == NULL || WNCK_IS_WORKSPACE (previous_workspace)); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == screen); /* leave when we are locked or show all workspaces. the null * check for @previous_workspace is used to update the tasklist * on setting changes */ if (xfce_taskbar_is_locked (tasklist) || (previous_workspace != NULL && tasklist->all_workspaces)) return; /* walk all the children and update their visibility */ active_ws = wnck_screen_get_active_workspace (screen); for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (child->type != CHILD_TYPE_GROUP) { if (xfce_tasklist_button_visible (child, active_ws)) gtk_widget_show (child->button); else gtk_widget_hide (child->button); } } } static void xfce_tasklist_window_added (WnckScreen *screen, WnckWindow *window, XfceTasklist *tasklist) { XfceTasklistChild *child; XfceTasklistChild *group_child = NULL; gboolean found; panel_return_if_fail (WNCK_IS_SCREEN (screen)); panel_return_if_fail (WNCK_IS_WINDOW (window)); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == screen); panel_return_if_fail (wnck_window_get_screen (window) == screen); /* ignore this window, but watch it for state changes */ if (wnck_window_is_skip_tasklist (window)) { tasklist->skipped_windows = g_slist_prepend (tasklist->skipped_windows, window); g_signal_connect (G_OBJECT (window), "state-changed", G_CALLBACK (xfce_tasklist_skipped_windows_state_changed), tasklist); return; } /* create new window button */ child = xfce_tasklist_button_new (window, tasklist); /* initial visibility of the function */ if (xfce_tasklist_button_visible (child, wnck_screen_get_active_workspace (screen))) gtk_widget_show (child->button); if (G_LIKELY (child->class_group != NULL)) { /* we need to ref the class group else the value returned from * wnck_window_get_class_group() is null */ panel_return_if_fail (WNCK_IS_CLASS_GROUP (child->class_group)); g_object_ref (G_OBJECT (child->class_group)); found = g_hash_table_lookup_extended (tasklist->class_groups, child->class_group, NULL, (gpointer *) &group_child); if (G_UNLIKELY (tasklist->grouping == XFCE_TASKLIST_GROUPING_ALWAYS)) { if (group_child == NULL) { /* create group button for this window and add it */ group_child = xfce_tasklist_group_button_new (child->class_group, tasklist); g_hash_table_insert (tasklist->class_groups, g_object_ref (child->class_group), group_child); } /* add window to the group button */ xfce_tasklist_group_button_add_window (group_child, child); } else if (!found) { /* add group in hash table without button */ g_hash_table_insert (tasklist->class_groups, g_object_ref (child->class_group), NULL); } } gtk_widget_queue_resize (GTK_WIDGET (tasklist)); } static void xfce_tasklist_window_removed (WnckScreen *screen, WnckWindow *window, XfceTasklist *tasklist) { GList *li; GSList *lp; XfceTasklistChild *child; //GList *windows, *lp; //gboolean remove_class_group = TRUE; guint n; panel_return_if_fail (WNCK_IS_SCREEN (screen)); panel_return_if_fail (WNCK_IS_WINDOW (window)); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == screen); /* check if the window is in our skipped window list */ if (wnck_window_is_skip_tasklist (window) && (lp = g_slist_find (tasklist->skipped_windows, window)) != NULL) { tasklist->skipped_windows = g_slist_delete_link (tasklist->skipped_windows, lp); g_signal_handlers_disconnect_by_func (G_OBJECT (window), G_CALLBACK (xfce_tasklist_skipped_windows_state_changed), tasklist); return; } /* remove the child from the taskbar */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (child->window == window) { if (child->class_group != NULL) { /* remove the class group from the internal list if this * was the last window in the group */ /* TODO windows = wnck_class_group_get_windows (child->class_group); for (lp = windows; remove_class_group && lp != NULL; lp = lp->next) if (!wnck_window_is_skip_tasklist (WNCK_WINDOW (lp->data))) remove_class_group = FALSE; if (remove_class_group) { tasklist->class_groups = g_slist_remove (tasklist->class_groups, child->class_group); }*/ panel_return_if_fail (WNCK_IS_CLASS_GROUP (child->class_group)); g_object_unref (G_OBJECT (child->class_group)); } /* disconnect from all the window watch functions */ panel_return_if_fail (WNCK_IS_WINDOW (window)); n = g_signal_handlers_disconnect_matched (G_OBJECT (window), G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, child); #ifdef GDK_WINDOWING_X11 /* hide the wireframe */ if (G_UNLIKELY (n > 5 && tasklist->show_wireframes)) { xfce_tasklist_wireframe_hide (tasklist); n--; } #endif panel_return_if_fail (n == 5); /* destroy the button, this will free the child data in the * container remove function */ gtk_widget_destroy (child->button); break; } } } static void xfce_tasklist_viewports_changed (WnckScreen *screen, XfceTasklist *tasklist) { WnckWorkspace *active_ws; panel_return_if_fail (WNCK_IS_SCREEN (screen)); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->screen == screen); /* pretend we changed workspace, this will update the * visibility of all the buttons */ active_ws = wnck_screen_get_active_workspace (screen); xfce_tasklist_active_workspace_changed (screen, active_ws, tasklist); } static void xfce_tasklist_skipped_windows_state_changed (WnckWindow *window, WnckWindowState changed_state, WnckWindowState new_state, XfceTasklist *tasklist) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (WNCK_IS_WINDOW (window)); panel_return_if_fail (g_slist_find (tasklist->skipped_windows, window) != NULL); if (PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_SKIP_TASKLIST)) { /* remove from list */ tasklist->skipped_windows = g_slist_remove (tasklist->skipped_windows, window); g_signal_handlers_disconnect_by_func (G_OBJECT (window), G_CALLBACK (xfce_tasklist_skipped_windows_state_changed), tasklist); /* pretend a normal window insert */ xfce_tasklist_window_added (wnck_window_get_screen (window), window, tasklist); } } static void xfce_tasklist_sort (XfceTasklist *tasklist) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->sort_order != XFCE_TASKLIST_SORT_ORDER_DND) tasklist->windows = g_list_sort_with_data (tasklist->windows, xfce_tasklist_button_compare, tasklist); gtk_widget_queue_resize (GTK_WIDGET (tasklist)); } static gboolean xfce_tasklist_update_icon_geometries (gpointer data) { XfceTasklist *tasklist = XFCE_TASKLIST (data); GList *li; XfceTasklistChild *child, *child2; GtkAllocation *alloc; GSList *lp; gint root_x, root_y; GtkWidget *toplevel; toplevel = gtk_widget_get_toplevel (GTK_WIDGET (tasklist)); gtk_window_get_position (GTK_WINDOW (toplevel), &root_x, &root_y); panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), FALSE); for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; switch (child->type) { case CHILD_TYPE_WINDOW: alloc = &child->button->allocation; panel_return_val_if_fail (WNCK_IS_WINDOW (child->window), FALSE); wnck_window_set_icon_geometry (child->window, alloc->x + root_x, alloc->y + root_y, alloc->width, alloc->height); break; case CHILD_TYPE_GROUP: alloc = &child->button->allocation; for (lp = child->windows; lp != NULL; lp = lp->next) { child2 = lp->data; panel_return_val_if_fail (WNCK_IS_WINDOW (child2->window), FALSE); wnck_window_set_icon_geometry (child2->window, alloc->x + root_x, alloc->y + root_y, alloc->width, alloc->height); } break; case CHILD_TYPE_OVERFLOW_MENU: alloc = &tasklist->arrow_button->allocation; panel_return_val_if_fail (WNCK_IS_WINDOW (child->window), FALSE); wnck_window_set_icon_geometry (child->window, alloc->x + root_x, alloc->y + root_y, alloc->width, alloc->height); break; case CHILD_TYPE_GROUP_MENU: /* we already handled those in the group button */ break; }; } return FALSE; } static void xfce_tasklist_update_icon_geometries_destroyed (gpointer data) { XFCE_TASKLIST (data)->update_icon_geometries_id = 0; } static gboolean xfce_tasklist_update_monitor_geometry_idle (gpointer data) { XfceTasklist *tasklist = XFCE_TASKLIST (data); GdkScreen *screen; gboolean geometry_set = FALSE; GdkWindow *window; guint tmp; panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), FALSE); GDK_THREADS_ENTER (); if (!tasklist->all_monitors) { screen = gtk_widget_get_screen (GTK_WIDGET (tasklist)); window = gtk_widget_get_window (GTK_WIDGET (tasklist)); if (G_LIKELY (screen != NULL && window != NULL && (tasklist->n_monitors = gdk_screen_get_n_monitors (screen)) > 1)) { /* set the monitor geometry */ tasklist->my_monitor = gdk_screen_get_monitor_at_window (screen, window); if (tasklist->all_monitors_geometry) tasklist->all_monitors_geometry = g_renew (GdkRectangle, tasklist->all_monitors_geometry, tasklist->n_monitors); else tasklist->all_monitors_geometry = g_new (GdkRectangle, tasklist->n_monitors); for(tmp = 0; tmp < tasklist->n_monitors; tmp++) gdk_screen_get_monitor_geometry (screen, tmp, &tasklist->all_monitors_geometry[tmp]); geometry_set = TRUE; } } /* make sure we never poke the window geometry unneeded * in the visibility function */ if (!geometry_set) xfce_tasklist_geometry_set_invalid (tasklist); /* update visibility of buttons */ if (tasklist->screen != NULL) xfce_tasklist_active_workspace_changed (tasklist->screen, NULL, tasklist); GDK_THREADS_LEAVE (); return FALSE; } static void xfce_tasklist_update_monitor_geometry_idle_destroy (gpointer data) { XFCE_TASKLIST (data)->update_monitor_geometry_id = 0; } static gboolean xfce_tasklist_child_drag_motion_timeout (gpointer data) { XfceTasklistChild *child = data; panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); panel_return_val_if_fail (WNCK_IS_SCREEN (child->tasklist->screen), FALSE); GDK_THREADS_ENTER (); if (child->type == CHILD_TYPE_WINDOW) { xfce_tasklist_button_activate (child, child->motion_timestamp); } else if (child->type == CHILD_TYPE_GROUP) { /* TODO popup menu */ } GDK_THREADS_LEAVE (); return FALSE; } static void xfce_tasklist_child_drag_motion_timeout_destroyed (gpointer data) { XfceTasklistChild *child = data; child->motion_timeout_id = 0; child->motion_timestamp = 0; } static gboolean xfce_tasklist_child_drag_motion (XfceTasklistChild *child, GdkDragContext *context, gint x, gint y, guint timestamp) { GtkWidget *dnd_widget; panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); /* don't respond to dragging our own children or panel plugins */ dnd_widget = gtk_drag_get_source_widget (context); if (dnd_widget == NULL || (gtk_widget_get_parent (dnd_widget) != GTK_WIDGET (child->tasklist) && !XFCE_IS_PANEL_PLUGIN (dnd_widget))) { child->motion_timestamp = timestamp; if (child->motion_timeout_id == 0 && !gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (child->button))) { child->motion_timeout_id = g_timeout_add_full (G_PRIORITY_LOW, DRAG_ACTIVATE_TIMEOUT, xfce_tasklist_child_drag_motion_timeout, child, xfce_tasklist_child_drag_motion_timeout_destroyed); } /* keep emitting the signal */ gdk_drag_status (context, 0, timestamp); /* we want to receive leave signal as well */ return TRUE; } else if (gtk_drag_dest_find_target (child->button, context, NULL) != GDK_NONE) { /* dnd to reorder buttons */ gdk_drag_status (context, GDK_ACTION_MOVE, timestamp); return TRUE; } /* also send drag-motion to other widgets */ return FALSE; } static void xfce_tasklist_child_drag_leave (XfceTasklistChild *child, GdkDragContext *context, GtkDragResult result) { panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); if (child->motion_timeout_id != 0) g_source_remove (child->motion_timeout_id); } static XfceTasklistChild * xfce_tasklist_child_new (XfceTasklist *tasklist) { XfceTasklistChild *child; panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), NULL); child = g_slice_new0 (XfceTasklistChild); child->tasklist = tasklist; /* create the window button */ child->button = xfce_arrow_button_new (GTK_ARROW_NONE); gtk_widget_set_parent (child->button, GTK_WIDGET (tasklist)); gtk_button_set_relief (GTK_BUTTON (child->button), tasklist->button_relief); child->box = xfce_hvbox_new (!xfce_tasklist_vertical (tasklist) ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL, FALSE, 6); gtk_container_add (GTK_CONTAINER (child->button), child->box); gtk_widget_show (child->box); child->icon = xfce_panel_image_new (); if (tasklist->show_labels) gtk_box_pack_start (GTK_BOX (child->box), child->icon, FALSE, TRUE, 0); else gtk_box_pack_start (GTK_BOX (child->box), child->icon, TRUE, TRUE, 0); if (tasklist->minimized_icon_lucency > 0) gtk_widget_show (child->icon); child->label = gtk_label_new (NULL); gtk_box_pack_start (GTK_BOX (child->box), child->label, TRUE, TRUE, 0); if (!xfce_tasklist_vertical (tasklist)) { /* gtk_box_reorder_child (GTK_BOX (child->box), child->icon, 0); */ gtk_misc_set_alignment (GTK_MISC (child->label), 0.0, 0.5); gtk_label_set_ellipsize (GTK_LABEL (child->label), tasklist->ellipsize_mode); } else { /* gtk_box_reorder_child (GTK_BOX (child->box), child->icon, -1); */ gtk_label_set_angle (GTK_LABEL (child->label), 270); gtk_misc_set_alignment (GTK_MISC (child->label), 0.50, 0.00); /* TODO can we already ellipsize here yet? */ } /* don't show the label if we're in iconbox style */ if (tasklist->show_labels) gtk_widget_show (child->label); gtk_drag_dest_set (GTK_WIDGET (child->button), 0, NULL, 0, GDK_ACTION_DEFAULT); g_signal_connect_swapped (G_OBJECT (child->button), "drag-motion", G_CALLBACK (xfce_tasklist_child_drag_motion), child); g_signal_connect_swapped (G_OBJECT (child->button), "drag-leave", G_CALLBACK (xfce_tasklist_child_drag_leave), child); return child; } /** * Wire Frame **/ #ifdef GDK_WINDOWING_X11 static void xfce_tasklist_wireframe_hide (XfceTasklist *tasklist) { GdkDisplay *dpy; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->wireframe_window != 0) { /* unmap the window */ dpy = gtk_widget_get_display (GTK_WIDGET (tasklist)); XUnmapWindow (GDK_DISPLAY_XDISPLAY (dpy), tasklist->wireframe_window); } } static void xfce_tasklist_wireframe_destroy (XfceTasklist *tasklist) { GdkDisplay *dpy; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->wireframe_window != 0) { /* unmap and destroy the window */ dpy = gtk_widget_get_display (GTK_WIDGET (tasklist)); XUnmapWindow (GDK_DISPLAY_XDISPLAY (dpy), tasklist->wireframe_window); XDestroyWindow (GDK_DISPLAY_XDISPLAY (dpy), tasklist->wireframe_window); tasklist->wireframe_window = 0; } } static void xfce_tasklist_wireframe_update (XfceTasklist *tasklist, XfceTasklistChild *child) { Display *dpy; GdkDisplay *gdpy; gint x, y, width, height; XSetWindowAttributes attrs; GC gc; XRectangle xrect; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (tasklist->show_wireframes == TRUE); panel_return_if_fail (WNCK_IS_WINDOW (child->window)); /* get the window geometry */ wnck_window_get_geometry (child->window, &x, &y, &width, &height); gdpy = gtk_widget_get_display (GTK_WIDGET (tasklist)); dpy = GDK_DISPLAY_XDISPLAY (gdpy); if (G_LIKELY (tasklist->wireframe_window != 0)) { /* reposition the wireframe */ XMoveResizeWindow (dpy, tasklist->wireframe_window, x, y, width, height); /* full window rectangle */ xrect.x = 0; xrect.y = 0; xrect.width = width; xrect.height = height; /* we need to restore the window first */ XShapeCombineRectangles (dpy, tasklist->wireframe_window, ShapeBounding, 0, 0, &xrect, 1, ShapeSet, Unsorted); } else { /* set window attributes */ attrs.override_redirect = True; attrs.background_pixel = 0x000000; /* create new window */ tasklist->wireframe_window = XCreateWindow (dpy, DefaultRootWindow (dpy), x, y, width, height, 0, CopyFromParent, InputOutput, CopyFromParent, CWOverrideRedirect | CWBackPixel, &attrs); } /* create rectangle what will be 'transparent' in the window */ xrect.x = WIREFRAME_SIZE; xrect.y = WIREFRAME_SIZE; xrect.width = width - WIREFRAME_SIZE * 2; xrect.height = height - WIREFRAME_SIZE * 2; /* substruct rectangle from the window */ XShapeCombineRectangles (dpy, tasklist->wireframe_window, ShapeBounding, 0, 0, &xrect, 1, ShapeSubtract, Unsorted); /* map the window */ XMapWindow (dpy, tasklist->wireframe_window); /* create a white gc */ gc = XCreateGC (dpy, tasklist->wireframe_window, 0, NULL); XSetForeground (dpy, gc, 0xffffff); /* draw the outer white rectangle */ XDrawRectangle (dpy, tasklist->wireframe_window, gc, 0, 0, width - 1, height - 1); /* draw the inner white rectangle */ XDrawRectangle (dpy, tasklist->wireframe_window, gc, WIREFRAME_SIZE - 1, WIREFRAME_SIZE - 1, width - 2 * (WIREFRAME_SIZE - 1) - 1, height - 2 * (WIREFRAME_SIZE - 1) - 1); XFreeGC (dpy, gc); } #endif /** * Tasklist Buttons **/ static inline gboolean xfce_tasklist_button_visible (XfceTasklistChild *child, WnckWorkspace *active_ws) { XfceTasklist *tasklist = XFCE_TASKLIST (child->tasklist); GdkRectangle window, intersection; guint best_size = 0, best_monitor = 0, size, tmp; panel_return_val_if_fail (active_ws == NULL || WNCK_IS_WORKSPACE (active_ws), FALSE); panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), FALSE); panel_return_val_if_fail (WNCK_IS_WINDOW (child->window), FALSE); if (xfce_tasklist_filter_monitors (tasklist)) { /* center of the window must be on this screen */ wnck_window_get_geometry (child->window, &window.x, &window.y, &window.width, &window.height); for (tmp = 0; tmp < tasklist->n_monitors; tmp++) { gdk_rectangle_intersect(&tasklist->all_monitors_geometry[tmp], &window, &intersection); size = intersection.width * intersection.height; if (size > best_size) { best_size = size; best_monitor = tmp; } } if (best_monitor != tasklist->my_monitor) return FALSE; } if (tasklist->all_workspaces || (active_ws != NULL && (G_UNLIKELY (wnck_workspace_is_virtual (active_ws)) ? wnck_window_is_in_viewport (child->window, active_ws) : wnck_window_is_on_workspace (child->window, active_ws))) || (tasklist->all_blinking && xfce_arrow_button_get_blinking (XFCE_ARROW_BUTTON (child->button)))) { return (!tasklist->only_minimized || wnck_window_is_minimized (child->window)); } return FALSE; } static gint xfce_tasklist_button_compare (gconstpointer child_a, gconstpointer child_b, gpointer user_data) { const XfceTasklistChild *a = child_a, *b = child_b; XfceTasklist *tasklist = XFCE_TASKLIST (user_data); gint retval; WnckClassGroup *class_group_a, *class_group_b; const gchar *name_a, *name_b; WnckWorkspace *workspace_a, *workspace_b; gint num_a, num_b; panel_return_val_if_fail (a->type == CHILD_TYPE_GROUP || WNCK_IS_WINDOW (a->window), 0); panel_return_val_if_fail (b->type == CHILD_TYPE_GROUP || WNCK_IS_WINDOW (b->window), 0); /* just append to the list */ if (tasklist->sort_order == XFCE_TASKLIST_SORT_ORDER_DND) return a->unique_id - b->unique_id; if (tasklist->all_workspaces) { /* get workspace (this is slightly inefficient because the WnckWindow * also stores the workspace number, not the structure, and we use that * for comparing too */ workspace_a = a->window != NULL ? wnck_window_get_workspace (a->window) : NULL; workspace_b = b->window != NULL ? wnck_window_get_workspace (b->window) : NULL; /* skip this if windows are in same worspace, or both pinned (== NULL) */ if (workspace_a != workspace_b) { /* NULL means the window is pinned */ if (workspace_a == NULL) workspace_a = wnck_screen_get_active_workspace (tasklist->screen); if (workspace_b == NULL) workspace_b = wnck_screen_get_active_workspace (tasklist->screen); /* compare by workspace number */ num_a = wnck_workspace_get_number (workspace_a); num_b = wnck_workspace_get_number (workspace_b); if (num_a != num_b) return num_a - num_b; } } if (tasklist->sort_order == XFCE_TASKLIST_SORT_ORDER_GROUP_TITLE || tasklist->sort_order == XFCE_TASKLIST_SORT_ORDER_GROUP_TIMESTAMP) { /* compare by class group names */ class_group_a = a->class_group; class_group_b = b->class_group; /* skip this if windows are in same group (or both NULL) */ if (class_group_a != class_group_b) { name_a = NULL; name_b = NULL; /* get the group name if available */ if (G_LIKELY (class_group_a != NULL)) name_a = wnck_class_group_get_name (class_group_a); if (G_LIKELY (class_group_b != NULL)) name_b = wnck_class_group_get_name (class_group_b); /* if there is no class group name, use the window name */ if (exo_str_is_empty (name_a) && a->window != NULL) name_a = wnck_window_get_name (a->window); if (exo_str_is_empty (name_b) && b->window != NULL) name_b = wnck_window_get_name (b->window) ; if (name_a == NULL) name_a = ""; if (name_b == NULL) name_b = ""; retval = strcasecmp (name_a, name_b); if (retval != 0) return retval; } else if (a->type != b->type) { /* put the group in front of the other window buttons * with the same group */ return b->type - a->type; } } if (tasklist->sort_order == XFCE_TASKLIST_SORT_ORDER_TIMESTAMP || tasklist->sort_order == XFCE_TASKLIST_SORT_ORDER_GROUP_TIMESTAMP) { return a->unique_id - b->unique_id; } else { if (a->window != NULL) name_a = wnck_window_get_name (a->window); else if (a->class_group != NULL) name_a = wnck_class_group_get_name (a->class_group); else name_a = NULL; if (b->window != NULL) name_b = wnck_window_get_name (b->window); else if (b->class_group != NULL) name_b = wnck_class_group_get_name (b->class_group); else name_b = NULL; if (name_a == NULL) name_a = ""; if (name_b == NULL) name_b = ""; return strcasecmp (name_a, name_b); } } static void xfce_tasklist_button_icon_changed (WnckWindow *window, XfceTasklistChild *child) { GdkPixbuf *pixbuf; GdkPixbuf *lucent = NULL; XfceTasklist *tasklist = child->tasklist; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (XFCE_IS_PANEL_IMAGE (child->icon)); panel_return_if_fail (WNCK_IS_WINDOW (window)); panel_return_if_fail (child->window == window); /* 0 means icons are disabled */ if (tasklist->minimized_icon_lucency == 0) return; /* get the window icon */ if (tasklist->show_labels) pixbuf = wnck_window_get_mini_icon (window); else pixbuf = wnck_window_get_icon (window); /* leave when there is no valid pixbuf */ if (G_UNLIKELY (pixbuf == NULL)) { xfce_panel_image_clear (XFCE_PANEL_IMAGE (child->icon)); return; } /* create a spotlight version of the icon when minimized */ if (!tasklist->only_minimized && tasklist->minimized_icon_lucency < 100 && wnck_window_is_minimized (window)) { lucent = exo_gdk_pixbuf_lucent (pixbuf, tasklist->minimized_icon_lucency); if (G_UNLIKELY (lucent != NULL)) pixbuf = lucent; } xfce_panel_image_set_from_pixbuf (XFCE_PANEL_IMAGE (child->icon), pixbuf); if (lucent != NULL && lucent != pixbuf) g_object_unref (G_OBJECT (lucent)); } static void xfce_tasklist_button_name_changed (WnckWindow *window, XfceTasklistChild *child) { const gchar *name; gchar *label = NULL; panel_return_if_fail (window == NULL || child->window == window); panel_return_if_fail (WNCK_IS_WINDOW (child->window)); panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); name = wnck_window_get_name (child->window); gtk_widget_set_tooltip_text (GTK_WIDGET (child->button), name); /* create the button label */ if (!child->tasklist->only_minimized && wnck_window_is_minimized (child->window)) name = label = g_strdup_printf ("[%s]", name); else if (wnck_window_is_shaded (child->window)) name = label = g_strdup_printf ("=%s=", name); gtk_label_set_text (GTK_LABEL (child->label), name); g_free (label); /* if window is null, we have not inserted the button the in * tasklist, so no need to sort, because we insert with sorting */ if (window != NULL) xfce_tasklist_sort (child->tasklist); } static void xfce_tasklist_button_state_changed (WnckWindow *window, WnckWindowState changed_state, WnckWindowState new_state, XfceTasklistChild *child) { gboolean blink; WnckScreen *screen; XfceTasklist *tasklist; WnckWorkspace *active_ws; panel_return_if_fail (WNCK_IS_WINDOW (window)); panel_return_if_fail (child->window == window); panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); /* remove if the new state is hidding the window from the tasklist */ if (PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_SKIP_TASKLIST)) { screen = wnck_window_get_screen (window); tasklist = child->tasklist; /* remove button from tasklist */ xfce_tasklist_window_removed (screen, window, child->tasklist); /* add the window to the skipped_windows list */ xfce_tasklist_window_added (screen, window, tasklist); return; } /* update the button name */ if (PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_SHADED | WNCK_WINDOW_STATE_MINIMIZED) && !child->tasklist->only_minimized) xfce_tasklist_button_name_changed (window, child); /* update the button icon if needed */ if (PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_MINIMIZED)) { if (G_UNLIKELY (child->tasklist->only_minimized)) { if (PANEL_HAS_FLAG (new_state, WNCK_WINDOW_STATE_MINIMIZED)) gtk_widget_show (child->button); else gtk_widget_hide (child->button); } else { /* update the icon (lucent) */ xfce_tasklist_button_icon_changed (window, child); } } /* update the blinking state */ if (PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_DEMANDS_ATTENTION) || PANEL_HAS_FLAG (changed_state, WNCK_WINDOW_STATE_URGENT)) { /* only start blinking if the window requesting urgency * notification is not the active window */ blink = wnck_window_or_transient_needs_attention (window); if (!blink || (blink && !wnck_window_is_active (window))) { /* if we have all_blinking set make sure we toggle visibility of the button * in case the window is not in the current workspace */ active_ws = wnck_screen_get_active_workspace (child->tasklist->screen); if (child->tasklist->all_blinking && blink && !xfce_tasklist_button_visible (child, active_ws)) { gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (child->button), FALSE); gtk_widget_show (child->button); } xfce_arrow_button_set_blinking (XFCE_ARROW_BUTTON (child->button), blink); if (child->tasklist->all_blinking && !xfce_tasklist_button_visible (child, active_ws)) gtk_widget_hide (child->button); } } } static void xfce_tasklist_button_workspace_changed (WnckWindow *window, XfceTasklistChild *child) { XfceTasklist *tasklist = XFCE_TASKLIST (child->tasklist); panel_return_if_fail (child->window == window); panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); xfce_tasklist_sort (tasklist); /* make sure we don't have two active windows (bug #6474) */ gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (child->button), FALSE); if (!tasklist->all_workspaces) xfce_tasklist_active_workspace_changed (tasklist->screen, NULL, tasklist); } static void xfce_tasklist_button_geometry_changed2 (WnckWindow *window, XfceTasklistChild *child) { WnckWorkspace *active_ws; panel_return_if_fail (child->window == window); panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); panel_return_if_fail (WNCK_IS_SCREEN (child->tasklist->screen)); if (xfce_tasklist_filter_monitors (child->tasklist)) { /* check if we need to change the visibility of the button */ active_ws = wnck_screen_get_active_workspace (child->tasklist->screen); if (xfce_tasklist_button_visible (child, active_ws)) gtk_widget_show (child->button); else gtk_widget_hide (child->button); } } #ifdef GDK_WINDOWING_X11 static void xfce_tasklist_button_geometry_changed (WnckWindow *window, XfceTasklistChild *child) { panel_return_if_fail (child->window == window); panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); xfce_tasklist_wireframe_update (child->tasklist, child); } static gboolean xfce_tasklist_button_leave_notify_event (GtkWidget *button, GdkEventCrossing *event, XfceTasklistChild *child) { panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); panel_return_val_if_fail (child->type != CHILD_TYPE_GROUP, FALSE); /* disconnect signals */ g_signal_handlers_disconnect_by_func (button, xfce_tasklist_button_leave_notify_event, child); g_signal_handlers_disconnect_by_func (child->window, xfce_tasklist_button_geometry_changed, child); /* unmap and destroy the wireframe window */ xfce_tasklist_wireframe_hide (child->tasklist); return FALSE; } #endif static gboolean xfce_tasklist_button_enter_notify_event (GtkWidget *button, GdkEventCrossing *event, XfceTasklistChild *child) { panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); panel_return_val_if_fail (child->type != CHILD_TYPE_GROUP, FALSE); panel_return_val_if_fail (GTK_IS_WIDGET (button), FALSE); panel_return_val_if_fail (WNCK_IS_WINDOW (child->window), FALSE); #ifdef GDK_WINDOWING_X11 /* leave when there is nothing to do */ if (!child->tasklist->show_wireframes) return FALSE; /* show wireframe for the child */ xfce_tasklist_wireframe_update (child->tasklist, child); /* connect signal to destroy the window when the user leaves the button */ g_signal_connect (G_OBJECT (button), "leave-notify-event", G_CALLBACK (xfce_tasklist_button_leave_notify_event), child); /* watch geometry changes */ g_signal_connect (G_OBJECT (child->window), "geometry-changed", G_CALLBACK (xfce_tasklist_button_geometry_changed), child); #endif return FALSE; } static gboolean xfce_tasklist_button_button_press_event (GtkWidget *button, GdkEventButton *event, XfceTasklistChild *child) { GtkWidget *menu, *panel_plugin; panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); panel_return_val_if_fail (child->type != CHILD_TYPE_GROUP, FALSE); if (event->type != GDK_BUTTON_PRESS || xfce_taskbar_is_locked (child->tasklist)) return FALSE; /* send the event to the panel plugin if control is pressed */ if (PANEL_HAS_FLAG (event->state, GDK_CONTROL_MASK)) { /* send the event to the panel plugin */ panel_plugin = xfce_tasklist_get_panel_plugin (child->tasklist); if (G_LIKELY (panel_plugin != NULL)) gtk_widget_event (panel_plugin, (GdkEvent *) event); return TRUE; } if (event->button == 3) { menu = wnck_action_menu_new (child->window); g_signal_connect (G_OBJECT (menu), "selection-done", G_CALLBACK (gtk_widget_destroy), NULL); gtk_menu_attach_to_widget (GTK_MENU (menu), button, NULL); gtk_menu_popup (GTK_MENU (menu), NULL, NULL, child->type == CHILD_TYPE_WINDOW ? xfce_panel_plugin_position_menu : NULL, xfce_tasklist_get_panel_plugin (child->tasklist), event->button, event->time); return TRUE; } return FALSE; } static gboolean xfce_tasklist_button_button_release_event (GtkWidget *button, GdkEventButton *event, XfceTasklistChild *child) { panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), FALSE); panel_return_val_if_fail (child->type != CHILD_TYPE_GROUP, FALSE); /* only respond to in-button events */ if (event->type == GDK_BUTTON_RELEASE && !xfce_taskbar_is_locked (child->tasklist) && !(event->x == 0 && event->y == 0) /* 0,0 = outside the widget in Gtk */ && event->x >= 0 && event->x < button->allocation.width && event->y >= 0 && event->y < button->allocation.height) { if (event->button == 1) { /* press the button */ xfce_tasklist_button_activate (child, event->time); return FALSE; } else if (event->button == 2) { switch (child->tasklist->middle_click) { case XFCE_TASKLIST_MIDDLE_CLICK_NOTHING: break; case XFCE_TASKLIST_MIDDLE_CLICK_CLOSE_WINDOW: wnck_window_close (child->window, event->time); return TRUE; case XFCE_TASKLIST_MIDDLE_CLICK_MINIMIZE_WINDOW: if (!wnck_window_is_minimized (child->window)) wnck_window_minimize (child->window); return FALSE; } } } return FALSE; } static void xfce_tasklist_button_enter_notify_event_disconnected (gpointer data, GClosure *closure) { XfceTasklistChild *child = data; panel_return_if_fail (WNCK_IS_WINDOW (child->window)); /* we need to detach the geometry watch because that is connected * to the window we proxy and thus not disconnected when the * proxy dies */ g_signal_handlers_disconnect_by_func (child->window, xfce_tasklist_button_geometry_changed, child); g_object_unref (G_OBJECT (child->window)); } static GtkWidget * xfce_tasklist_button_proxy_menu_item (XfceTasklistChild *child, gboolean allow_wireframe) { GtkWidget *mi; GtkWidget *image; GtkWidget *label; XfceTasklist *tasklist = child->tasklist; panel_return_val_if_fail (XFCE_IS_TASKLIST (child->tasklist), NULL); panel_return_val_if_fail (child->type == CHILD_TYPE_OVERFLOW_MENU || child->type == CHILD_TYPE_GROUP_MENU, NULL); panel_return_val_if_fail (GTK_IS_LABEL (child->label), NULL); panel_return_val_if_fail (WNCK_IS_WINDOW (child->window), NULL); mi = gtk_image_menu_item_new (); exo_binding_new (G_OBJECT (child->label), "label", G_OBJECT (mi), "label"); exo_binding_new (G_OBJECT (child->label), "label", G_OBJECT (mi), "tooltip-text"); label = gtk_bin_get_child (GTK_BIN (mi)); panel_return_val_if_fail (GTK_IS_LABEL (label), NULL); gtk_label_set_max_width_chars (GTK_LABEL (label), tasklist->menu_max_width_chars); gtk_label_set_ellipsize (GTK_LABEL (label), tasklist->ellipsize_mode); if (G_LIKELY (tasklist->menu_icon_size > 0)) { image = xfce_panel_image_new (); gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (mi), image); xfce_panel_image_set_size (XFCE_PANEL_IMAGE (image), tasklist->menu_icon_size); exo_binding_new (G_OBJECT (child->icon), "pixbuf", G_OBJECT (image), "pixbuf"); gtk_widget_show (image); } if (allow_wireframe) { g_object_ref (G_OBJECT (child->window)); g_signal_connect_data (G_OBJECT (mi), "enter-notify-event", G_CALLBACK (xfce_tasklist_button_enter_notify_event), child, xfce_tasklist_button_enter_notify_event_disconnected, 0); } g_signal_connect (G_OBJECT (mi), "button-press-event", G_CALLBACK (xfce_tasklist_button_button_press_event), child); g_signal_connect (G_OBJECT (mi), "button-release-event", G_CALLBACK (xfce_tasklist_button_button_release_event), child); /* TODO bold labels for urgent windows */ /* TODO item dnd */ return mi; } static void xfce_tasklist_button_activate (XfceTasklistChild *child, guint32 timestamp) { WnckWorkspace *workspace; gint window_x, window_y; gint workspace_width, workspace_height; gint screen_width, screen_height; gint viewport_x, viewport_y; panel_return_if_fail (XFCE_IS_TASKLIST (child->tasklist)); panel_return_if_fail (WNCK_IS_WINDOW (child->window)); panel_return_if_fail (WNCK_IS_SCREEN (child->tasklist->screen)); if (wnck_window_is_active (child->window) || wnck_window_transient_is_most_recently_activated (child->window)) { /* minimize does not work when this is assigned to the * middle mouse button */ if (child->tasklist->middle_click != XFCE_TASKLIST_MIDDLE_CLICK_MINIMIZE_WINDOW) wnck_window_minimize (child->window); } else { /* we only change worksapces/viewports for non-pinned windows * and if all workspaces/viewports are shown or if we have * all blinking enabled and the current button is blinking */ if ((child->tasklist->all_workspaces && !wnck_window_is_pinned (child->window)) || (child->tasklist->all_blinking && xfce_arrow_button_get_blinking (XFCE_ARROW_BUTTON (child->button)))) { workspace = wnck_window_get_workspace (child->window); /* only switch workspaces/viewports if switch_workspace is enabled or * we want to restore a minimized window to the current workspace/viewport */ if (workspace != NULL && (child->tasklist->switch_workspace || !wnck_window_is_minimized (child->window))) { if (G_UNLIKELY (wnck_workspace_is_virtual (workspace))) { if (!wnck_window_is_in_viewport (child->window, workspace)) { /* viewport info */ workspace_width = wnck_workspace_get_width (workspace); workspace_height = wnck_workspace_get_height (workspace); screen_width = wnck_screen_get_width (child->tasklist->screen); screen_height = wnck_screen_get_height (child->tasklist->screen); /* we only support multiple viewports like compiz has * (all equally spread across the screen) */ if ((workspace_width % screen_width) == 0 && (workspace_height % screen_height) == 0) { wnck_window_get_geometry (child->window, &window_x, &window_y, NULL, NULL); /* lookup nearest workspace edge */ viewport_x = window_x - (window_x % screen_width); viewport_x = CLAMP (viewport_x, 0, workspace_width - screen_width); viewport_y = window_y - (window_y % screen_height); viewport_y = CLAMP (viewport_y, 0, workspace_height - screen_height); /* move to the other viewport */ wnck_screen_move_viewport (child->tasklist->screen, viewport_x, viewport_y); } else { g_warning ("only viewport with equally distributed screens are supported: %dx%d & %dx%d", workspace_width, workspace_height, screen_width, screen_height); } } } else if (wnck_screen_get_active_workspace (child->tasklist->screen) != workspace) { /* switch to the other workspace before we activate the window */ wnck_workspace_activate (workspace, timestamp); gtk_main_iteration (); } } else if (workspace != NULL && wnck_workspace_is_virtual (workspace) && !wnck_window_is_in_viewport (child->window, workspace)) { /* viewport info */ workspace_width = wnck_workspace_get_width (workspace); workspace_height = wnck_workspace_get_height (workspace); screen_width = wnck_screen_get_width (child->tasklist->screen); screen_height = wnck_screen_get_height (child->tasklist->screen); /* we only support multiple viewports like compiz has * (all equaly spread across the screen) */ if ((workspace_width % screen_width) == 0 && (workspace_height % screen_height) == 0) { viewport_x = wnck_workspace_get_viewport_x (workspace); viewport_y = wnck_workspace_get_viewport_y (workspace); /* note that the x and y might be negative numbers, since they are relative * to the current screen, not to the edge of the screen they are on. this is * not a problem since the mod result will always be positive */ wnck_window_get_geometry (child->window, &window_x, &window_y, NULL, NULL); /* get the new screen position, with the same screen offset */ window_x = viewport_x + (window_x % screen_width); window_y = viewport_y + (window_y % screen_height); /* move the window */ wnck_window_set_geometry (child->window, WNCK_WINDOW_GRAVITY_CURRENT, WNCK_WINDOW_CHANGE_X | WNCK_WINDOW_CHANGE_Y, window_x, window_y, -1, -1); } else { g_warning ("only viewport with equally distributed screens are supported: %dx%d & %dx%d", workspace_width, workspace_height, screen_width, screen_height); } } } wnck_window_activate_transient (child->window, timestamp); } } static void xfce_tasklist_button_drag_data_get (GtkWidget *button, GdkDragContext *context, GtkSelectionData *selection_data, guint info, guint timestamp, XfceTasklistChild *child) { gulong xid; panel_return_if_fail (WNCK_IS_WINDOW (child->window)); xid = wnck_window_get_xid (child->window); gtk_selection_data_set (selection_data, gtk_selection_data_get_target (selection_data), 8, (guchar *)&xid, sizeof (gulong)); } static void xfce_tasklist_button_drag_begin (GtkWidget *button, GdkDragContext *context, XfceTasklistChild *child) { GdkPixbuf *pixbuf; GdkPixmap *pixmap; panel_return_if_fail (WNCK_IS_WINDOW (child->window)); if (child->tasklist->show_labels) { pixmap = gtk_widget_get_snapshot (button, NULL); if (pixmap != NULL) { gtk_drag_set_icon_pixmap (context, gdk_drawable_get_colormap (GDK_DRAWABLE (pixmap)), pixmap, NULL, 0, 0); g_object_unref (G_OBJECT (pixmap)); return; } } pixbuf = wnck_window_get_icon (child->window); if (G_LIKELY (pixbuf != NULL)) gtk_drag_set_icon_pixbuf (context, pixbuf, 0, 0); } static void xfce_tasklist_button_drag_data_received (GtkWidget *button, GdkDragContext *context, gint x, gint y, GtkSelectionData *selection_data, guint info, guint drag_time, XfceTasklistChild *child2) { GList *li, *sibling; gulong xid; XfceTasklistChild *child; XfceTasklist *tasklist = XFCE_TASKLIST (child2->tasklist); panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->sort_order != XFCE_TASKLIST_SORT_ORDER_DND) return; sibling = g_list_find (tasklist->windows, child2); panel_return_if_fail (sibling != NULL); if ((!xfce_tasklist_vertical (tasklist) && x >= button->allocation.width / 2) || (xfce_tasklist_vertical (tasklist) && y >= button->allocation.height / 2)) sibling = g_list_next (sibling); xid = *((gulong *) gtk_selection_data_get_data (selection_data)); for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; if (sibling != li /* drop on end previous button */ && child != child2 /* drop on the same button */ && g_list_next (li) != sibling /* drop start of next button */ && child->window != NULL && wnck_window_get_xid (child->window) == xid) { /* swap items */ tasklist->windows = g_list_delete_link (tasklist->windows, li); tasklist->windows = g_list_insert_before (tasklist->windows, sibling, child); gtk_widget_queue_resize (GTK_WIDGET (tasklist)); break; } } } static XfceTasklistChild * xfce_tasklist_button_new (WnckWindow *window, XfceTasklist *tasklist) { XfceTasklistChild *child; static guint unique_id_counter = 0; panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), NULL); panel_return_val_if_fail (WNCK_IS_WINDOW (window), NULL); /* avoid integer overflows */ if (G_UNLIKELY (unique_id_counter >= G_MAXUINT)) unique_id_counter = 0; child = xfce_tasklist_child_new (tasklist); child->type = CHILD_TYPE_WINDOW; child->window = window; child->class_group = wnck_window_get_class_group (window); child->unique_id = unique_id_counter++; /* drag and drop to the pager */ gtk_drag_source_set (child->button, GDK_BUTTON1_MASK, source_targets, G_N_ELEMENTS (source_targets), GDK_ACTION_MOVE); gtk_drag_dest_set (child->button, GTK_DEST_DEFAULT_DROP, source_targets, G_N_ELEMENTS (source_targets), GDK_ACTION_MOVE); g_signal_connect (G_OBJECT (child->button), "drag-data-get", G_CALLBACK (xfce_tasklist_button_drag_data_get), child); g_signal_connect (G_OBJECT (child->button), "drag-begin", G_CALLBACK (xfce_tasklist_button_drag_begin), child); g_signal_connect (G_OBJECT (child->button), "drag-data-received", G_CALLBACK (xfce_tasklist_button_drag_data_received), child); /* note that the same signals should be in the proxy menu item too */ g_signal_connect (G_OBJECT (child->button), "enter-notify-event", G_CALLBACK (xfce_tasklist_button_enter_notify_event), child); g_signal_connect (G_OBJECT (child->button), "button-press-event", G_CALLBACK (xfce_tasklist_button_button_press_event), child); g_signal_connect (G_OBJECT (child->button), "button-release-event", G_CALLBACK (xfce_tasklist_button_button_release_event), child); /* monitor window changes */ g_signal_connect (G_OBJECT (window), "icon-changed", G_CALLBACK (xfce_tasklist_button_icon_changed), child); g_signal_connect (G_OBJECT (window), "name-changed", G_CALLBACK (xfce_tasklist_button_name_changed), child); g_signal_connect (G_OBJECT (window), "state-changed", G_CALLBACK (xfce_tasklist_button_state_changed), child); g_signal_connect (G_OBJECT (window), "workspace-changed", G_CALLBACK (xfce_tasklist_button_workspace_changed), child); g_signal_connect (G_OBJECT (window), "geometry-changed", G_CALLBACK (xfce_tasklist_button_geometry_changed2), child); /* poke functions */ xfce_tasklist_button_icon_changed (window, child); xfce_tasklist_button_name_changed (NULL, child); /* insert */ tasklist->windows = g_list_insert_sorted_with_data (tasklist->windows, child, xfce_tasklist_button_compare, tasklist); return child; } /** * Group Buttons **/ static void xfce_tasklist_group_button_menu_minimize_all (XfceTasklistChild *group_child) { GSList *li; XfceTasklistChild *child; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { panel_return_if_fail (WNCK_IS_WINDOW (child->window)); wnck_window_minimize (child->window); } } } static void xfce_tasklist_group_button_menu_unminimize_all (XfceTasklistChild *group_child) { GSList *li; XfceTasklistChild *child; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { panel_return_if_fail (WNCK_IS_WINDOW (child->window)); wnck_window_unminimize (child->window, gtk_get_current_event_time ()); } } } static void xfce_tasklist_group_button_menu_maximize_all (XfceTasklistChild *group_child) { GSList *li; XfceTasklistChild *child; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { panel_return_if_fail (WNCK_IS_WINDOW (child->window)); wnck_window_maximize (child->window); } } } static void xfce_tasklist_group_button_menu_unmaximize_all (XfceTasklistChild *group_child) { GSList *li; XfceTasklistChild *child; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { panel_return_if_fail (WNCK_IS_WINDOW (child->window)); wnck_window_unmaximize (child->window); } } } static void xfce_tasklist_group_button_menu_close_all (XfceTasklistChild *group_child) { GSList *li; XfceTasklistChild *child; panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { panel_return_if_fail (WNCK_IS_WINDOW (child->window)); wnck_window_close (child->window, gtk_get_current_event_time ()); } } } static GtkWidget * xfce_tasklist_group_button_menu (XfceTasklistChild *group_child, gboolean action_menu_entries) { GSList *li; XfceTasklistChild *child; GtkWidget *mi; GtkWidget *menu; GtkWidget *image; panel_return_val_if_fail (XFCE_IS_TASKLIST (group_child->tasklist), NULL); panel_return_val_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group), NULL); menu = gtk_menu_new (); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) { mi = xfce_tasklist_button_proxy_menu_item (child, !action_menu_entries); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); gtk_widget_show (mi); if (action_menu_entries) gtk_menu_item_set_submenu (GTK_MENU_ITEM (mi), wnck_action_menu_new (child->window)); } } if (action_menu_entries) { mi = gtk_separator_menu_item_new (); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); gtk_widget_show (mi); mi = gtk_image_menu_item_new_with_mnemonic (_("Mi_nimize All")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); g_signal_connect_swapped (G_OBJECT (mi), "activate", G_CALLBACK (xfce_tasklist_group_button_menu_minimize_all), group_child); gtk_widget_show (mi); image = gtk_image_new_from_stock ("wnck-stock-minimize", GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (mi), image); gtk_widget_show (image); mi = gtk_image_menu_item_new_with_mnemonic (_("Un_minimize All")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); g_signal_connect_swapped (G_OBJECT (mi), "activate", G_CALLBACK (xfce_tasklist_group_button_menu_unminimize_all), group_child); gtk_widget_show (mi); mi = gtk_image_menu_item_new_with_mnemonic (_("Ma_ximize All")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); g_signal_connect_swapped (G_OBJECT (mi), "activate", G_CALLBACK (xfce_tasklist_group_button_menu_maximize_all), group_child); gtk_widget_show (mi); image = gtk_image_new_from_stock ("wnck-stock-maximize", GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (mi), image); gtk_widget_show (image); mi = gtk_image_menu_item_new_with_mnemonic (_("_Unmaximize All")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); g_signal_connect_swapped (G_OBJECT (mi), "activate", G_CALLBACK (xfce_tasklist_group_button_menu_unmaximize_all), group_child); gtk_widget_show (mi); mi = gtk_separator_menu_item_new (); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); gtk_widget_show (mi); mi = gtk_image_menu_item_new_with_mnemonic(_("_Close All")); gtk_menu_shell_append (GTK_MENU_SHELL (menu), mi); g_signal_connect_swapped (G_OBJECT (mi), "activate", G_CALLBACK (xfce_tasklist_group_button_menu_close_all), group_child); gtk_widget_show (mi); image = gtk_image_new_from_stock ("wnck-stock-delete", GTK_ICON_SIZE_MENU); gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (mi), image); gtk_widget_show (image); } return menu; } static void xfce_tasklist_group_button_menu_destroy (GtkWidget *menu, XfceTasklistChild *group_child) { panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (GTK_IS_TOGGLE_BUTTON (group_child->button)); panel_return_if_fail (GTK_IS_WIDGET (menu)); gtk_widget_destroy (menu); gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (group_child->button), FALSE); #ifdef GDK_WINDOWING_X11 /* make sure the wireframe is hidden */ xfce_tasklist_wireframe_hide (group_child->tasklist); #endif } static gboolean xfce_tasklist_group_button_button_press_event (GtkWidget *button, GdkEventButton *event, XfceTasklistChild *group_child) { GtkWidget *panel_plugin; GtkWidget *menu; panel_return_val_if_fail (XFCE_IS_TASKLIST (group_child->tasklist), FALSE); panel_return_val_if_fail (group_child->type == CHILD_TYPE_GROUP, FALSE); if (event->type != GDK_BUTTON_PRESS || xfce_taskbar_is_locked (group_child->tasklist)) return FALSE; /* send the event to the panel plugin if control is pressed */ if (PANEL_HAS_FLAG (event->state, GDK_CONTROL_MASK)) { /* send the event to the panel plugin */ panel_plugin = xfce_tasklist_get_panel_plugin (group_child->tasklist); if (G_LIKELY (panel_plugin != NULL)) gtk_widget_event (panel_plugin, (GdkEvent *) event); return TRUE; } if (event->button == 1 || event->button == 3) { menu = xfce_tasklist_group_button_menu (group_child, event->button == 3); g_signal_connect (G_OBJECT (menu), "selection-done", G_CALLBACK (xfce_tasklist_group_button_menu_destroy), group_child); gtk_menu_attach_to_widget (GTK_MENU (menu), button, NULL); gtk_menu_popup (GTK_MENU (menu), NULL, NULL, xfce_panel_plugin_position_menu, xfce_tasklist_get_panel_plugin (group_child->tasklist), event->button, event->time); return TRUE; } return FALSE; } static void xfce_tasklist_group_button_name_changed (WnckClassGroup *class_group, XfceTasklistChild *group_child) { const gchar *name; gchar *label; guint n_windows; GSList *li; XfceTasklistChild *child; panel_return_if_fail (class_group == NULL || group_child->class_group == class_group); panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); /* count number of windows in the menu */ for (li = group_child->windows, n_windows = 0; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button) && child->type == CHILD_TYPE_GROUP_MENU) n_windows++; } /* create the button label */ name = wnck_class_group_get_name (group_child->class_group); if (!exo_str_is_empty (name)) label = g_strdup_printf ("%s (%d)", name, n_windows); else label = g_strdup_printf ("(%d)", n_windows); gtk_label_set_text (GTK_LABEL (group_child->label), label); g_free (label); /* don't sort if there is no need to update the sorting (ie. only number * of windows is changed or button is not inserted in the tasklist yet */ if (class_group != NULL) xfce_tasklist_sort (group_child->tasklist); } static void xfce_tasklist_group_button_icon_changed (WnckClassGroup *class_group, XfceTasklistChild *group_child) { GdkPixbuf *pixbuf; panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (WNCK_IS_CLASS_GROUP (class_group)); panel_return_if_fail (group_child->class_group == class_group); panel_return_if_fail (XFCE_IS_PANEL_IMAGE (group_child->icon)); /* 0 means icons are disabled, although the grouping button does * not use lucient icons */ if (group_child->tasklist->minimized_icon_lucency == 0) return; /* get the class group icon */ if (group_child->tasklist->show_labels) pixbuf = wnck_class_group_get_mini_icon (class_group); else pixbuf = wnck_class_group_get_icon (class_group); if (G_LIKELY (pixbuf != NULL)) xfce_panel_image_set_from_pixbuf (XFCE_PANEL_IMAGE (group_child->icon), pixbuf); else xfce_panel_image_clear (XFCE_PANEL_IMAGE (group_child->icon)); } static void xfce_tasklist_group_button_remove (XfceTasklistChild *group_child) { GSList *li; guint n; XfceTasklistChild *child; /* leave if hash table triggers this function where no group * child is set */ if (group_child == NULL) return; panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (g_list_find (group_child->tasklist->windows, group_child) != NULL); /* disconnect from all the group watch functions */ n = g_signal_handlers_disconnect_matched (G_OBJECT (group_child->class_group), G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, group_child); panel_return_if_fail (n == 2); /* disconnect from visible windows */ for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; panel_return_if_fail (GTK_IS_BUTTON (child->button)); n = g_signal_handlers_disconnect_matched (G_OBJECT (child->button), G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, group_child); panel_return_if_fail (n == 2); } g_slist_free (group_child->windows); group_child->windows = NULL; /* destroy the button, this will free the remaining child * data in the container remove function */ gtk_widget_destroy (group_child->button); } static void xfce_tasklist_group_button_child_visible_changed (XfceTasklistChild *group_child) { XfceTasklistChild *child; GSList *li; gint visible_counter = 0; XfceTasklistChildType type; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (group_child->tasklist->grouping != XFCE_TASKLIST_GROUPING_NEVER); for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button)) visible_counter++; } if (visible_counter > 1) { /* show the button and take the windows */ gtk_widget_show (group_child->button); type = CHILD_TYPE_GROUP_MENU; } else { /* hide the button and ungroup the buttons */ gtk_widget_hide (group_child->button); type = CHILD_TYPE_WINDOW; } for (li = group_child->windows; li != NULL; li = li->next) { child = li->data; if (GTK_WIDGET_VISIBLE (child->button)) child->type = type; } gtk_widget_queue_resize (GTK_WIDGET (group_child->tasklist)); xfce_tasklist_group_button_name_changed (NULL, group_child); } static void xfce_tasklist_group_button_child_destroyed (XfceTasklistChild *group_child, GtkWidget *child_button) { GSList *li, *lnext; XfceTasklistChild *child; guint n_children; panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (GTK_IS_BUTTON (child_button)); panel_return_if_fail (group_child->windows != NULL); panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); for (li = group_child->windows, n_children = 0; li != NULL; li = lnext) { child = li->data; lnext = li->next; if (G_UNLIKELY (child->button == child_button)) group_child->windows = g_slist_delete_link (group_child->windows, li); else n_children++; } if ((group_child->tasklist->grouping == XFCE_TASKLIST_GROUPING_ALWAYS && n_children > 0)) #if 0 || (group_child->tasklist->grouping == XFCE_TASKLIST_GROUPING_AUTO && n_children > 1)) #endif { xfce_tasklist_group_button_child_visible_changed (group_child); xfce_tasklist_group_button_name_changed (NULL, group_child); } else { /* self destroy */ g_object_ref (G_OBJECT (group_child->class_group)); g_hash_table_replace (group_child->tasklist->class_groups, group_child->class_group, NULL); } } static void xfce_tasklist_group_button_add_window (XfceTasklistChild *group_child, XfceTasklistChild *window_child) { panel_return_if_fail (group_child->type == CHILD_TYPE_GROUP); panel_return_if_fail (window_child->type != CHILD_TYPE_GROUP); panel_return_if_fail (WNCK_IS_CLASS_GROUP (group_child->class_group)); panel_return_if_fail (WNCK_IS_WINDOW (window_child->window)); panel_return_if_fail (window_child->class_group == group_child->class_group); panel_return_if_fail (XFCE_IS_TASKLIST (group_child->tasklist)); panel_return_if_fail (g_slist_find (group_child->windows, window_child) == NULL); /* watch child visibility changes */ g_signal_connect_swapped (G_OBJECT (window_child->button), "notify::visible", G_CALLBACK (xfce_tasklist_group_button_child_visible_changed), group_child); g_signal_connect_swapped (G_OBJECT (window_child->button), "destroy", G_CALLBACK (xfce_tasklist_group_button_child_destroyed), group_child); /* add to internal list */ group_child->windows = g_slist_prepend (group_child->windows, window_child); /* update visibility */ xfce_tasklist_group_button_child_visible_changed (group_child); } static XfceTasklistChild * xfce_tasklist_group_button_new (WnckClassGroup *class_group, XfceTasklist *tasklist) { XfceTasklistChild *child; panel_return_val_if_fail (XFCE_IS_TASKLIST (tasklist), NULL); panel_return_val_if_fail (WNCK_IS_CLASS_GROUP (class_group), NULL); child = xfce_tasklist_child_new (tasklist); child->type = CHILD_TYPE_GROUP; child->class_group = class_group; /* note that the same signals should be in the proxy menu item too */ g_signal_connect (G_OBJECT (child->button), "button-press-event", G_CALLBACK (xfce_tasklist_group_button_button_press_event), child); /* monitor class group changes */ g_signal_connect (G_OBJECT (class_group), "icon-changed", G_CALLBACK (xfce_tasklist_group_button_icon_changed), child); g_signal_connect (G_OBJECT (class_group), "name-changed", G_CALLBACK (xfce_tasklist_group_button_name_changed), child); /* poke functions */ xfce_tasklist_group_button_icon_changed (class_group, child); xfce_tasklist_group_button_name_changed (NULL, child); /* insert */ tasklist->windows = g_list_insert_sorted_with_data (tasklist->windows, child, xfce_tasklist_button_compare, tasklist); return child; } /** * Potential Public Functions **/ static void xfce_tasklist_set_include_all_workspaces (XfceTasklist *tasklist, gboolean all_workspaces) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); all_workspaces = !!all_workspaces; if (tasklist->all_workspaces != all_workspaces) { tasklist->all_workspaces = all_workspaces; if (tasklist->screen != NULL) { /* update visibility of buttons */ xfce_tasklist_active_workspace_changed (tasklist->screen, NULL, tasklist); /* make sure sorting is ok */ xfce_tasklist_sort (tasklist); } } } static void xfce_tasklist_set_include_all_monitors (XfceTasklist *tasklist, gboolean all_monitors) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); all_monitors = !!all_monitors; if (tasklist->all_monitors != all_monitors) { tasklist->all_monitors = all_monitors; /* set the geometry to invalid or update the geometry and * update the visibility of the buttons */ if (all_monitors) { xfce_tasklist_geometry_set_invalid (tasklist); /* update visibility of buttons */ xfce_tasklist_active_workspace_changed (tasklist->screen, NULL, tasklist); } else if (tasklist->gdk_screen != NULL) { xfce_tasklist_gdk_screen_changed (tasklist->gdk_screen, tasklist); } } } static void xfce_tasklist_set_button_relief (XfceTasklist *tasklist, GtkReliefStyle button_relief) { GList *li; XfceTasklistChild *child; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->button_relief != button_relief) { tasklist->button_relief = button_relief; /* change the relief of all buttons in the list */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; gtk_button_set_relief (GTK_BUTTON (child->button), button_relief); } /* arrow button for overflow menu */ gtk_button_set_relief (GTK_BUTTON (tasklist->arrow_button), button_relief); } } static void xfce_tasklist_set_show_labels (XfceTasklist *tasklist, gboolean show_labels) { GList *li; XfceTasklistChild *child; panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); show_labels = !!show_labels; if (tasklist->show_labels != show_labels) { tasklist->show_labels = show_labels; /* change the mode of all the buttons */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; /* show or hide the label */ if (show_labels) { gtk_widget_show (child->label); gtk_box_set_child_packing (GTK_BOX (child->box), child->icon, FALSE, FALSE, 0, GTK_PACK_START); } else { gtk_widget_hide (child->label); gtk_box_set_child_packing (GTK_BOX (child->box), child->icon, TRUE, TRUE, 0, GTK_PACK_START); } /* update the icon (we use another size for * icon box mode) */ xfce_tasklist_button_icon_changed (child->window, child); } } } static void xfce_tasklist_set_show_only_minimized (XfceTasklist *tasklist, gboolean only_minimized) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); only_minimized = !!only_minimized; if (tasklist->only_minimized != only_minimized) { tasklist->only_minimized = only_minimized; /* update all windows */ if (tasklist->screen != NULL) xfce_tasklist_active_workspace_changed (tasklist->screen, NULL, tasklist); } } static void xfce_tasklist_set_show_wireframes (XfceTasklist *tasklist, gboolean show_wireframes) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); tasklist->show_wireframes = !!show_wireframes; #ifdef GDK_WINDOWING_X11 /* destroy the window if needed */ xfce_tasklist_wireframe_destroy (tasklist); #endif } static void xfce_tasklist_set_grouping (XfceTasklist *tasklist, XfceTasklistGrouping grouping) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); /* TODO avoid overflow, because we allows + 1 in the object */ if (grouping > XFCE_TASKLIST_GROUPING_MAX) grouping = XFCE_TASKLIST_GROUPING_MAX; if (tasklist->grouping != grouping) { tasklist->grouping = grouping; if (tasklist->screen != NULL) { xfce_tasklist_disconnect_screen (tasklist); xfce_tasklist_connect_screen (tasklist); } } } static void xfce_tasklist_update_orientation (XfceTasklist *tasklist) { gboolean horizontal; GList *li; XfceTasklistChild *child; horizontal = !xfce_tasklist_vertical (tasklist); /* update the tasklist */ for (li = tasklist->windows; li != NULL; li = li->next) { child = li->data; /* update task box */ xfce_hvbox_set_orientation (XFCE_HVBOX (child->box), horizontal ? GTK_ORIENTATION_HORIZONTAL : GTK_ORIENTATION_VERTICAL); /* update the label */ if (horizontal) { /* gtk_box_reorder_child (GTK_BOX (child->box), child->icon, 0); */ gtk_misc_set_alignment (GTK_MISC (child->label), 0.0, 0.5); gtk_label_set_angle (GTK_LABEL (child->label), 0); gtk_label_set_ellipsize (GTK_LABEL (child->label), child->tasklist->ellipsize_mode); } else { /* gtk_box_reorder_child (GTK_BOX (child->box), child->icon, -1); */ gtk_misc_set_alignment (GTK_MISC (child->label), 0.50, 0.00); gtk_label_set_angle (GTK_LABEL (child->label), 270); gtk_label_set_ellipsize (GTK_LABEL (child->label), PANGO_ELLIPSIZE_NONE); } } gtk_widget_queue_resize (GTK_WIDGET (tasklist)); } void xfce_tasklist_set_nrows (XfceTasklist *tasklist, gint nrows) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); panel_return_if_fail (nrows >= 1); if (tasklist->nrows != nrows) { tasklist->nrows = nrows; gtk_widget_queue_resize (GTK_WIDGET (tasklist)); } } void xfce_tasklist_set_mode (XfceTasklist *tasklist, XfcePanelPluginMode mode) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->mode != mode) { tasklist->mode = mode; xfce_tasklist_update_orientation (tasklist); } } void xfce_tasklist_set_size (XfceTasklist *tasklist, gint size) { panel_return_if_fail (XFCE_IS_TASKLIST (tasklist)); if (tasklist->size != size) { tasklist->size = size; gtk_widget_queue_resize (GTK_WIDGET (tasklist)); } } void xfce_tasklist_update_monitor_geometry (XfceTasklist *tasklist) { if (tasklist->update_monitor_geometry_id == 0) { tasklist->update_monitor_geometry_id = g_idle_add_full (G_PRIORITY_LOW, xfce_tasklist_update_monitor_geometry_idle, tasklist, xfce_tasklist_update_monitor_geometry_idle_destroy); } }
Sidnioulz/SandboxXfce4Panel
plugins/tasklist/tasklist-widget.c
C
gpl-2.0
139,282
#ifndef ENGINEERING_SCREEN_H #define ENGINEERING_SCREEN_H #include "gui/gui2_overlay.h" #include "shipTemplate.h" #include "playerInfo.h" class GuiKeyValueDisplay; class GuiLabel; class GuiSlider; class GuiAutoLayout; class GuiImage; class GuiArrow; class GuiToggleButton; class GuiProgressbar; class EngineeringScreen : public GuiOverlay { private: GuiOverlay* background_gradient; GuiOverlay* background_crosses; GuiKeyValueDisplay* energy_display; GuiKeyValueDisplay* hull_display; GuiKeyValueDisplay* front_shield_display; GuiKeyValueDisplay* rear_shield_display; GuiLabel* power_label; GuiSlider* power_slider; GuiLabel* coolant_label; GuiSlider* coolant_slider; class SystemRow { public: GuiAutoLayout* layout; GuiToggleButton* button; GuiProgressbar* damage_bar; GuiLabel* damage_label; GuiProgressbar* heat_bar; GuiArrow* heat_arrow; GuiImage* heat_icon; GuiProgressbar* power_bar; GuiProgressbar* coolant_bar; }; std::vector<SystemRow> system_rows; GuiAutoLayout* system_effects_container; std::vector<GuiKeyValueDisplay*> system_effects; unsigned int system_effects_index; ESystem selected_system; float previous_energy_measurement; float previous_energy_level; float average_energy_delta; void addSystemEffect(string key, string value); void selectSystem(ESystem system); public: EngineeringScreen(GuiContainer* owner, ECrewPosition crew_position=engineering); virtual void onDraw(sf::RenderTarget& window) override; virtual void onHotkey(const HotkeyResult& key) override; }; #endif//ENGINEERING_SCREEN_H
tdelc/EmptyEpsilon
src/screens/crew6/engineeringScreen.h
C
gpl-2.0
1,718
/* packet-xyplex.c * Routines for xyplex packet dissection * * Copyright 2002 Randy McEoin <rmceoin@pe.com> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * Copied from packet-tftp.c * * 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 <glib.h> #include <epan/packet.h> #include <epan/conversation.h> void proto_register_xyplex(void); void proto_reg_handoff_xyplex(void); static int proto_xyplex = -1; static int hf_xyplex_type = -1; static int hf_xyplex_pad = -1; static int hf_xyplex_server_port = -1; static int hf_xyplex_return_port = -1; static int hf_xyplex_reserved = -1; static int hf_xyplex_reply = -1; static int hf_xyplex_data = -1; static gint ett_xyplex = -1; static dissector_handle_t xyplex_handle; #define UDP_PORT_XYPLEX 173 #define XYPLEX_REG_OK 0x00 #define XYPLEX_REG_QUEFULL 0x05 static const value_string xyplex_reg_vals[] = { { XYPLEX_REG_OK, "OK" }, { XYPLEX_REG_QUEFULL, "Queue Full" }, { 0, NULL } }; static int dissect_xyplex(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data _U_) { proto_tree *xyplex_tree; proto_item *ti; conversation_t *conversation; gint offset = 0; guint8 prototype; guint8 padding; guint16 server_port; guint16 return_port; guint16 reserved; guint16 reply; col_set_str(pinfo->cinfo, COL_PROTOCOL, "XYPLEX"); ti = proto_tree_add_item(tree, proto_xyplex, tvb, offset, -1, ENC_NA); xyplex_tree = proto_item_add_subtree(ti, ett_xyplex); if (pinfo->destport == UDP_PORT_XYPLEX) { /* This is a registration request from a Unix server * to the Xyplex server. The server_port indicates * which Xyplex serial port is desired. The * return_port tells the Xyplex server what TCP port * to open to the Unix server. */ prototype = tvb_get_guint8(tvb, offset); padding = tvb_get_guint8(tvb, offset+1); server_port = tvb_get_ntohs(tvb, offset+2); return_port = tvb_get_ntohs(tvb, offset+4); reserved = tvb_get_ntohs(tvb, offset+6); col_add_fstr(pinfo->cinfo, COL_INFO, "Registration Request: %d Return: %d", server_port, return_port); if (tree) { proto_tree_add_uint(xyplex_tree, hf_xyplex_type, tvb, offset, 1, prototype); proto_tree_add_uint(xyplex_tree, hf_xyplex_pad, tvb, offset+1, 1, padding); proto_tree_add_uint(xyplex_tree, hf_xyplex_server_port, tvb, offset+2, 2, server_port); proto_tree_add_uint(xyplex_tree, hf_xyplex_return_port, tvb, offset+4, 2, return_port); proto_tree_add_uint(xyplex_tree, hf_xyplex_reserved, tvb, offset+6, 2, reserved); } offset += 8; /* Look for all future TCP conversations between the * requestiong server and the Xyplex host using the * return_port. */ conversation = find_conversation(pinfo->fd->num, &pinfo->src, &pinfo->dst, PT_TCP, return_port, 0, NO_PORT_B); if (conversation == NULL) { conversation = conversation_new(pinfo->fd->num, &pinfo->src, &pinfo->dst, PT_TCP, return_port, 0, NO_PORT2); conversation_set_dissector(conversation, xyplex_handle); } return offset; } if (pinfo->srcport == UDP_PORT_XYPLEX) { prototype = tvb_get_guint8(tvb, offset); padding = tvb_get_guint8(tvb, offset+1); reply = tvb_get_ntohs(tvb, offset+2); col_add_fstr(pinfo->cinfo, COL_INFO, "Registration Reply: %s", val_to_str(reply, xyplex_reg_vals, "Unknown (0x%02x)")); if (tree) { proto_tree_add_uint(xyplex_tree, hf_xyplex_type, tvb, offset, 1, prototype); proto_tree_add_uint(xyplex_tree, hf_xyplex_pad, tvb, offset+1, 1, padding); proto_tree_add_uint(xyplex_tree, hf_xyplex_reply, tvb, offset+2, 2, reply); } offset += 4; return offset; } /* * This must be the TCP data stream. This will just be * the raw data being transfered from the remote server * and the Xyplex serial port. */ col_add_fstr(pinfo->cinfo, COL_INFO, "%d > %d Data", pinfo->srcport, pinfo->destport); proto_tree_add_item(xyplex_tree, hf_xyplex_data, tvb, offset, -1, ENC_NA); return tvb_reported_length_remaining(tvb, offset); } void proto_register_xyplex(void) { static hf_register_info hf[] = { { &hf_xyplex_type, { "Type", "xyplex.type", FT_UINT8, BASE_DEC, NULL, 0x0, "Protocol type", HFILL }}, { &hf_xyplex_pad, { "Pad", "xyplex.pad", FT_UINT8, BASE_DEC, NULL, 0x0, "Padding", HFILL }}, { &hf_xyplex_server_port, { "Server Port", "xyplex.server_port", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_xyplex_return_port, { "Return Port", "xyplex.return_port", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_xyplex_reserved, { "Reserved field", "xyplex.reserved", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, { &hf_xyplex_reply, { "Registration Reply", "xyplex.reply", FT_UINT16, BASE_DEC, VALS(xyplex_reg_vals), 0x0, NULL, HFILL }}, { &hf_xyplex_data, { "Data", "xyplex.data", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }}, }; static gint *ett[] = { &ett_xyplex, }; proto_xyplex = proto_register_protocol("Xyplex", "XYPLEX", "xyplex"); proto_register_field_array(proto_xyplex, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_xyplex(void) { xyplex_handle = new_create_dissector_handle(dissect_xyplex, proto_xyplex); dissector_add_uint("udp.port", UDP_PORT_XYPLEX, xyplex_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local Variables: * c-basic-offset: 2 * tab-width: 8 * indent-tabs-mode: nil * End: * * ex: set shiftwidth=2 tabstop=8 expandtab: * :indentSize=2:tabSize=8:noTabs=true: */
weizhenwei/wireshark
epan/dissectors/packet-xyplex.c
C
gpl-2.0
6,962
.data str1: .asciiz " - " .text .globl main main: li $s0,0 move $s1,$a0 move $s2,$a1 for: bge $s0,$s1,endfor li $v0,11 li $a0,0x0A syscall li $v0,4 sll $s3,$s0,2 addu $s3,$s3,$s2 lw $s4,0($s3) move $a0,$s4 syscall la $a0,str1 li $v0,4 syscall move $a0,$s4 addi $sp,$sp,-4 sw $ra,0($sp) jal strlen move $a0,$v0 lw $ra,0($sp) addi $sp,$sp,4 li $v0,1 syscall addi $s0,$s0,1 j for endfor: jr $ra strlen: li $t4,0 move $t1,$a0 while: lb $t2,0($t1) beq $t2,'\0',endwhile addi $t1,$t1,1 addi $t4,$t4,1 j while endwhile: move $v0,$t4 jr $ra
diogodanielsoaresferreira/AssemblyExercises
Aula 8/A7Ex2.asm
Assembly
gpl-2.0
571
#ifndef _OMFS_H #define _OMFS_H #include <linux/module.h> #include <linux/fs.h> #include "omfs_fs.h" /* In-memory structures */ struct omfs_sb_info { u64 s_num_blocks; u64 s_bitmap_ino; u64 s_root_ino; u32 s_blocksize; u32 s_mirrors; u32 s_sys_blocksize; u32 s_clustersize; int s_block_shift; unsigned long **s_imap; int s_imap_size; struct mutex s_bitmap_lock; int s_uid; int s_gid; int s_dmask; int s_fmask; }; /* convert a cluster number to a scaled block number */ static inline sector_t clus_to_blk(struct omfs_sb_info *sbi, sector_t block) { return block << sbi->s_block_shift; } static inline struct omfs_sb_info *OMFS_SB(struct super_block *sb) { return sb->s_fs_info; } /* bitmap.c */ extern unsigned long omfs_count_free(struct super_block *sb); extern int omfs_allocate_block(struct super_block *sb, u64 block); extern int omfs_allocate_range(struct super_block *sb, int min_request, int max_request, u64 *return_block, int *return_size); extern int omfs_clear_range(struct super_block *sb, u64 block, int count); /* dir.c */ extern struct file_operations omfs_dir_operations; extern const struct inode_operations omfs_dir_inops; extern int omfs_make_empty(struct inode *inode, struct super_block *sb); extern int omfs_is_bad(struct omfs_sb_info *sbi, struct omfs_header *header, u64 fsblock); /* file.c */ extern struct file_operations omfs_file_operations; extern const struct inode_operations omfs_file_inops; extern const struct address_space_operations omfs_aops; extern void omfs_make_empty_table(struct buffer_head *bh, int offset); extern int omfs_shrink_inode(struct inode *inode); /* inode.c */ extern struct inode *omfs_iget(struct super_block *sb, ino_t inode); extern struct inode *omfs_new_inode(struct inode *dir, int mode); extern int omfs_reserve_block(struct super_block *sb, sector_t block); extern int omfs_find_empty_block(struct super_block *sb, int mode, ino_t *ino); extern int omfs_sync_inode(struct inode *inode); #endif
gzdaoke/linux2.6.32_kernel
fs/omfs/omfs.h
C
gpl-2.0
1,991
/* * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.api.recording.state; import jdk.jfr.Recording; import jdk.jfr.RecordingState; import jdk.test.lib.jfr.CommonHelper; import jdk.test.lib.jfr.VoidFunction; /** * @test * @summary Test Recording state with concurrent recordings * @key jfr * * @library /lib / * @run main/othervm jdk.jfr.api.recording.state.TestStateMultiple */ public class TestStateMultiple { public static void main(String[] args) throws Throwable { Recording rA = new Recording(); CommonHelper.verifyRecordingState(rA, RecordingState.NEW); verifyIllegalState(() -> rA.stop(), "stop() when not started"); rA.start(); CommonHelper.verifyRecordingState(rA, RecordingState.RUNNING); Recording rB = new Recording(); CommonHelper.verifyRecordingState(rA, RecordingState.RUNNING); verifyIllegalState(() -> rA.start(), "double start()"); CommonHelper.verifyRecordingState(rB, RecordingState.NEW); verifyIllegalState(() -> rB.stop(), "stop() when not started"); rB.start(); CommonHelper.verifyRecordingState(rA, RecordingState.RUNNING); CommonHelper.verifyRecordingState(rB, RecordingState.RUNNING); rB.stop(); CommonHelper.verifyRecordingState(rA, RecordingState.RUNNING); CommonHelper.verifyRecordingState(rB, RecordingState.STOPPED); verifyIllegalState(() -> rB.start(), "start() after stop()"); rB.close(); CommonHelper.verifyRecordingState(rA, RecordingState.RUNNING); CommonHelper.verifyRecordingState(rB, RecordingState.CLOSED); verifyIllegalState(() -> rB.start(), "start() after close()"); rA.stop(); CommonHelper.verifyRecordingState(rA, RecordingState.STOPPED); verifyIllegalState(() -> rA.start(), "start() after stop()"); CommonHelper.verifyRecordingState(rB, RecordingState.CLOSED); rA.close(); CommonHelper.verifyRecordingState(rA, RecordingState.CLOSED); CommonHelper.verifyRecordingState(rB, RecordingState.CLOSED); verifyIllegalState(() -> rA.stop(), "stop() after close()"); verifyIllegalState(() -> rB.start(), "start() after close()"); } private static void verifyIllegalState(VoidFunction f, String msg) throws Throwable { CommonHelper.verifyException(f, msg, IllegalStateException.class); } }
openjdk/jdk8u
jdk/test/jdk/jfr/api/recording/state/TestStateMultiple.java
Java
gpl-2.0
3,580
/****************************************************************************** * Product: ADempiereLBR - ADempiere Localization Brazil * * This program is free software; you can redistribute it and/or modify it * * under the terms 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. * * 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. * *****************************************************************************/ package org.adempierelbr.util; public abstract class RemoverAcentos { static String acentuado = "çÇáéíóúýÁÉÍÓÚÝàèìòùÀÈÌÒÙãõñäëïöüÿÄËÏÖÜÃÕÑâêîôûÂÊÎÔÛ¹²³ªº"; static String semAcento = "cCaeiouyAEIOUYaeiouAEIOUaonaeiouyAEIOUAONaeiouAEIOU123ao"; static char[] tabela; static { tabela = new char[256]; for (int i = 0; i < tabela.length; ++i) { tabela[i] = (char) i; } for (int i = 0; i < acentuado.length(); ++i) { tabela[acentuado.charAt(i)] = semAcento.charAt(i); } } public static StringBuffer remover(final StringBuffer s){ return new StringBuffer(RemoverAcentos.remover(s.toString())); } public static String remover(final String s) { StringBuffer sb = new StringBuffer(); if (s == null) return ""; for (int i = 0; i < s.length(); ++i) { char ch = s.charAt(i); if (ch < 256) { sb.append(removeSpecial(tabela[ch])); } else { sb.append(removeSpecial(ch)); } } String retorno = sb.toString(); retorno = retorno.replaceAll("½", "1/2").replaceAll("¼", "1/4").replaceAll("¾", "3/4"); retorno = retorno.replaceAll("\"", " ").replaceAll("[œ*߃µøπæΩ]", " "); return retorno.trim(); } private static String removeSpecial(char value){ if (Character.isLetterOrDigit(value) || String.valueOf(value).matches("[!?$%()--+/;:.,]") || value == ' '){ return String.valueOf(value); } return ""; } }
arthurmelo88/palmetalADP
adempierelbr/base/src/org/adempierelbr/util/RemoverAcentos.java
Java
gpl-2.0
2,403
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_COCOA_TOOLBAR_TOOLBAR_BUTTON_H_ #define CHROME_BROWSER_UI_COCOA_TOOLBAR_TOOLBAR_BUTTON_H_ #pragma once #import <Cocoa/Cocoa.h> @interface ToolbarButton : NSButton { @protected BOOL handleMiddleClick_; BOOL handlingMiddleClick_; } @property(assign, nonatomic) BOOL handleMiddleClick; @end @interface ToolbarButton (ExposedForTesting) - (BOOL)shouldHandleEvent:(NSEvent*)theEvent; @end #endif
qtekfun/htcDesire820Kernel
external/chromium/chrome/browser/ui/cocoa/toolbar/toolbar_button.h
C
gpl-2.0
614
/* * JCE Editor 2.2.0 * @package JCE * @url http://www.joomlacontenteditor.net * @copyright Copyright (C) 2006 - 2012 Ryan Demmer. All rights reserved * @license GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html * @date 20 June 2012 * 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. * * NOTE : Javascript files have been compressed for speed and can be uncompressed using http://jsbeautifier.org/ */ (function(){var WFExtensions={types:{},add:function(n,o){this[n]=o;return this[n];},addType:function(n){this.types[n]={};},addExtension:function(type,n,o){if(typeof this.types[type]=='undefined'){this.addType(type);} this.types[type][n]=o;},getType:function(type){return this.types[type]||false;},getExtension:function(type,ext){var s=this.getType(type);return s[ext];}};window.WFExtensions=WFExtensions;})();
viollarr/alab
components/com_jce/editor/libraries/js/extensions.js
JavaScript
gpl-2.0
1,410
/* Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.serotonin.mango.db.dao; import java.util.List; import javax.sql.DataSource; import org.scada_lts.mango.adapter.MangoPointValues; import org.scada_lts.mango.service.PointValueService; import org.springframework.dao.ConcurrencyFailureException; import com.serotonin.mango.rt.dataImage.PointValueTime; import com.serotonin.mango.rt.dataImage.SetPointSource; import com.serotonin.mango.vo.AnonymousUser; import com.serotonin.mango.vo.bean.LongPair; public class PointValueDao { private MangoPointValues pointValueService; public PointValueDao() { initializePrivateVariables(); } public PointValueDao(DataSource dataSource) { initializePrivateVariables(); } /** * Only the PointValueCache should call this method during runtime. Do not * use. */ public PointValueTime savePointValueSync(int pointId, PointValueTime pointValue, SetPointSource source) { long id = savePointValueImpl(pointId, pointValue, source, false); PointValueTime savedPointValue; int retries = 5; while (true) { try { savedPointValue = pointValueService.getPointValue(id); break; } catch (ConcurrencyFailureException e) { if (retries <= 0) throw e; retries--; } } return savedPointValue; } /** * Only the PointValueCache should call this method during runtime. Do not * use. */ public void savePointValueAsync(int pointId, PointValueTime pointValue, SetPointSource source) { long id = savePointValueImpl(pointId, pointValue, source, true); if (id != -1) pointValueService.clearUnsavedPointValues(); } long savePointValueImpl(final int pointId, final PointValueTime pointValue, final SetPointSource source, boolean async) { return pointValueService.savePointValueImpl(pointId, pointValue, source, async); } public void savePointValue(int pointId, PointValueTime pointValue) { savePointValueImpl(pointId, pointValue, new AnonymousUser(), true); } public List<PointValueTime> getPointValues(int dataPointId, long since) { return pointValueService.getPointValues(dataPointId, since); } public List<PointValueTime> getPointValuesBetween(int dataPointId, long from, long to) { return pointValueService.getPointValuesBetween(dataPointId, from, to); } public List<PointValueTime> getLatestPointValues(int dataPointId, int limit) { return pointValueService.getLatestPointValues(dataPointId, limit); } public List<PointValueTime> getLatestPointValues(int dataPointId, int limit, long before) { return pointValueService.getLatestPointValues(dataPointId, limit, before); } public PointValueTime getLatestPointValue(int dataPointId) { return pointValueService.getLatestPointValue(dataPointId); } public PointValueTime getPointValueBefore(int dataPointId, long time) { return pointValueService.getPointValueBefore(dataPointId, time); } public PointValueTime getPointValueAt(int dataPointId, long time) { return pointValueService.getPointValueAt(dataPointId, time); } public long deletePointValuesBefore(int dataPointId, long time) { return pointValueService.deletePointValuesBeforeWithOutLast(dataPointId, time); } public long deletePointValues(int dataPointId) { return pointValueService.deletePointValues(dataPointId); } public long deleteAllPointData() { return pointValueService.deleteAllPointValue(); } public long deletePointValuesWithMismatchedType(int dataPointId, int dataType) { return pointValueService.deletePointValuesWithMismatchedType(dataPointId, dataType); } public void compressTables() { //TODO rewrite because not have ejt //Common.ctx.getDatabaseAccess().executeCompress(ejt); } public long dateRangeCount(int dataPointId, long from, long to) { return pointValueService.dateRangeCount(dataPointId, from, to); } public long getInceptionDate(int dataPointId) { return pointValueService.getInceptionDate(dataPointId); } public long getStartTime(List<Integer> dataPointIds) { return pointValueService.getStartTime(dataPointIds); } public long getEndTime(List<Integer> dataPointIds) { return pointValueService.getEndTime(dataPointIds); } public LongPair getStartAndEndTime(List<Integer> dataPointIds) { return pointValueService.getStartAndEndTime(dataPointIds); } public List<Long> getFiledataIds() { return pointValueService.getFiledataIds(); } private void initializePrivateVariables(){ pointValueService = new PointValueService(); } }
SCADA-LTS/Scada-LTS
src/com/serotonin/mango/db/dao/PointValueDao.java
Java
gpl-2.0
5,271
/** @file WT0124 Pool Thermometer decoder. Copyright (C) 2018 Benjamin Larsson 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. */ /** WT0124 Pool Thermometer decoder. 5e ba 9a 9f e1 34 01011110 10111010 10011010 10011111 11100001 00110100 5555RRRR RRRRTTTT TTTTTTTT UUCCFFFF XXXXXXXX ???????? - 5 = constant 5 - R = random power on id - T = 12 bits of temperature with 0x900 bias and scaled by 10 - U = unk, maybe battery indicator (display is missing one though) - C = channel - F = constant F - X = xor checksum - ? = unknown */ #include "decoder.h" static int wt1024_callback(r_device *decoder, bitbuffer_t *bitbuffer) { data_t *data; uint8_t *b; // bits of a row uint16_t sensor_rid; int16_t value; float temp_c; uint8_t channel; if (bitbuffer->bits_per_row[1] !=49) return DECODE_ABORT_LENGTH; /* select row after preamble */ b = bitbuffer->bb[1]; /* Validate constant */ if (b[0]>>4 != 0x5) { return DECODE_ABORT_EARLY; } /* Validate checksum */ if ((b[0]^b[1]^b[2]^b[3]) != b[4]) return DECODE_FAIL_MIC; /* Get rid */ sensor_rid = (b[0]&0x0F)<<4 | (b[1]&0x0F); /* Get temperature */ temp_c = ((((b[1] & 0xF) << 8) | b[2]) - 0x990) * 0.1f; /* Get channel */ channel = ((b[3]>>4) & 0x3); /* unk */ value = b[5]; if (decoder->verbose) { fprintf(stderr, "wt1024_callback:"); bitbuffer_print(bitbuffer); } data = data_make( "model", "", DATA_STRING, _X("WT0124-Pool","WT0124 Pool Thermometer"), _X("id","rid"), "Random ID", DATA_INT, sensor_rid, "channel", "Channel", DATA_INT, channel, "temperature_C", "Temperature", DATA_FORMAT, "%.1f C", DATA_DOUBLE, temp_c, "mic", "Integrity", DATA_STRING, "CHECKSUM", "data", "Data", DATA_INT, value, NULL); decoder_output_data(decoder, data); // Return 1 if message successfully decoded return 1; } /* * List of fields that may appear in the output * * Used to determine what fields will be output in what * order for this device when using -F csv. * */ static char *output_fields[] = { "model", "rid", // TODO: delete this "id", "channel", "temperature_C", "mic", "data", NULL, }; r_device wt1024 = { .name = "WT0124 Pool Thermometer", .modulation = OOK_PULSE_PWM, .short_width = 680, .long_width = 1850, .reset_limit = 30000, .gap_limit = 4000, .sync_width = 10000, .decode_fn = &wt1024_callback, .disabled = 0, .fields = output_fields, };
klattimer/rtl_433
src/devices/wt0124.c
C
gpl-2.0
3,008
#!/usr/bin/python import unittest import apt_pkg import apt.progress.base class TestCache(unittest.TestCase): """Test invocation of apt_pkg.Cache()""" def setUp(self): apt_pkg.init_config() apt_pkg.init_system() def test_wrong_invocation(self): """cache_invocation: Test wrong invocation.""" apt_cache = apt_pkg.Cache(progress=None) self.assertRaises(ValueError, apt_pkg.Cache, apt_cache) self.assertRaises(ValueError, apt_pkg.Cache, apt.progress.base.AcquireProgress()) self.assertRaises(ValueError, apt_pkg.Cache, 0) def test_proper_invocation(self): """cache_invocation: Test correct invocation.""" apt_cache = apt_pkg.Cache(progress=None) apt_depcache = apt_pkg.DepCache(apt_cache) if __name__ == "__main__": unittest.main()
suokko/python-apt
tests/test_cache_invocation.py
Python
gpl-2.0
863
<?php /* Smarty version 2.6.18, created on 2016-02-07 13:57:40 compiled from agency-access.html */ ?> <?php if ($this->_tpl_vars['infomessage']): ?> <div class='infomessage'> <?php echo $this->_tpl_vars['infomessage']; ?> </div> <?php endif; ?> <?php $_smarty_tpl_vars = $this->_tpl_vars; $this->_smarty_include(array('smarty_include_tpl_file' => "user-access.html", 'smarty_include_vars' => array('users' => $this->_tpl_vars['users']))); $this->_tpl_vars = $_smarty_tpl_vars; unset($_smarty_tpl_vars); ?>
AdRiverSoftware/AdServerProjectWebnock
var/templates_compiled/%%DA^DA7^DA767746%%agency-access.html.php
PHP
gpl-2.0
525
class Grib2_c < PACKMAN::Package url 'http://www.ncl.ucar.edu/Download/files/g2clib-1.5.0-patch.tar.gz' sha1 '3113b88e0295dbc64428edd87c0b583e774fb320' version '1.5.0' depends_on 'jasper' depends_on 'libpng' def install defs = 'DEFS=-DUSE_JPEG2000 -DUSE_PNG' defs << ' -D__64BIT__' if PACKMAN.os.x86_64? inc = "-I#{Jasper.include} -I#{Libpng.include}" PACKMAN.replace 'makefile', { /^DEFS=.*$/ => defs, /^(INC=.*)$/ => "\\1 #{inc}", /^CC=.*$/ => "CC=#{PACKMAN.compiler('c').command}", } PACKMAN.run 'make all' PACKMAN.mkdir include PACKMAN.cp 'grib2.h', include PACKMAN.mkdir lib PACKMAN.cp 'libgrib2c.a', lib end end
cheunghy/packman
packages/grib2_c.rb
Ruby
gpl-2.0
692
<?php /** * View helper for feed tabs. * * PHP version 7 * * Copyright (C) The National Library of Finland 2019. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category VuFind * @package View_Helpers * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ namespace Finna\View\Helper\Root; /** * View helper for feed tabs. * * @category VuFind * @package View_Helpers * @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link http://vufind.org Main Site */ class FeedTabs extends \Zend\View\Helper\AbstractHelper { /** * Returns HTML for the widget. * * @param array $feedIds Feed ids to display. * * @return string */ public function __invoke($feedIds) { $title = $feedIds['title'] ?? ''; $ids = $feedIds['ids']; return $this->getView()->render( 'Helpers/feedtabs.phtml', [ 'title' => $title, 'id' => md5(json_encode($ids)), 'feedIds' => $ids, 'active' => array_shift($ids) ] ); } }
arto70/NDL-VuFind2
module/Finna/src/Finna/View/Helper/Root/FeedTabs.php
PHP
gpl-2.0
1,933
<?php /** * @file * Default theme implementation to display the basic html structure of a single * Drupal page. * * Variables: * - $css: An array of CSS files for the current page. * - $language: (object) The language the site is being displayed in. * $language->language contains its textual representation. * $language->dir contains the language direction. It will either be 'ltr' or 'rtl'. * - $rdf_namespaces: All the RDF namespace prefixes used in the HTML document. * - $grddl_profile: A GRDDL profile allowing agents to extract the RDF data. * - $head_title: A modified version of the page title, for use in the TITLE tag. * - $head: Markup for the HEAD section (including meta tags, keyword tags, and * so on). * - $styles: Style tags necessary to import all CSS files for the page. * - $scripts: Script tags necessary to load the JavaScript files and settings * for the page. * - $page_top: Initial markup from any modules that have altered the * page. This variable should always be output first, before all other dynamic * content. * - $page: The rendered page content. * - $page_bottom: Final closing markup from any modules that have altered the * page. This variable should always be output last, after all other dynamic * content. * - $classes String of classes that can be used to style contextually through * CSS. * * @see template_preprocess() * @see template_preprocess_html() * @see template_process() */ $html_attributes = "lang=\"{$language->language}\" dir=\"{$language->dir}\" {$rdf->version}{$rdf->namespaces}"; ?> <?php print $doctype; ?> <!--[if IE 8 ]><html <?php print $html_attributes; ?> class="no-js ie8"><![endif]--> <!--[if IE 9 ]><html <?php print $html_attributes; ?> class="no-js ie9"><![endif]--> <!--[if (gt IE 9)|!(IE)]><!--><html <?php print $html_attributes; ?> class="no-js"><!--<![endif]--> <head<?php print $rdf->profile; ?>> <?php print $head; ?> <!--[if lte IE 7]> <div style=' text-align:center; clear: both; padding:0 0 0 15px; position: relative;'> <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode"><img src="http://storage.ie6countdown.com/assets/100/images/banners/warning_bar_0000_us.jpg" border="0" height="42" width="820" alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today." /></a></div> <![endif]--> <title><?php print $head_title; ?></title> <!--[if LT IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!--[if lte IE 8]> <style type="text/css"> .poll .bar, .poll .bar .foreground, #block-search-form .container-inline, #search-block-form .container-inline, .section-1 { behavior:url(<?php echo base_path().path_to_theme() ?>/js/PIE.php); zoom:1; position:relative;} </style> <![endif]--> <?php print $styles; ?> <?php print $scripts; ?> <script type="text/javascript"> WebFontConfig = { google: { families: [ 'Orbitron:900:latin' ] } }; (function() { var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })(); </script> </head> <body id="body" class="<?php print $classes; ?>" <?php print $attributes;?>> <?php print $page_top; ?> <?php print $page; ?> <?php print $page_bottom; ?> </body> </html>
jassonalgo/mythemejasson
sites/all/themes/theme698/templates/html.tpl.php
PHP
gpl-2.0
3,612
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ****************************************************************************/ #pragma once #include "../../utils/hostosinfo.h" #include <QApplication> #include <QDesktopWidget> #include <QPoint> #include <QRect> #include <QWidget> namespace Utils { namespace Internal { inline int screenNumber(const QPoint &pos, QWidget *w) { if (QApplication::desktop()->isVirtualDesktop()) return QApplication::desktop()->screenNumber(pos); else return QApplication::desktop()->screenNumber(w); } inline QRect screenGeometry(const QPoint &pos, QWidget *w) { if (HostOsInfo::isMacHost()) return QApplication::desktop()->availableGeometry(screenNumber(pos, w)); return QApplication::desktop()->screenGeometry(screenNumber(pos, w)); } } // namespace Internal } // namespace Utils
narunlifescience/Todi
src/widgets/tooltip/reuse.h
C
gpl-2.0
1,907
/* * net/dccp/proto.c * * An implementation of the DCCP protocol * Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/dccp.h> #include <linux/module.h> #include <linux/types.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/in.h> #include <linux/if_arp.h> #include <linux/init.h> #include <linux/random.h> #include <linux/slab.h> #include <net/checksum.h> #include <net/inet_sock.h> #include <net/sock.h> #include <net/xfrm.h> #include <asm/ioctls.h> #include <linux/spinlock.h> #include <linux/timer.h> #include <linux/delay.h> #include <linux/poll.h> #include "ccid.h" #include "dccp.h" #include "feat.h" DEFINE_SNMP_STAT(struct dccp_mib, dccp_statistics) __read_mostly; EXPORT_SYMBOL_GPL(dccp_statistics); struct percpu_counter dccp_orphan_count; EXPORT_SYMBOL_GPL(dccp_orphan_count); struct inet_hashinfo dccp_hashinfo; EXPORT_SYMBOL_GPL(dccp_hashinfo); /* the maximum queue length for tx in packets. 0 is no limit */ int sysctl_dccp_tx_qlen __read_mostly = 5; #ifdef CONFIG_IP_DCCP_DEBUG static const char *dccp_state_name(const int state) { static const char *const dccp_state_names[] = { [DCCP_OPEN] = "OPEN", [DCCP_REQUESTING] = "REQUESTING", [DCCP_PARTOPEN] = "PARTOPEN", [DCCP_LISTEN] = "LISTEN", [DCCP_RESPOND] = "RESPOND", [DCCP_CLOSING] = "CLOSING", [DCCP_ACTIVE_CLOSEREQ] = "CLOSEREQ", [DCCP_PASSIVE_CLOSE] = "PASSIVE_CLOSE", [DCCP_PASSIVE_CLOSEREQ] = "PASSIVE_CLOSEREQ", [DCCP_TIME_WAIT] = "TIME_WAIT", [DCCP_CLOSED] = "CLOSED", }; if (state >= DCCP_MAX_STATES) return "INVALID STATE!"; else return dccp_state_names[state]; } #endif void dccp_set_state(struct sock *sk, const int state) { const int oldstate = sk->sk_state; dccp_pr_debug("%s(%p) %s --> %s\n", dccp_role(sk), sk, dccp_state_name(oldstate), dccp_state_name(state)); WARN_ON(state == oldstate); switch (state) { case DCCP_OPEN: if (oldstate != DCCP_OPEN) DCCP_INC_STATS(DCCP_MIB_CURRESTAB); /* Client retransmits all Confirm options until entering OPEN */ if (oldstate == DCCP_PARTOPEN) dccp_feat_list_purge(&dccp_sk(sk)->dccps_featneg); break; case DCCP_CLOSED: if (oldstate == DCCP_OPEN || oldstate == DCCP_ACTIVE_CLOSEREQ || oldstate == DCCP_CLOSING) DCCP_INC_STATS(DCCP_MIB_ESTABRESETS); sk->sk_prot->unhash(sk); if (inet_csk(sk)->icsk_bind_hash != NULL && !(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) inet_put_port(sk); /* fall through */ default: if (oldstate == DCCP_OPEN) DCCP_DEC_STATS(DCCP_MIB_CURRESTAB); } /* Change state AFTER socket is unhashed to avoid closed * socket sitting in hash tables. */ sk->sk_state = state; } EXPORT_SYMBOL_GPL(dccp_set_state); static void dccp_finish_passive_close(struct sock *sk) { switch (sk->sk_state) { case DCCP_PASSIVE_CLOSE: /* Node (client or server) has received Close packet. */ dccp_send_reset(sk, DCCP_RESET_CODE_CLOSED); dccp_set_state(sk, DCCP_CLOSED); break; case DCCP_PASSIVE_CLOSEREQ: /* * Client received CloseReq. We set the `active' flag so that * dccp_send_close() retransmits the Close as per RFC 4340, 8.3. */ dccp_send_close(sk, 1); dccp_set_state(sk, DCCP_CLOSING); } } void dccp_done(struct sock *sk) { dccp_set_state(sk, DCCP_CLOSED); dccp_clear_xmit_timers(sk); sk->sk_shutdown = SHUTDOWN_MASK; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_state_change(sk); else inet_csk_destroy_sock(sk); } EXPORT_SYMBOL_GPL(dccp_done); const char *dccp_packet_name(const int type) { static const char *const dccp_packet_names[] = { [DCCP_PKT_REQUEST] = "REQUEST", [DCCP_PKT_RESPONSE] = "RESPONSE", [DCCP_PKT_DATA] = "DATA", [DCCP_PKT_ACK] = "ACK", [DCCP_PKT_DATAACK] = "DATAACK", [DCCP_PKT_CLOSEREQ] = "CLOSEREQ", [DCCP_PKT_CLOSE] = "CLOSE", [DCCP_PKT_RESET] = "RESET", [DCCP_PKT_SYNC] = "SYNC", [DCCP_PKT_SYNCACK] = "SYNCACK", }; if (type >= DCCP_NR_PKT_TYPES) return "INVALID"; else return dccp_packet_names[type]; } EXPORT_SYMBOL_GPL(dccp_packet_name); int dccp_init_sock(struct sock *sk, const __u8 ctl_sock_initialized) { struct dccp_sock *dp = dccp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_rto = DCCP_TIMEOUT_INIT; icsk->icsk_syn_retries = sysctl_dccp_request_retries; sk->sk_state = DCCP_CLOSED; sk->sk_write_space = dccp_write_space; icsk->icsk_sync_mss = dccp_sync_mss; dp->dccps_mss_cache = 536; dp->dccps_rate_last = jiffies; dp->dccps_role = DCCP_ROLE_UNDEFINED; dp->dccps_service = DCCP_SERVICE_CODE_IS_ABSENT; dp->dccps_tx_qlen = sysctl_dccp_tx_qlen; dccp_init_xmit_timers(sk); INIT_LIST_HEAD(&dp->dccps_featneg); /* control socket doesn't need feat nego */ if (likely(ctl_sock_initialized)) return dccp_feat_init(sk); return 0; } EXPORT_SYMBOL_GPL(dccp_init_sock); void dccp_destroy_sock(struct sock *sk) { struct dccp_sock *dp = dccp_sk(sk); /* * DCCP doesn't use sk_write_queue, just sk_send_head * for retransmissions */ if (sk->sk_send_head != NULL) { kfree_skb(sk->sk_send_head); sk->sk_send_head = NULL; } /* Clean up a referenced DCCP bind bucket. */ if (inet_csk(sk)->icsk_bind_hash != NULL) inet_put_port(sk); kfree(dp->dccps_service_list); dp->dccps_service_list = NULL; if (dp->dccps_hc_rx_ackvec != NULL) { dccp_ackvec_free(dp->dccps_hc_rx_ackvec); dp->dccps_hc_rx_ackvec = NULL; } ccid_hc_rx_delete(dp->dccps_hc_rx_ccid, sk); ccid_hc_tx_delete(dp->dccps_hc_tx_ccid, sk); dp->dccps_hc_rx_ccid = dp->dccps_hc_tx_ccid = NULL; /* clean up feature negotiation state */ dccp_feat_list_purge(&dp->dccps_featneg); } EXPORT_SYMBOL_GPL(dccp_destroy_sock); static inline int dccp_listen_start(struct sock *sk, int backlog) { struct dccp_sock *dp = dccp_sk(sk); dp->dccps_role = DCCP_ROLE_LISTEN; /* do not start to listen if feature negotiation setup fails */ if (dccp_feat_finalise_settings(dp)) return -EPROTO; return inet_csk_listen_start(sk, backlog); } static inline int dccp_need_reset(int state) { return state != DCCP_CLOSED && state != DCCP_LISTEN && state != DCCP_REQUESTING; } int dccp_disconnect(struct sock *sk, int flags) { struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet = inet_sk(sk); int err = 0; const int old_state = sk->sk_state; if (old_state != DCCP_CLOSED) dccp_set_state(sk, DCCP_CLOSED); /* * This corresponds to the ABORT function of RFC793, sec. 3.8 * TCP uses a RST segment, DCCP a Reset packet with Code 2, "Aborted". */ if (old_state == DCCP_LISTEN) { inet_csk_listen_stop(sk); } else if (dccp_need_reset(old_state)) { dccp_send_reset(sk, DCCP_RESET_CODE_ABORTED); sk->sk_err = ECONNRESET; } else if (old_state == DCCP_REQUESTING) sk->sk_err = ECONNRESET; dccp_clear_xmit_timers(sk); __skb_queue_purge(&sk->sk_receive_queue); __skb_queue_purge(&sk->sk_write_queue); if (sk->sk_send_head != NULL) { __kfree_skb(sk->sk_send_head); sk->sk_send_head = NULL; } inet->inet_dport = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); sk->sk_shutdown = 0; sock_reset_flag(sk, SOCK_DONE); icsk->icsk_backoff = 0; inet_csk_delack_init(sk); __sk_dst_reset(sk); WARN_ON(inet->inet_num && !icsk->icsk_bind_hash); sk->sk_error_report(sk); return err; } EXPORT_SYMBOL_GPL(dccp_disconnect); /* * Wait for a DCCP event. * * Note that we don't need to lock the socket, as the upper poll layers * take care of normal races (between the test and the event) and we don't * go look at any of the socket buffers directly. */ unsigned int dccp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask; struct sock *sk = sock->sk; sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == DCCP_LISTEN) return inet_csk_listen_poll(sk); /* Socket is not locked. We are protected from async events by poll logic and correct handling of state changes made by another threads is impossible in any case. */ mask = 0; if (sk->sk_err) mask = POLLERR; if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == DCCP_CLOSED) mask |= POLLHUP; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLIN | POLLRDNORM | POLLRDHUP; /* Connected? */ if ((1 << sk->sk_state) & ~(DCCPF_REQUESTING | DCCPF_RESPOND)) { if (atomic_read(&sk->sk_rmem_alloc) > 0) mask |= POLLIN | POLLRDNORM; if (!(sk->sk_shutdown & SEND_SHUTDOWN)) { if (sk_stream_is_writeable(sk)) { mask |= POLLOUT | POLLWRNORM; } else { /* send SIGIO later */ set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); /* Race breaker. If space is freed after * wspace test but before the flags are set, * IO signal will be lost. */ if (sk_stream_is_writeable(sk)) mask |= POLLOUT | POLLWRNORM; } } } return mask; } EXPORT_SYMBOL_GPL(dccp_poll); int dccp_ioctl(struct sock *sk, int cmd, unsigned long arg) { int rc = -ENOTCONN; lock_sock(sk); if (sk->sk_state == DCCP_LISTEN) goto out; switch (cmd) { case SIOCINQ: { struct sk_buff *skb; unsigned long amount = 0; skb = skb_peek(&sk->sk_receive_queue); if (skb != NULL) { /* * We will only return the amount of this packet since * that is all that will be read. */ amount = skb->len; } rc = put_user(amount, (int __user *)arg); } break; default: rc = -ENOIOCTLCMD; break; } out: release_sock(sk); return rc; } EXPORT_SYMBOL_GPL(dccp_ioctl); static int dccp_setsockopt_service(struct sock *sk, const __be32 service, char __user *optval, unsigned int optlen) { struct dccp_sock *dp = dccp_sk(sk); struct dccp_service_list *sl = NULL; if (service == DCCP_SERVICE_INVALID_VALUE || optlen > DCCP_SERVICE_LIST_MAX_LEN * sizeof(u32)) return -EINVAL; if (optlen > sizeof(service)) { sl = kmalloc(optlen, GFP_KERNEL); if (sl == NULL) return -ENOMEM; sl->dccpsl_nr = optlen / sizeof(u32) - 1; if (copy_from_user(sl->dccpsl_list, optval + sizeof(service), optlen - sizeof(service)) || dccp_list_has_service(sl, DCCP_SERVICE_INVALID_VALUE)) { kfree(sl); return -EFAULT; } } lock_sock(sk); dp->dccps_service = service; kfree(dp->dccps_service_list); dp->dccps_service_list = sl; release_sock(sk); return 0; } static int dccp_setsockopt_cscov(struct sock *sk, int cscov, bool rx) { u8 *list, len; int i, rc; if (cscov < 0 || cscov > 15) return -EINVAL; /* * Populate a list of permissible values, in the range cscov...15. This * is necessary since feature negotiation of single values only works if * both sides incidentally choose the same value. Since the list starts * lowest-value first, negotiation will pick the smallest shared value. */ if (cscov == 0) return 0; len = 16 - cscov; list = kmalloc(len, GFP_KERNEL); if (list == NULL) return -ENOBUFS; for (i = 0; i < len; i++) list[i] = cscov++; rc = dccp_feat_register_sp(sk, DCCPF_MIN_CSUM_COVER, rx, list, len); if (rc == 0) { if (rx) dccp_sk(sk)->dccps_pcrlen = cscov; else dccp_sk(sk)->dccps_pcslen = cscov; } kfree(list); return rc; } static int dccp_setsockopt_ccid(struct sock *sk, int type, char __user *optval, unsigned int optlen) { u8 *val; int rc = 0; if (optlen < 1 || optlen > DCCP_FEAT_MAX_SP_VALS) return -EINVAL; val = memdup_user(optval, optlen); if (IS_ERR(val)) return PTR_ERR(val); lock_sock(sk); if (type == DCCP_SOCKOPT_TX_CCID || type == DCCP_SOCKOPT_CCID) rc = dccp_feat_register_sp(sk, DCCPF_CCID, 1, val, optlen); if (!rc && (type == DCCP_SOCKOPT_RX_CCID || type == DCCP_SOCKOPT_CCID)) rc = dccp_feat_register_sp(sk, DCCPF_CCID, 0, val, optlen); release_sock(sk); kfree(val); return rc; } static int do_dccp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { struct dccp_sock *dp = dccp_sk(sk); int val, err = 0; switch (optname) { case DCCP_SOCKOPT_PACKET_SIZE: DCCP_WARN("sockopt(PACKET_SIZE) is deprecated: fix your app\n"); return 0; case DCCP_SOCKOPT_CHANGE_L: case DCCP_SOCKOPT_CHANGE_R: DCCP_WARN("sockopt(CHANGE_L/R) is deprecated: fix your app\n"); return 0; case DCCP_SOCKOPT_CCID: case DCCP_SOCKOPT_RX_CCID: case DCCP_SOCKOPT_TX_CCID: return dccp_setsockopt_ccid(sk, optname, optval, optlen); } if (optlen < (int)sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; if (optname == DCCP_SOCKOPT_SERVICE) return dccp_setsockopt_service(sk, val, optval, optlen); lock_sock(sk); switch (optname) { case DCCP_SOCKOPT_SERVER_TIMEWAIT: if (dp->dccps_role != DCCP_ROLE_SERVER) err = -EOPNOTSUPP; else dp->dccps_server_timewait = (val != 0); break; case DCCP_SOCKOPT_SEND_CSCOV: err = dccp_setsockopt_cscov(sk, val, false); break; case DCCP_SOCKOPT_RECV_CSCOV: err = dccp_setsockopt_cscov(sk, val, true); break; case DCCP_SOCKOPT_QPOLICY_ID: if (sk->sk_state != DCCP_CLOSED) err = -EISCONN; else if (val < 0 || val >= DCCPQ_POLICY_MAX) err = -EINVAL; else dp->dccps_qpolicy = val; break; case DCCP_SOCKOPT_QPOLICY_TXQLEN: if (val < 0) err = -EINVAL; else dp->dccps_tx_qlen = val; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } int dccp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level != SOL_DCCP) return inet_csk(sk)->icsk_af_ops->setsockopt(sk, level, optname, optval, optlen); return do_dccp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(dccp_setsockopt); #ifdef CONFIG_COMPAT int compat_dccp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level != SOL_DCCP) return inet_csk_compat_setsockopt(sk, level, optname, optval, optlen); return do_dccp_setsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(compat_dccp_setsockopt); #endif static int dccp_getsockopt_service(struct sock *sk, int len, __be32 __user *optval, int __user *optlen) { const struct dccp_sock *dp = dccp_sk(sk); const struct dccp_service_list *sl; int err = -ENOENT, slen = 0, total_len = sizeof(u32); lock_sock(sk); if ((sl = dp->dccps_service_list) != NULL) { slen = sl->dccpsl_nr * sizeof(u32); total_len += slen; } err = -EINVAL; if (total_len > len) goto out; err = 0; if (put_user(total_len, optlen) || put_user(dp->dccps_service, optval) || (sl != NULL && copy_to_user(optval + 1, sl->dccpsl_list, slen))) err = -EFAULT; out: release_sock(sk); return err; } static int do_dccp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct dccp_sock *dp; int val, len; if (get_user(len, optlen)) return -EFAULT; if (len < (int)sizeof(int)) return -EINVAL; dp = dccp_sk(sk); switch (optname) { case DCCP_SOCKOPT_PACKET_SIZE: DCCP_WARN("sockopt(PACKET_SIZE) is deprecated: fix your app\n"); return 0; case DCCP_SOCKOPT_SERVICE: return dccp_getsockopt_service(sk, len, (__be32 __user *)optval, optlen); case DCCP_SOCKOPT_GET_CUR_MPS: val = dp->dccps_mss_cache; break; case DCCP_SOCKOPT_AVAILABLE_CCIDS: return ccid_getsockopt_builtin_ccids(sk, len, optval, optlen); case DCCP_SOCKOPT_TX_CCID: val = ccid_get_current_tx_ccid(dp); if (val < 0) return -ENOPROTOOPT; break; case DCCP_SOCKOPT_RX_CCID: val = ccid_get_current_rx_ccid(dp); if (val < 0) return -ENOPROTOOPT; break; case DCCP_SOCKOPT_SERVER_TIMEWAIT: val = dp->dccps_server_timewait; break; case DCCP_SOCKOPT_SEND_CSCOV: val = dp->dccps_pcslen; break; case DCCP_SOCKOPT_RECV_CSCOV: val = dp->dccps_pcrlen; break; case DCCP_SOCKOPT_QPOLICY_ID: val = dp->dccps_qpolicy; break; case DCCP_SOCKOPT_QPOLICY_TXQLEN: val = dp->dccps_tx_qlen; break; case 128 ... 191: return ccid_hc_rx_getsockopt(dp->dccps_hc_rx_ccid, sk, optname, len, (u32 __user *)optval, optlen); case 192 ... 255: return ccid_hc_tx_getsockopt(dp->dccps_hc_tx_ccid, sk, optname, len, (u32 __user *)optval, optlen); default: return -ENOPROTOOPT; } len = sizeof(val); if (put_user(len, optlen) || copy_to_user(optval, &val, len)) return -EFAULT; return 0; } int dccp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level != SOL_DCCP) return inet_csk(sk)->icsk_af_ops->getsockopt(sk, level, optname, optval, optlen); return do_dccp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(dccp_getsockopt); #ifdef CONFIG_COMPAT int compat_dccp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level != SOL_DCCP) return inet_csk_compat_getsockopt(sk, level, optname, optval, optlen); return do_dccp_getsockopt(sk, level, optname, optval, optlen); } EXPORT_SYMBOL_GPL(compat_dccp_getsockopt); #endif static int dccp_msghdr_parse(struct msghdr *msg, struct sk_buff *skb) { struct cmsghdr *cmsg; /* * Assign an (opaque) qpolicy priority value to skb->priority. * * We are overloading this skb field for use with the qpolicy subystem. * The skb->priority is normally used for the SO_PRIORITY option, which * is initialised from sk_priority. Since the assignment of sk_priority * to skb->priority happens later (on layer 3), we overload this field * for use with queueing priorities as long as the skb is on layer 4. * The default priority value (if nothing is set) is 0. */ skb->priority = 0; for_each_cmsghdr(cmsg, msg) { if (!CMSG_OK(msg, cmsg)) return -EINVAL; if (cmsg->cmsg_level != SOL_DCCP) continue; if (cmsg->cmsg_type <= DCCP_SCM_QPOLICY_MAX && !dccp_qpolicy_param_ok(skb->sk, cmsg->cmsg_type)) return -EINVAL; switch (cmsg->cmsg_type) { case DCCP_SCM_PRIORITY: if (cmsg->cmsg_len != CMSG_LEN(sizeof(__u32))) return -EINVAL; skb->priority = *(__u32 *)CMSG_DATA(cmsg); break; default: return -EINVAL; } } return 0; } int dccp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { const struct dccp_sock *dp = dccp_sk(sk); const int flags = msg->msg_flags; const int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; int rc, size; long timeo; if (len > dp->dccps_mss_cache) return -EMSGSIZE; lock_sock(sk); if (dccp_qpolicy_full(sk)) { rc = -EAGAIN; goto out_release; } timeo = sock_sndtimeo(sk, noblock); /* * We have to use sk_stream_wait_connect here to set sk_write_pending, * so that the trick in dccp_rcv_request_sent_state_process. */ /* Wait for a connection to finish. */ if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN)) if ((rc = sk_stream_wait_connect(sk, &timeo)) != 0) goto out_release; size = sk->sk_prot->max_header + len; release_sock(sk); skb = sock_alloc_send_skb(sk, size, noblock, &rc); lock_sock(sk); if (skb == NULL) goto out_release; skb_reserve(skb, sk->sk_prot->max_header); rc = memcpy_from_msg(skb_put(skb, len), msg, len); if (rc != 0) goto out_discard; rc = dccp_msghdr_parse(msg, skb); if (rc != 0) goto out_discard; dccp_qpolicy_push(sk, skb); /* * The xmit_timer is set if the TX CCID is rate-based and will expire * when congestion control permits to release further packets into the * network. Window-based CCIDs do not use this timer. */ if (!timer_pending(&dp->dccps_xmit_timer)) dccp_write_xmit(sk); out_release: release_sock(sk); return rc ? : len; out_discard: kfree_skb(skb); goto out_release; } EXPORT_SYMBOL_GPL(dccp_sendmsg); int dccp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int nonblock, int flags, int *addr_len) { const struct dccp_hdr *dh; long timeo; lock_sock(sk); if (sk->sk_state == DCCP_LISTEN) { len = -ENOTCONN; goto out; } timeo = sock_rcvtimeo(sk, nonblock); do { struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); if (skb == NULL) goto verify_sock_status; dh = dccp_hdr(skb); switch (dh->dccph_type) { case DCCP_PKT_DATA: case DCCP_PKT_DATAACK: goto found_ok_skb; case DCCP_PKT_CLOSE: case DCCP_PKT_CLOSEREQ: if (!(flags & MSG_PEEK)) dccp_finish_passive_close(sk); /* fall through */ case DCCP_PKT_RESET: dccp_pr_debug("found fin (%s) ok!\n", dccp_packet_name(dh->dccph_type)); len = 0; goto found_fin_ok; default: dccp_pr_debug("packet_type=%s\n", dccp_packet_name(dh->dccph_type)); sk_eat_skb(sk, skb); } verify_sock_status: if (sock_flag(sk, SOCK_DONE)) { len = 0; break; } if (sk->sk_err) { len = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) { len = 0; break; } if (sk->sk_state == DCCP_CLOSED) { if (!sock_flag(sk, SOCK_DONE)) { /* This occurs when user tries to read * from never connected socket. */ len = -ENOTCONN; break; } len = 0; break; } if (!timeo) { len = -EAGAIN; break; } if (signal_pending(current)) { len = sock_intr_errno(timeo); break; } sk_wait_data(sk, &timeo, NULL); continue; found_ok_skb: if (len > skb->len) len = skb->len; else if (len < skb->len) msg->msg_flags |= MSG_TRUNC; if (skb_copy_datagram_msg(skb, 0, msg, len)) { /* Exception. Bailout! */ len = -EFAULT; break; } if (flags & MSG_TRUNC) len = skb->len; found_fin_ok: if (!(flags & MSG_PEEK)) sk_eat_skb(sk, skb); break; } while (1); out: release_sock(sk); return len; } EXPORT_SYMBOL_GPL(dccp_recvmsg); int inet_dccp_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; unsigned char old_state; int err; lock_sock(sk); err = -EINVAL; if (sock->state != SS_UNCONNECTED || sock->type != SOCK_DCCP) goto out; old_state = sk->sk_state; if (!((1 << old_state) & (DCCPF_CLOSED | DCCPF_LISTEN))) goto out; /* Really, if the socket is already in listen state * we can only allow the backlog to be adjusted. */ if (old_state != DCCP_LISTEN) { /* * FIXME: here it probably should be sk->sk_prot->listen_start * see tcp_listen_start */ err = dccp_listen_start(sk, backlog); if (err) goto out; } sk->sk_max_ack_backlog = backlog; err = 0; out: release_sock(sk); return err; } EXPORT_SYMBOL_GPL(inet_dccp_listen); static void dccp_terminate_connection(struct sock *sk) { u8 next_state = DCCP_CLOSED; switch (sk->sk_state) { case DCCP_PASSIVE_CLOSE: case DCCP_PASSIVE_CLOSEREQ: dccp_finish_passive_close(sk); break; case DCCP_PARTOPEN: dccp_pr_debug("Stop PARTOPEN timer (%p)\n", sk); inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); /* fall through */ case DCCP_OPEN: dccp_send_close(sk, 1); if (dccp_sk(sk)->dccps_role == DCCP_ROLE_SERVER && !dccp_sk(sk)->dccps_server_timewait) next_state = DCCP_ACTIVE_CLOSEREQ; else next_state = DCCP_CLOSING; /* fall through */ default: dccp_set_state(sk, next_state); } } void dccp_close(struct sock *sk, long timeout) { struct dccp_sock *dp = dccp_sk(sk); struct sk_buff *skb; u32 data_was_unread = 0; int state; lock_sock(sk); sk->sk_shutdown = SHUTDOWN_MASK; if (sk->sk_state == DCCP_LISTEN) { dccp_set_state(sk, DCCP_CLOSED); /* Special case. */ inet_csk_listen_stop(sk); goto adjudge_to_death; } sk_stop_timer(sk, &dp->dccps_xmit_timer); /* * We need to flush the recv. buffs. We do this only on the * descriptor close, not protocol-sourced closes, because the *reader process may not have drained the data yet! */ while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) { data_was_unread += skb->len; __kfree_skb(skb); } if (data_was_unread) { /* Unread data was tossed, send an appropriate Reset Code */ DCCP_WARN("ABORT with %u bytes unread\n", data_was_unread); dccp_send_reset(sk, DCCP_RESET_CODE_ABORTED); dccp_set_state(sk, DCCP_CLOSED); } else if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) { /* Check zero linger _after_ checking for unread data. */ sk->sk_prot->disconnect(sk, 0); } else if (sk->sk_state != DCCP_CLOSED) { /* * Normal connection termination. May need to wait if there are * still packets in the TX queue that are delayed by the CCID. */ dccp_flush_write_queue(sk, &timeout); dccp_terminate_connection(sk); } /* * Flush write queue. This may be necessary in several cases: * - we have been closed by the peer but still have application data; * - abortive termination (unread data or zero linger time), * - normal termination but queue could not be flushed within time limit */ __skb_queue_purge(&sk->sk_write_queue); sk_stream_wait_close(sk, timeout); adjudge_to_death: state = sk->sk_state; sock_hold(sk); sock_orphan(sk); /* * It is the last release_sock in its life. It will remove backlog. */ release_sock(sk); /* * Now socket is owned by kernel and we acquire BH lock * to finish close. No need to check for user refs. */ local_bh_disable(); bh_lock_sock(sk); WARN_ON(sock_owned_by_user(sk)); percpu_counter_inc(sk->sk_prot->orphan_count); /* Have we already been destroyed by a softirq or backlog? */ if (state != DCCP_CLOSED && sk->sk_state == DCCP_CLOSED) goto out; if (sk->sk_state == DCCP_CLOSED) inet_csk_destroy_sock(sk); /* Otherwise, socket is reprieved until protocol close. */ out: bh_unlock_sock(sk); local_bh_enable(); sock_put(sk); } EXPORT_SYMBOL_GPL(dccp_close); void dccp_shutdown(struct sock *sk, int how) { dccp_pr_debug("called shutdown(%x)\n", how); } EXPORT_SYMBOL_GPL(dccp_shutdown); static inline int __init dccp_mib_init(void) { dccp_statistics = alloc_percpu(struct dccp_mib); if (!dccp_statistics) return -ENOMEM; return 0; } static inline void dccp_mib_exit(void) { free_percpu(dccp_statistics); } static int thash_entries; module_param(thash_entries, int, 0444); MODULE_PARM_DESC(thash_entries, "Number of ehash buckets"); #ifdef CONFIG_IP_DCCP_DEBUG bool dccp_debug; module_param(dccp_debug, bool, 0644); MODULE_PARM_DESC(dccp_debug, "Enable debug messages"); EXPORT_SYMBOL_GPL(dccp_debug); #endif static int __init dccp_init(void) { unsigned long goal; int ehash_order, bhash_order, i; int rc; BUILD_BUG_ON(sizeof(struct dccp_skb_cb) > FIELD_SIZEOF(struct sk_buff, cb)); rc = percpu_counter_init(&dccp_orphan_count, 0, GFP_KERNEL); if (rc) goto out_fail; rc = -ENOBUFS; inet_hashinfo_init(&dccp_hashinfo); dccp_hashinfo.bind_bucket_cachep = kmem_cache_create("dccp_bind_bucket", sizeof(struct inet_bind_bucket), 0, SLAB_HWCACHE_ALIGN, NULL); if (!dccp_hashinfo.bind_bucket_cachep) goto out_free_percpu; /* * Size and allocate the main established and bind bucket * hash tables. * * The methodology is similar to that of the buffer cache. */ if (totalram_pages >= (128 * 1024)) goal = totalram_pages >> (21 - PAGE_SHIFT); else goal = totalram_pages >> (23 - PAGE_SHIFT); if (thash_entries) goal = (thash_entries * sizeof(struct inet_ehash_bucket)) >> PAGE_SHIFT; for (ehash_order = 0; (1UL << ehash_order) < goal; ehash_order++) ; do { unsigned long hash_size = (1UL << ehash_order) * PAGE_SIZE / sizeof(struct inet_ehash_bucket); while (hash_size & (hash_size - 1)) hash_size--; dccp_hashinfo.ehash_mask = hash_size - 1; dccp_hashinfo.ehash = (struct inet_ehash_bucket *) __get_free_pages(GFP_ATOMIC|__GFP_NOWARN, ehash_order); } while (!dccp_hashinfo.ehash && --ehash_order > 0); if (!dccp_hashinfo.ehash) { DCCP_CRIT("Failed to allocate DCCP established hash table"); goto out_free_bind_bucket_cachep; } for (i = 0; i <= dccp_hashinfo.ehash_mask; i++) INIT_HLIST_NULLS_HEAD(&dccp_hashinfo.ehash[i].chain, i); if (inet_ehash_locks_alloc(&dccp_hashinfo)) goto out_free_dccp_ehash; bhash_order = ehash_order; do { dccp_hashinfo.bhash_size = (1UL << bhash_order) * PAGE_SIZE / sizeof(struct inet_bind_hashbucket); if ((dccp_hashinfo.bhash_size > (64 * 1024)) && bhash_order > 0) continue; dccp_hashinfo.bhash = (struct inet_bind_hashbucket *) __get_free_pages(GFP_ATOMIC|__GFP_NOWARN, bhash_order); } while (!dccp_hashinfo.bhash && --bhash_order >= 0); if (!dccp_hashinfo.bhash) { DCCP_CRIT("Failed to allocate DCCP bind hash table"); goto out_free_dccp_locks; } for (i = 0; i < dccp_hashinfo.bhash_size; i++) { spin_lock_init(&dccp_hashinfo.bhash[i].lock); INIT_HLIST_HEAD(&dccp_hashinfo.bhash[i].chain); } rc = dccp_mib_init(); if (rc) goto out_free_dccp_bhash; rc = dccp_ackvec_init(); if (rc) goto out_free_dccp_mib; rc = dccp_sysctl_init(); if (rc) goto out_ackvec_exit; rc = ccid_initialize_builtins(); if (rc) goto out_sysctl_exit; dccp_timestamping_init(); return 0; out_sysctl_exit: dccp_sysctl_exit(); out_ackvec_exit: dccp_ackvec_exit(); out_free_dccp_mib: dccp_mib_exit(); out_free_dccp_bhash: free_pages((unsigned long)dccp_hashinfo.bhash, bhash_order); out_free_dccp_locks: inet_ehash_locks_free(&dccp_hashinfo); out_free_dccp_ehash: free_pages((unsigned long)dccp_hashinfo.ehash, ehash_order); out_free_bind_bucket_cachep: kmem_cache_destroy(dccp_hashinfo.bind_bucket_cachep); out_free_percpu: percpu_counter_destroy(&dccp_orphan_count); out_fail: dccp_hashinfo.bhash = NULL; dccp_hashinfo.ehash = NULL; dccp_hashinfo.bind_bucket_cachep = NULL; return rc; } static void __exit dccp_fini(void) { ccid_cleanup_builtins(); dccp_mib_exit(); free_pages((unsigned long)dccp_hashinfo.bhash, get_order(dccp_hashinfo.bhash_size * sizeof(struct inet_bind_hashbucket))); free_pages((unsigned long)dccp_hashinfo.ehash, get_order((dccp_hashinfo.ehash_mask + 1) * sizeof(struct inet_ehash_bucket))); inet_ehash_locks_free(&dccp_hashinfo); kmem_cache_destroy(dccp_hashinfo.bind_bucket_cachep); dccp_ackvec_exit(); dccp_sysctl_exit(); percpu_counter_destroy(&dccp_orphan_count); } module_init(dccp_init); module_exit(dccp_fini); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Arnaldo Carvalho de Melo <acme@conectiva.com.br>"); MODULE_DESCRIPTION("DCCP - Datagram Congestion Controlled Protocol");
volk3/CS736
net/dccp/proto.c
C
gpl-2.0
30,486
package blender.makesdna.sdna; import java.nio.ByteBuffer; import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; public class bObject extends ID implements DNA, Cloneable { // #114 public bObject[] myarray; public ID id = (ID)this; public AnimData adt; // ptr 96 public Object sculpt; // ptr (SculptSession) 0 public short type; // 2 public short partype; // 2 public int par1; // 4 public int par2; // 4 public int par3; // 4 public byte[] parsubstr = new byte[32]; // 1 public bObject parent; // ptr 1296 public bObject track; // ptr 1296 public bObject proxy; // ptr 1296 public bObject proxy_group; // ptr 1296 public bObject proxy_from; // ptr 1296 public Ipo ipo; // ptr 112 public Object path; // ptr (Path) 0 public BoundBox bb; // ptr 104 public bAction action; // ptr 152 public bAction poselib; // ptr 152 public bPose pose; // ptr 184 public Object data; // ptr 0 public bGPdata gpd; // ptr 104 public bAnimVizSettings avs = new bAnimVizSettings(); // 48 public bMotionPath mpath; // ptr 24 public ListBase constraintChannels = new ListBase(); // 16 public ListBase effect = new ListBase(); // 16 public ListBase disp = new ListBase(); // 16 public ListBase defbase = new ListBase(); // 16 public ListBase modifiers = new ListBase(); // 16 public int mode; // 4 public int restore_mode; // 4 public Material[] mat; // ptr 800 public Object matbits; // ptr 1 public int totcol; // 4 public int actcol; // 4 public float[] loc = new float[3]; // 4 public float[] dloc = new float[3]; // 4 public float[] orig = new float[3]; // 4 public float[] size = new float[3]; // 4 public float[] dsize = new float[3]; // 4 public float[] rot = new float[3]; // 4 public float[] drot = new float[3]; // 4 public float[] quat = new float[4]; // 4 public float[] dquat = new float[4]; // 4 public float[] rotAxis = new float[3]; // 4 public float[] drotAxis = new float[3]; // 4 public float rotAngle; // 4 public float drotAngle; // 4 public float[][] obmat = new float[4][4]; // 4 public float[][] parentinv = new float[4][4]; // 4 public float[][] constinv = new float[4][4]; // 4 public float[][] imat = new float[4][4]; // 4 public float[][] imat_ren = new float[4][4]; // 4 public int lay; // 4 public short flag; // 2 public short colbits; // 2 public short transflag; // 2 public short protectflag; // 2 public short trackflag; // 2 public short upflag; // 2 public short nlaflag; // 2 public short ipoflag; // 2 public short ipowin; // 2 public short scaflag; // 2 public short scavisflag; // 2 public short boundtype; // 2 public int dupon; // 4 public int dupoff; // 4 public int dupsta; // 4 public int dupend; // 4 public float sf; // 4 public float ctime; // 4 public float mass; // 4 public float damping; // 4 public float inertia; // 4 public float formfactor; // 4 public float rdamping; // 4 public float sizefac; // 4 public float margin; // 4 public float max_vel; // 4 public float min_vel; // 4 public float m_contactProcessingThreshold; // 4 public short rotmode; // 2 public byte dt; // 1 public byte dtx; // 1 public byte empty_drawtype; // 1 public byte[] pad1 = new byte[3]; // 1 public float empty_drawsize; // 4 public float dupfacesca; // 4 public ListBase prop = new ListBase(); // 16 public ListBase sensors = new ListBase(); // 16 public ListBase controllers = new ListBase(); // 16 public ListBase actuators = new ListBase(); // 16 public float[] bbsize = new float[3]; // 4 public short index; // 2 public short actdef; // 2 public float[] col = new float[4]; // 4 public int gameflag; // 4 public int gameflag2; // 4 public BulletSoftBody bsoft; // ptr 120 public short softflag; // 2 public short recalc; // 2 public float[] anisotropicFriction = new float[3]; // 4 public ListBase constraints = new ListBase(); // 16 public ListBase nlastrips = new ListBase(); // 16 public ListBase hooks = new ListBase(); // 16 public ListBase particlesystem = new ListBase(); // 16 public PartDeflect pd; // ptr 152 public SoftBody soft; // ptr 376 public Group dup_group; // ptr 104 public short fluidsimFlag; // 2 public short restrictflag; // 2 public short shapenr; // 2 public short shapeflag; // 2 public float smoothresh; // 4 public short recalco; // 2 public short body_type; // 2 public FluidsimSettings fluidsimSettings; // ptr 456 public Object derivedDeform; // ptr (DerivedMesh) 0 public Object derivedFinal; // ptr (DerivedMesh) 0 public int lastDataMask; // 4 public int state; // 4 public int init_state; // 4 public int pad2; // 4 public ListBase gpulamp = new ListBase(); // 16 public ListBase pc_ids = new ListBase(); // 16 public ListBase duplilist; // ptr 16 public void read(ByteBuffer buffer) { super.read(buffer); adt = DNATools.link(DNATools.ptr(buffer), AnimData.class); // get ptr sculpt = DNATools.ptr(buffer); // get ptr type = buffer.getShort(); partype = buffer.getShort(); par1 = buffer.getInt(); par2 = buffer.getInt(); par3 = buffer.getInt(); buffer.get(parsubstr); parent = DNATools.link(DNATools.ptr(buffer), bObject.class); // get ptr track = DNATools.link(DNATools.ptr(buffer), bObject.class); // get ptr proxy = DNATools.link(DNATools.ptr(buffer), bObject.class); // get ptr proxy_group = DNATools.link(DNATools.ptr(buffer), bObject.class); // get ptr proxy_from = DNATools.link(DNATools.ptr(buffer), bObject.class); // get ptr ipo = DNATools.link(DNATools.ptr(buffer), Ipo.class); // get ptr path = DNATools.ptr(buffer); // get ptr bb = DNATools.link(DNATools.ptr(buffer), BoundBox.class); // get ptr action = DNATools.link(DNATools.ptr(buffer), bAction.class); // get ptr poselib = DNATools.link(DNATools.ptr(buffer), bAction.class); // get ptr pose = DNATools.link(DNATools.ptr(buffer), bPose.class); // get ptr data = DNATools.ptr(buffer); // get ptr gpd = DNATools.link(DNATools.ptr(buffer), bGPdata.class); // get ptr avs.read(buffer); mpath = DNATools.link(DNATools.ptr(buffer), bMotionPath.class); // get ptr constraintChannels.read(buffer); effect.read(buffer); disp.read(buffer); defbase.read(buffer); modifiers.read(buffer); mode = buffer.getInt(); restore_mode = buffer.getInt(); mat = DNATools.link(DNATools.ptr(buffer), Material[].class); // get ptr matbits = DNATools.ptr(buffer); // get ptr totcol = buffer.getInt(); actcol = buffer.getInt(); for(int i=0;i<loc.length;i++) loc[i]=buffer.getFloat(); for(int i=0;i<dloc.length;i++) dloc[i]=buffer.getFloat(); for(int i=0;i<orig.length;i++) orig[i]=buffer.getFloat(); for(int i=0;i<size.length;i++) size[i]=buffer.getFloat(); for(int i=0;i<dsize.length;i++) dsize[i]=buffer.getFloat(); for(int i=0;i<rot.length;i++) rot[i]=buffer.getFloat(); for(int i=0;i<drot.length;i++) drot[i]=buffer.getFloat(); for(int i=0;i<quat.length;i++) quat[i]=buffer.getFloat(); for(int i=0;i<dquat.length;i++) dquat[i]=buffer.getFloat(); for(int i=0;i<rotAxis.length;i++) rotAxis[i]=buffer.getFloat(); for(int i=0;i<drotAxis.length;i++) drotAxis[i]=buffer.getFloat(); rotAngle = buffer.getFloat(); drotAngle = buffer.getFloat(); for(int i=0;i<obmat.length;i++) for(int j=0;j<obmat[i].length;j++) obmat[i][j]=buffer.getFloat(); for(int i=0;i<parentinv.length;i++) for(int j=0;j<parentinv[i].length;j++) parentinv[i][j]=buffer.getFloat(); for(int i=0;i<constinv.length;i++) for(int j=0;j<constinv[i].length;j++) constinv[i][j]=buffer.getFloat(); for(int i=0;i<imat.length;i++) for(int j=0;j<imat[i].length;j++) imat[i][j]=buffer.getFloat(); for(int i=0;i<imat_ren.length;i++) for(int j=0;j<imat_ren[i].length;j++) imat_ren[i][j]=buffer.getFloat(); lay = buffer.getInt(); flag = buffer.getShort(); colbits = buffer.getShort(); transflag = buffer.getShort(); protectflag = buffer.getShort(); trackflag = buffer.getShort(); upflag = buffer.getShort(); nlaflag = buffer.getShort(); ipoflag = buffer.getShort(); ipowin = buffer.getShort(); scaflag = buffer.getShort(); scavisflag = buffer.getShort(); boundtype = buffer.getShort(); dupon = buffer.getInt(); dupoff = buffer.getInt(); dupsta = buffer.getInt(); dupend = buffer.getInt(); sf = buffer.getFloat(); ctime = buffer.getFloat(); mass = buffer.getFloat(); damping = buffer.getFloat(); inertia = buffer.getFloat(); formfactor = buffer.getFloat(); rdamping = buffer.getFloat(); sizefac = buffer.getFloat(); margin = buffer.getFloat(); max_vel = buffer.getFloat(); min_vel = buffer.getFloat(); m_contactProcessingThreshold = buffer.getFloat(); rotmode = buffer.getShort(); dt = buffer.get(); dtx = buffer.get(); empty_drawtype = buffer.get(); buffer.get(pad1); empty_drawsize = buffer.getFloat(); dupfacesca = buffer.getFloat(); prop.read(buffer); sensors.read(buffer); controllers.read(buffer); actuators.read(buffer); for(int i=0;i<bbsize.length;i++) bbsize[i]=buffer.getFloat(); index = buffer.getShort(); actdef = buffer.getShort(); for(int i=0;i<col.length;i++) col[i]=buffer.getFloat(); gameflag = buffer.getInt(); gameflag2 = buffer.getInt(); bsoft = DNATools.link(DNATools.ptr(buffer), BulletSoftBody.class); // get ptr softflag = buffer.getShort(); recalc = buffer.getShort(); for(int i=0;i<anisotropicFriction.length;i++) anisotropicFriction[i]=buffer.getFloat(); constraints.read(buffer); nlastrips.read(buffer); hooks.read(buffer); particlesystem.read(buffer); pd = DNATools.link(DNATools.ptr(buffer), PartDeflect.class); // get ptr soft = DNATools.link(DNATools.ptr(buffer), SoftBody.class); // get ptr dup_group = DNATools.link(DNATools.ptr(buffer), Group.class); // get ptr fluidsimFlag = buffer.getShort(); restrictflag = buffer.getShort(); shapenr = buffer.getShort(); shapeflag = buffer.getShort(); smoothresh = buffer.getFloat(); recalco = buffer.getShort(); body_type = buffer.getShort(); fluidsimSettings = DNATools.link(DNATools.ptr(buffer), FluidsimSettings.class); // get ptr derivedDeform = DNATools.ptr(buffer); // get ptr derivedFinal = DNATools.ptr(buffer); // get ptr lastDataMask = buffer.getInt(); state = buffer.getInt(); init_state = buffer.getInt(); pad2 = buffer.getInt(); gpulamp.read(buffer); pc_ids.read(buffer); duplilist = DNATools.link(DNATools.ptr(buffer), ListBase.class); // get ptr } public void write(DataOutput buffer) throws IOException { super.write(buffer); buffer.writeInt(adt!=null?adt.hashCode():0); buffer.writeInt(sculpt!=null?sculpt.hashCode():0); buffer.writeShort(type); buffer.writeShort(partype); buffer.writeInt(par1); buffer.writeInt(par2); buffer.writeInt(par3); buffer.write(parsubstr); buffer.writeInt(parent!=null?parent.hashCode():0); buffer.writeInt(track!=null?track.hashCode():0); buffer.writeInt(proxy!=null?proxy.hashCode():0); buffer.writeInt(proxy_group!=null?proxy_group.hashCode():0); buffer.writeInt(proxy_from!=null?proxy_from.hashCode():0); buffer.writeInt(ipo!=null?ipo.hashCode():0); buffer.writeInt(path!=null?path.hashCode():0); buffer.writeInt(bb!=null?bb.hashCode():0); buffer.writeInt(action!=null?action.hashCode():0); buffer.writeInt(poselib!=null?poselib.hashCode():0); buffer.writeInt(pose!=null?pose.hashCode():0); buffer.writeInt(data!=null?data.hashCode():0); buffer.writeInt(gpd!=null?gpd.hashCode():0); avs.write(buffer); buffer.writeInt(mpath!=null?mpath.hashCode():0); constraintChannels.write(buffer); effect.write(buffer); disp.write(buffer); defbase.write(buffer); modifiers.write(buffer); buffer.writeInt(mode); buffer.writeInt(restore_mode); buffer.writeInt(mat!=null?mat.hashCode():0); buffer.writeInt(matbits!=null?matbits.hashCode():0); buffer.writeInt(totcol); buffer.writeInt(actcol); for(int i=0;i<loc.length;i++) buffer.writeFloat(loc[i]); for(int i=0;i<dloc.length;i++) buffer.writeFloat(dloc[i]); for(int i=0;i<orig.length;i++) buffer.writeFloat(orig[i]); for(int i=0;i<size.length;i++) buffer.writeFloat(size[i]); for(int i=0;i<dsize.length;i++) buffer.writeFloat(dsize[i]); for(int i=0;i<rot.length;i++) buffer.writeFloat(rot[i]); for(int i=0;i<drot.length;i++) buffer.writeFloat(drot[i]); for(int i=0;i<quat.length;i++) buffer.writeFloat(quat[i]); for(int i=0;i<dquat.length;i++) buffer.writeFloat(dquat[i]); for(int i=0;i<rotAxis.length;i++) buffer.writeFloat(rotAxis[i]); for(int i=0;i<drotAxis.length;i++) buffer.writeFloat(drotAxis[i]); buffer.writeFloat(rotAngle); buffer.writeFloat(drotAngle); for(int i=0; i<obmat.length; i++) for(int j=0;j<obmat[i].length;j++) buffer.writeFloat(obmat[i][j]); for(int i=0; i<parentinv.length; i++) for(int j=0;j<parentinv[i].length;j++) buffer.writeFloat(parentinv[i][j]); for(int i=0; i<constinv.length; i++) for(int j=0;j<constinv[i].length;j++) buffer.writeFloat(constinv[i][j]); for(int i=0; i<imat.length; i++) for(int j=0;j<imat[i].length;j++) buffer.writeFloat(imat[i][j]); for(int i=0; i<imat_ren.length; i++) for(int j=0;j<imat_ren[i].length;j++) buffer.writeFloat(imat_ren[i][j]); buffer.writeInt(lay); buffer.writeShort(flag); buffer.writeShort(colbits); buffer.writeShort(transflag); buffer.writeShort(protectflag); buffer.writeShort(trackflag); buffer.writeShort(upflag); buffer.writeShort(nlaflag); buffer.writeShort(ipoflag); buffer.writeShort(ipowin); buffer.writeShort(scaflag); buffer.writeShort(scavisflag); buffer.writeShort(boundtype); buffer.writeInt(dupon); buffer.writeInt(dupoff); buffer.writeInt(dupsta); buffer.writeInt(dupend); buffer.writeFloat(sf); buffer.writeFloat(ctime); buffer.writeFloat(mass); buffer.writeFloat(damping); buffer.writeFloat(inertia); buffer.writeFloat(formfactor); buffer.writeFloat(rdamping); buffer.writeFloat(sizefac); buffer.writeFloat(margin); buffer.writeFloat(max_vel); buffer.writeFloat(min_vel); buffer.writeFloat(m_contactProcessingThreshold); buffer.writeShort(rotmode); buffer.writeByte(dt); buffer.writeByte(dtx); buffer.writeByte(empty_drawtype); buffer.write(pad1); buffer.writeFloat(empty_drawsize); buffer.writeFloat(dupfacesca); prop.write(buffer); sensors.write(buffer); controllers.write(buffer); actuators.write(buffer); for(int i=0;i<bbsize.length;i++) buffer.writeFloat(bbsize[i]); buffer.writeShort(index); buffer.writeShort(actdef); for(int i=0;i<col.length;i++) buffer.writeFloat(col[i]); buffer.writeInt(gameflag); buffer.writeInt(gameflag2); buffer.writeInt(bsoft!=null?bsoft.hashCode():0); buffer.writeShort(softflag); buffer.writeShort(recalc); for(int i=0;i<anisotropicFriction.length;i++) buffer.writeFloat(anisotropicFriction[i]); constraints.write(buffer); nlastrips.write(buffer); hooks.write(buffer); particlesystem.write(buffer); buffer.writeInt(pd!=null?pd.hashCode():0); buffer.writeInt(soft!=null?soft.hashCode():0); buffer.writeInt(dup_group!=null?dup_group.hashCode():0); buffer.writeShort(fluidsimFlag); buffer.writeShort(restrictflag); buffer.writeShort(shapenr); buffer.writeShort(shapeflag); buffer.writeFloat(smoothresh); buffer.writeShort(recalco); buffer.writeShort(body_type); buffer.writeInt(fluidsimSettings!=null?fluidsimSettings.hashCode():0); buffer.writeInt(derivedDeform!=null?derivedDeform.hashCode():0); buffer.writeInt(derivedFinal!=null?derivedFinal.hashCode():0); buffer.writeInt(lastDataMask); buffer.writeInt(state); buffer.writeInt(init_state); buffer.writeInt(pad2); gpulamp.write(buffer); pc_ids.write(buffer); buffer.writeInt(duplilist!=null?duplilist.hashCode():0); } public Object setmyarray(Object array) { myarray = (bObject[])array; return this; } public Object getmyarray() { return myarray; } public String toString() { StringBuilder sb = new StringBuilder("bObject:\n"); sb.append(super.toString()); sb.append(" adt: ").append(adt).append("\n"); sb.append(" sculpt: ").append(sculpt).append("\n"); sb.append(" type: ").append(type).append("\n"); sb.append(" partype: ").append(partype).append("\n"); sb.append(" par1: ").append(par1).append("\n"); sb.append(" par2: ").append(par2).append("\n"); sb.append(" par3: ").append(par3).append("\n"); sb.append(" parsubstr: ").append(new String(parsubstr)).append("\n"); sb.append(" parent: ").append(parent).append("\n"); sb.append(" track: ").append(track).append("\n"); sb.append(" proxy: ").append(proxy).append("\n"); sb.append(" proxy_group: ").append(proxy_group).append("\n"); sb.append(" proxy_from: ").append(proxy_from).append("\n"); sb.append(" ipo: ").append(ipo).append("\n"); sb.append(" path: ").append(path).append("\n"); sb.append(" bb: ").append(bb).append("\n"); sb.append(" action: ").append(action).append("\n"); sb.append(" poselib: ").append(poselib).append("\n"); sb.append(" pose: ").append(pose).append("\n"); sb.append(" data: ").append(data).append("\n"); sb.append(" gpd: ").append(gpd).append("\n"); sb.append(" avs: ").append(avs).append("\n"); sb.append(" mpath: ").append(mpath).append("\n"); sb.append(" constraintChannels: ").append(constraintChannels).append("\n"); sb.append(" effect: ").append(effect).append("\n"); sb.append(" disp: ").append(disp).append("\n"); sb.append(" defbase: ").append(defbase).append("\n"); sb.append(" modifiers: ").append(modifiers).append("\n"); sb.append(" mode: ").append(mode).append("\n"); sb.append(" restore_mode: ").append(restore_mode).append("\n"); sb.append(" mat: ").append(Arrays.toString(mat)).append("\n"); sb.append(" matbits: ").append(matbits).append("\n"); sb.append(" totcol: ").append(totcol).append("\n"); sb.append(" actcol: ").append(actcol).append("\n"); sb.append(" loc: ").append(Arrays.toString(loc)).append("\n"); sb.append(" dloc: ").append(Arrays.toString(dloc)).append("\n"); sb.append(" orig: ").append(Arrays.toString(orig)).append("\n"); sb.append(" size: ").append(Arrays.toString(size)).append("\n"); sb.append(" dsize: ").append(Arrays.toString(dsize)).append("\n"); sb.append(" rot: ").append(Arrays.toString(rot)).append("\n"); sb.append(" drot: ").append(Arrays.toString(drot)).append("\n"); sb.append(" quat: ").append(Arrays.toString(quat)).append("\n"); sb.append(" dquat: ").append(Arrays.toString(dquat)).append("\n"); sb.append(" rotAxis: ").append(Arrays.toString(rotAxis)).append("\n"); sb.append(" drotAxis: ").append(Arrays.toString(drotAxis)).append("\n"); sb.append(" rotAngle: ").append(rotAngle).append("\n"); sb.append(" drotAngle: ").append(drotAngle).append("\n"); sb.append(" obmat: ").append(Arrays.toString(obmat)).append("\n"); sb.append(" parentinv: ").append(Arrays.toString(parentinv)).append("\n"); sb.append(" constinv: ").append(Arrays.toString(constinv)).append("\n"); sb.append(" imat: ").append(Arrays.toString(imat)).append("\n"); sb.append(" imat_ren: ").append(Arrays.toString(imat_ren)).append("\n"); sb.append(" lay: ").append(lay).append("\n"); sb.append(" flag: ").append(flag).append("\n"); sb.append(" colbits: ").append(colbits).append("\n"); sb.append(" transflag: ").append(transflag).append("\n"); sb.append(" protectflag: ").append(protectflag).append("\n"); sb.append(" trackflag: ").append(trackflag).append("\n"); sb.append(" upflag: ").append(upflag).append("\n"); sb.append(" nlaflag: ").append(nlaflag).append("\n"); sb.append(" ipoflag: ").append(ipoflag).append("\n"); sb.append(" ipowin: ").append(ipowin).append("\n"); sb.append(" scaflag: ").append(scaflag).append("\n"); sb.append(" scavisflag: ").append(scavisflag).append("\n"); sb.append(" boundtype: ").append(boundtype).append("\n"); sb.append(" dupon: ").append(dupon).append("\n"); sb.append(" dupoff: ").append(dupoff).append("\n"); sb.append(" dupsta: ").append(dupsta).append("\n"); sb.append(" dupend: ").append(dupend).append("\n"); sb.append(" sf: ").append(sf).append("\n"); sb.append(" ctime: ").append(ctime).append("\n"); sb.append(" mass: ").append(mass).append("\n"); sb.append(" damping: ").append(damping).append("\n"); sb.append(" inertia: ").append(inertia).append("\n"); sb.append(" formfactor: ").append(formfactor).append("\n"); sb.append(" rdamping: ").append(rdamping).append("\n"); sb.append(" sizefac: ").append(sizefac).append("\n"); sb.append(" margin: ").append(margin).append("\n"); sb.append(" max_vel: ").append(max_vel).append("\n"); sb.append(" min_vel: ").append(min_vel).append("\n"); sb.append(" m_contactProcessingThreshold: ").append(m_contactProcessingThreshold).append("\n"); sb.append(" rotmode: ").append(rotmode).append("\n"); sb.append(" dt: ").append(dt).append("\n"); sb.append(" dtx: ").append(dtx).append("\n"); sb.append(" empty_drawtype: ").append(empty_drawtype).append("\n"); sb.append(" pad1: ").append(new String(pad1)).append("\n"); sb.append(" empty_drawsize: ").append(empty_drawsize).append("\n"); sb.append(" dupfacesca: ").append(dupfacesca).append("\n"); sb.append(" prop: ").append(prop).append("\n"); sb.append(" sensors: ").append(sensors).append("\n"); sb.append(" controllers: ").append(controllers).append("\n"); sb.append(" actuators: ").append(actuators).append("\n"); sb.append(" bbsize: ").append(Arrays.toString(bbsize)).append("\n"); sb.append(" index: ").append(index).append("\n"); sb.append(" actdef: ").append(actdef).append("\n"); sb.append(" col: ").append(Arrays.toString(col)).append("\n"); sb.append(" gameflag: ").append(gameflag).append("\n"); sb.append(" gameflag2: ").append(gameflag2).append("\n"); sb.append(" bsoft: ").append(bsoft).append("\n"); sb.append(" softflag: ").append(softflag).append("\n"); sb.append(" recalc: ").append(recalc).append("\n"); sb.append(" anisotropicFriction: ").append(Arrays.toString(anisotropicFriction)).append("\n"); sb.append(" constraints: ").append(constraints).append("\n"); sb.append(" nlastrips: ").append(nlastrips).append("\n"); sb.append(" hooks: ").append(hooks).append("\n"); sb.append(" particlesystem: ").append(particlesystem).append("\n"); sb.append(" pd: ").append(pd).append("\n"); sb.append(" soft: ").append(soft).append("\n"); sb.append(" dup_group: ").append(dup_group).append("\n"); sb.append(" fluidsimFlag: ").append(fluidsimFlag).append("\n"); sb.append(" restrictflag: ").append(restrictflag).append("\n"); sb.append(" shapenr: ").append(shapenr).append("\n"); sb.append(" shapeflag: ").append(shapeflag).append("\n"); sb.append(" smoothresh: ").append(smoothresh).append("\n"); sb.append(" recalco: ").append(recalco).append("\n"); sb.append(" body_type: ").append(body_type).append("\n"); sb.append(" fluidsimSettings: ").append(fluidsimSettings).append("\n"); sb.append(" derivedDeform: ").append(derivedDeform).append("\n"); sb.append(" derivedFinal: ").append(derivedFinal).append("\n"); sb.append(" lastDataMask: ").append(lastDataMask).append("\n"); sb.append(" state: ").append(state).append("\n"); sb.append(" init_state: ").append(init_state).append("\n"); sb.append(" pad2: ").append(pad2).append("\n"); sb.append(" gpulamp: ").append(gpulamp).append("\n"); sb.append(" pc_ids: ").append(pc_ids).append("\n"); sb.append(" duplilist: ").append(duplilist).append("\n"); return sb.toString(); } public bObject copy() { try {return (bObject)super.clone();} catch(CloneNotSupportedException ex) {return null;} } }
244xiao/blender-java
blender-java/src/blender/makesdna/sdna/bObject.java
Java
gpl-2.0
24,548
#ifndef __ALPHA_MMU_CONTEXT_H #define __ALPHA_MMU_CONTEXT_H /* * get a new mmu context.. * * Copyright (C) 1996, Linus Torvalds */ #include <asm/system.h> #include <asm/machvec.h> #include <asm/compiler.h> #include <asm-generic/mm_hooks.h> /* * Force a context reload. This is needed when we change the page * table pointer or when we update the ASN of the current process. */ /* Don't get into trouble with dueling __EXTERN_INLINEs. */ #ifndef __EXTERN_INLINE #include <asm/io.h> #endif static inline unsigned long __reload_thread(struct pcb_struct *pcb) { register unsigned long a0 __asm__("$16"); register unsigned long v0 __asm__("$0"); a0 = virt_to_phys(pcb); __asm__ __volatile__( "call_pal %2 #__reload_thread" : "=r"(v0), "=r"(a0) : "i"(PAL_swpctx), "r"(a0) : "$1", "$22", "$23", "$24", "$25"); return v0; } /* * The maximum ASN's the processor supports. On the EV4 this is 63 * but the PAL-code doesn't actually use this information. On the * EV5 this is 127, and EV6 has 255. * * On the EV4, the ASNs are more-or-less useless anyway, as they are * only used as an icache tag, not for TB entries. On the EV5 and EV6, * ASN's also validate the TB entries, and thus make a lot more sense. * * The EV4 ASN's don't even match the architecture manual, ugh. And * I quote: "If a processor implements address space numbers (ASNs), * and the old PTE has the Address Space Match (ASM) bit clear (ASNs * in use) and the Valid bit set, then entries can also effectively be * made coherent by assigning a new, unused ASN to the currently * running process and not reusing the previous ASN before calling the * appropriate PALcode routine to invalidate the translation buffer (TB)". * * In short, the EV4 has a "kind of" ASN capability, but it doesn't actually * work correctly and can thus not be used (explaining the lack of PAL-code * support). */ #define EV4_MAX_ASN 63 #define EV5_MAX_ASN 127 #define EV6_MAX_ASN 255 #ifdef CONFIG_ALPHA_GENERIC # define MAX_ASN (alpha_mv.max_asn) #else # ifdef CONFIG_ALPHA_EV4 # define MAX_ASN EV4_MAX_ASN # elif defined(CONFIG_ALPHA_EV5) # define MAX_ASN EV5_MAX_ASN # else # define MAX_ASN EV6_MAX_ASN # endif #endif /* * cpu_last_asn(processor): * 63 0 * +-------------+----------------+--------------+ * | asn version | this processor | hardware asn | * +-------------+----------------+--------------+ */ #include <asm/smp.h> #ifdef CONFIG_SMP #define cpu_last_asn(cpuid) (cpu_data[cpuid].last_asn) #else extern unsigned long last_asn; #define cpu_last_asn(cpuid) last_asn #endif /* CONFIG_SMP */ #define WIDTH_HARDWARE_ASN 8 #define ASN_FIRST_VERSION (1UL << WIDTH_HARDWARE_ASN) #define HARDWARE_ASN_MASK ((1UL << WIDTH_HARDWARE_ASN) - 1) /* * NOTE! The way this is set up, the high bits of the "asn_cache" (and * the "mm->context") are the ASN _version_ code. A version of 0 is * always considered invalid, so to invalidate another process you only * need to do "p->mm->context = 0". * * If we need more ASN's than the processor has, we invalidate the old * user TLB's (tbiap()) and start a new ASN version. That will automatically * force a new asn for any other processes the next time they want to * run. */ #ifndef __EXTERN_INLINE #define __EXTERN_INLINE extern inline #define __MMU_EXTERN_INLINE #endif extern inline unsigned long __get_new_mm_context(struct mm_struct *mm, long cpu) { unsigned long asn = cpu_last_asn(cpu); unsigned long next = asn + 1; if ((asn & HARDWARE_ASN_MASK) >= MAX_ASN) { tbiap(); imb(); next = (asn & ~HARDWARE_ASN_MASK) + ASN_FIRST_VERSION; } cpu_last_asn(cpu) = next; return next; } __EXTERN_INLINE void ev5_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm, struct task_struct *next) { /* Check if our ASN is of an older version, and thus invalid. */ unsigned long asn; unsigned long mmc; long cpu = smp_processor_id(); #ifdef CONFIG_SMP cpu_data[cpu].asn_lock = 1; barrier(); #endif asn = cpu_last_asn(cpu); mmc = next_mm->context[cpu]; if ((mmc ^ asn) & ~HARDWARE_ASN_MASK) { mmc = __get_new_mm_context(next_mm, cpu); next_mm->context[cpu] = mmc; } #ifdef CONFIG_SMP else cpu_data[cpu].need_new_asn = 1; #endif /* Always update the PCB ASN. Another thread may have allocated a new mm->context (via flush_tlb_mm) without the ASN serial number wrapping. We have no way to detect when this is needed. */ task_thread_info(next)->pcb.asn = mmc & HARDWARE_ASN_MASK; } __EXTERN_INLINE void ev4_switch_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm, struct task_struct *next) { /* As described, ASN's are broken for TLB usage. But we can optimize for switching between threads -- if the mm is unchanged from current we needn't flush. */ /* ??? May not be needed because EV4 PALcode recognizes that ASN's are broken and does a tbiap itself on swpctx, under the "Must set ASN or flush" rule. At least this is true for a 1992 SRM, reports Joseph Martin (jmartin@hlo.dec.com). I'm going to leave this here anyway, just to Be Sure. -- r~ */ if (prev_mm != next_mm) tbiap(); /* Do continue to allocate ASNs, because we can still use them to avoid flushing the icache. */ ev5_switch_mm(prev_mm, next_mm, next); } extern void __load_new_mm_context(struct mm_struct *); #ifdef CONFIG_SMP #define check_mmu_context() \ do { \ int cpu = smp_processor_id(); \ cpu_data[cpu].asn_lock = 0; \ barrier(); \ if (cpu_data[cpu].need_new_asn) { \ struct mm_struct * mm = current->active_mm; \ cpu_data[cpu].need_new_asn = 0; \ if (!mm->context[cpu]) \ __load_new_mm_context(mm); \ } \ } while(0) #else #define check_mmu_context() do { } while(0) #endif __EXTERN_INLINE void ev5_activate_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm) { __load_new_mm_context(next_mm); } __EXTERN_INLINE void ev4_activate_mm(struct mm_struct *prev_mm, struct mm_struct *next_mm) { __load_new_mm_context(next_mm); tbiap(); } #define deactivate_mm(tsk,mm) do { } while (0) #ifdef CONFIG_ALPHA_GENERIC # define switch_mm(a,b,c) alpha_mv.mv_switch_mm((a),(b),(c)) # define activate_mm(x,y) alpha_mv.mv_activate_mm((x),(y)) #else # ifdef CONFIG_ALPHA_EV4 # define switch_mm(a,b,c) ev4_switch_mm((a),(b),(c)) # define activate_mm(x,y) ev4_activate_mm((x),(y)) # else # define switch_mm(a,b,c) ev5_switch_mm((a),(b),(c)) # define activate_mm(x,y) ev5_activate_mm((x),(y)) # endif #endif static inline int init_new_context(struct task_struct *tsk, struct mm_struct *mm) { int i; for_each_online_cpu(i) mm->context[i] = 0; if (tsk != current) task_thread_info(tsk)->pcb.ptbr = ((unsigned long)mm->pgd - IDENT_ADDR) >> PAGE_SHIFT; return 0; } extern inline void destroy_context(struct mm_struct *mm) { /* Nothing to do. */ } static inline void enter_lazy_tlb(struct mm_struct *mm, struct task_struct *tsk) { task_thread_info(tsk)->pcb.ptbr = ((unsigned long)mm->pgd - IDENT_ADDR) >> PAGE_SHIFT; } #ifdef __MMU_EXTERN_INLINE #undef __EXTERN_INLINE #undef __MMU_EXTERN_INLINE #endif #endif /* __ALPHA_MMU_CONTEXT_H */
jeffegg/beaglebone
arch/alpha/include/asm/mmu_context.h
C
gpl-2.0
7,447
// automatically generated by m4 from headers in proto subdir #ifndef _ADT_WV_STACK_H #define _ADT_WV_STACK_H #include <stddef.h> // DATA STRUCTURES typedef struct wv_stack_s { void *data; size_t size; size_t capacity; size_t max_size; } wv_stack_t; extern size_t __LIB__ __FASTCALL__ wv_stack_capacity(wv_stack_t *s); extern void __LIB__ __FASTCALL__ wv_stack_clear(wv_stack_t *s); extern void __LIB__ __FASTCALL__ wv_stack_destroy(wv_stack_t *s); extern int __LIB__ __FASTCALL__ wv_stack_empty(wv_stack_t *s); extern wv_stack_t __LIB__ *wv_stack_init(void *p,size_t capacity,size_t max_size); extern wv_stack_t __LIB__ __CALLEE__ *wv_stack_init_callee(void *p,size_t capacity,size_t max_size); #define wv_stack_init(a,b,c) wv_stack_init_callee(a,b,c) extern size_t __LIB__ __FASTCALL__ wv_stack_max_size(wv_stack_t *s); extern void __LIB__ __FASTCALL__ *wv_stack_pop(wv_stack_t *s); extern int __LIB__ wv_stack_push(wv_stack_t *s,void *item); extern int __LIB__ __CALLEE__ wv_stack_push_callee(wv_stack_t *s,void *item); #define wv_stack_push(a,b) wv_stack_push_callee(a,b) extern int __LIB__ wv_stack_reserve(wv_stack_t *s,size_t n); extern int __LIB__ __CALLEE__ wv_stack_reserve_callee(wv_stack_t *s,size_t n); #define wv_stack_reserve(a,b) wv_stack_reserve_callee(a,b) extern int __LIB__ __FASTCALL__ wv_stack_shrink_to_fit(wv_stack_t *s); extern size_t __LIB__ __FASTCALL__ wv_stack_size(wv_stack_t *s); extern void __LIB__ __FASTCALL__ *wv_stack_top(wv_stack_t *s); #endif
bitfixer/bitfixer
dg/z88dk/include/_DEVELOPMENT/sccz80/adt/wv_stack.h
C
gpl-2.0
1,548
#include "sdl13_eventmanager.h" #include "common/SDL_InputSwitch.h" using namespace event_manager; #define NB_CONTROLS 10 static InputSwitch *keyControls[NB_CONTROLS] = { new KeyInputSwitch(SDLK_s,true), new KeyInputSwitch(SDLK_f,true), new KeyInputSwitch(SDLK_d,true), new KeyInputSwitch(SDLK_UNKNOWN,true), new KeyInputSwitch(SDLK_e,true), new KeyInputSwitch(SDLK_LEFT,true), new KeyInputSwitch(SDLK_RIGHT,true), new KeyInputSwitch(SDLK_DOWN,true), new KeyInputSwitch(SDLK_UNKNOWN,true), new KeyInputSwitch(SDLK_UP,true) }; static InputSwitch *keyAlternateControls[NB_CONTROLS] = { new JoystickAxisSwitch(0, 0, false, false), new JoystickAxisSwitch(0, 0, true, false), new JoystickAxisSwitch(0, 1, true, false), new JoystickSwitch(0, 1, false), new JoystickSwitch(0, 0, false), new JoystickAxisSwitch(1, 0, false, false), new JoystickAxisSwitch(1, 0, true, false), new JoystickAxisSwitch(1, 1, true, false), new JoystickSwitch(1, 1, false), new JoystickSwitch(1, 0, false) }; static void getControlEvent(SDL_Event e, InputSwitch *input, GameControlEvent *result) { result->gameEvent = kGameNone; result->cursorEvent = kCursorNone; result->keyboardEvent = kKeyboardNone; result->isUp = true; result->caught = false; result->isJoystick = false; result->unicodeKeySym = 0; switch (e.type) { case SDL_QUIT: result->cursorEvent = kQuit; break; case SDL_KEYDOWN: result->keyboardEvent = kKeyboardDown; result->unicodeKeySym = e.key.keysym.unicode; break; case SDL_KEYUP: result->keyboardEvent = kKeyboardUp; result->unicodeKeySym = e.key.keysym.unicode; break; default: break; } // Game event handling if (input == NULL) return; result->isJoystick = input->isJoystick(); if (input->isQuit()) result->cursorEvent = kQuit; if (input->isValidate()) result->cursorEvent = kStart; if (input->isCancel()) result->cursorEvent = kBack; if (input->isArrowDown()) result->cursorEvent = kDown; if (input->isArrowUp()) result->cursorEvent = kUp; if (input->isArrowLeft()) result->cursorEvent = kLeft; if (input->isArrowRight()) result->cursorEvent = kRight; if (input->isPause()) result->gameEvent = kPauseGame; result->isUp = input->isUp(); if ((*input == *keyControls[kPlayer1LeftControl]) || (*input == *keyAlternateControls[kPlayer1LeftControl])) result->gameEvent = kPlayer1Left; if ((*input == *keyControls[kPlayer1RightControl]) || (*input == *keyAlternateControls[kPlayer1RightControl])) result->gameEvent = kPlayer1Right; if ((*input == *keyControls[kPlayer1ClockwiseControl]) || (*input == *keyAlternateControls[kPlayer1ClockwiseControl])) result->gameEvent = kPlayer1TurnRight; if ((*input == *keyControls[kPlayer1CounterclockwiseControl]) || (*input == *keyAlternateControls[kPlayer1CounterclockwiseControl])) result->gameEvent = kPlayer1TurnLeft; if ((*input == *keyControls[kPlayer1DownControl]) || (*input == *keyAlternateControls[kPlayer1DownControl])) result->gameEvent = kPlayer1Down; if ((*input == *keyControls[kPlayer2LeftControl]) || (*input == *keyAlternateControls[kPlayer2LeftControl])) result->gameEvent = kPlayer2Left; if ((*input == *keyControls[kPlayer2RightControl]) || (*input == *keyAlternateControls[kPlayer2RightControl])) result->gameEvent = kPlayer2Right; if ((*input == *keyControls[kPlayer2ClockwiseControl]) || (*input == *keyAlternateControls[kPlayer2ClockwiseControl])) result->gameEvent = kPlayer2TurnRight; if ((*input == *keyControls[kPlayer2CounterclockwiseControl]) || (*input == *keyAlternateControls[kPlayer2CounterclockwiseControl])) result->gameEvent = kPlayer2TurnLeft; if ((*input == *keyControls[kPlayer2DownControl]) || (*input == *keyAlternateControls[kPlayer2DownControl])) result->gameEvent = kPlayer2Down; } static void getControlEvent(SDL_Event e, GameControlEvent *result) { InputSwitch *input = switchForEvent(&e); getControlEvent(e, input, result); if (input) delete input; } ios_fc::String SDL13_EventManager::getControlName(int controlType, bool alternate) { ios_fc::String controlName(" "); if (alternate) { if (keyAlternateControls[controlType]) controlName = keyAlternateControls[controlType]->name(); } else { if (keyControls[controlType]) controlName = keyControls[controlType]->name(); } return controlName; } bool SDL13_EventManager::changeControl(int controlType, bool alternate, GameControlEvent &event) { return true; } void SDL13_EventManager::saveControls() { } struct CursorEventArg { CursorEventArg(int x, int y) : x(x), y(y) {} int x, y; }; SDL13_EventManager::SDL13_EventManager() : CycledComponent(0.01), m_idleDx(0), m_idleDy(0), m_mouseX(0), m_mouseY(0) { SDL_EnableUNICODE(1); } bool SDL13_EventManager::pollEvent(GameControlEvent &controlEvent) { SDL_Event e; bool result = SDL_PollEvent(&e); // Try to translate the SDL event into a game event // Try to translate the SDL event into a cursor event // Try to translate the SDL event into a keyboard event getControlEvent(e, &controlEvent); // Try to translate the SDL event into a mouse event translateMouseEvent(e, controlEvent); return result; } void SDL13_EventManager::pushMouseEvent(int x, int y, CursorEventType type) { // Push an SDL user event SDL_Event mouseEvent; mouseEvent.type = SDL_USEREVENT; mouseEvent.user.code = type; mouseEvent.user.data1 = new CursorEventArg(x, y); SDL_PushEvent(&mouseEvent); } void SDL13_EventManager::translateMouseEvent(const SDL_Event &sdl_event, GameControlEvent &controlEvent) { switch (sdl_event.type) { case SDL_MOUSEMOTION: m_mouseX = sdl_event.motion.x; m_mouseY = sdl_event.motion.y; controlEvent.isUp = false; controlEvent.cursorEvent = kGameMouseMoved; controlEvent.x = m_mouseX; controlEvent.y = m_mouseY; break; case SDL_JOYAXISMOTION: if (sdl_event.jaxis.axis == 2) { m_idleDy = sdl_event.jaxis.value / 5000; } else if (sdl_event.jaxis.axis == 3) { m_idleDx = sdl_event.jaxis.value / 5000; } break; case SDL_MOUSEBUTTONDOWN: if (sdl_event.button.button == SDL_BUTTON_LEFT) { controlEvent.isUp = false; controlEvent.cursorEvent = kGameMouseDown; controlEvent.x = sdl_event.button.x; controlEvent.y = sdl_event.button.y; } break; case SDL_MOUSEBUTTONUP: if (sdl_event.button.button == SDL_BUTTON_LEFT) { controlEvent.isUp = true; controlEvent.cursorEvent = kGameMouseUp; controlEvent.x = sdl_event.button.x; controlEvent.y = sdl_event.button.y; } break; case SDL_USEREVENT: { switch (sdl_event.user.code) { case kGameMouseMoved: case kGameMouseDown: case kGameMouseUp: { CursorEventArg *arg = (CursorEventArg *)sdl_event.user.data1; controlEvent.x = arg->x; controlEvent.y = arg->y; delete arg; } break; default: break; } switch (sdl_event.user.code) { case kGameMouseMoved: controlEvent.isUp = false; controlEvent.cursorEvent = kGameMouseMoved; break; case kGameMouseDown: controlEvent.isUp = false; controlEvent.cursorEvent = kGameMouseDown; break; case kGameMouseUp: controlEvent.isUp = true; controlEvent.cursorEvent = kGameMouseUp; break; default: break; } } default: break; } } void SDL13_EventManager::cycle() { if ((m_idleDx * m_idleDx) + (m_idleDy * m_idleDy) < 1) return; m_mouseX += m_idleDx; m_mouseY += m_idleDy; pushMouseEvent(m_mouseX, m_mouseY, kGameMouseMoved); }
flboudet/flobz
gametools/sdl_drawcontext/sdl13/sdl13_eventmanager.cpp
C++
gpl-2.0
8,463
package org.nextprot.api.core.service; import org.junit.Ignore; import org.junit.Test; import org.nextprot.api.commons.constants.AnnotationCategory; import org.nextprot.api.core.domain.BioObject; import org.nextprot.api.core.domain.Interaction; import org.nextprot.api.core.domain.Isoform; import org.nextprot.api.core.domain.annotation.Annotation; import org.nextprot.api.core.domain.annotation.AnnotationEvidence; import org.nextprot.api.core.domain.annotation.AnnotationIsoformSpecificity; import org.nextprot.api.core.test.base.CoreUnitBaseTest; import org.nextprot.api.core.utils.BinaryInteraction2Annotation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.*; @ActiveProfiles({ "dev" }) public class InteractionServiceIntegrationTest extends CoreUnitBaseTest { @Autowired private InteractionService interactionService; @Autowired private StatementService statementService; @Autowired private IsoformService isoformService; @Autowired private MainNamesService mainNamesService; @Ignore @Test public void shouldWork() throws BinaryInteraction2Annotation.MissingInteractantEntryException { String entryName = "NX_P38398"; List<Annotation> annots = new ArrayList<>(); List<Isoform> isoforms = this.isoformService.findIsoformsByEntryName(entryName); List<Interaction> interactions = this.interactionService.findInteractionsByEntry(entryName); for (Interaction inter : interactions) { Annotation annot = BinaryInteraction2Annotation.transform(inter, entryName, isoforms, mainNamesService); annots.add(annot); BioObject bo = annot.getBioObject(); if (bo!=null && (bo.getAccession().equals("NX_Q92560") || bo.getAccession().equals("Q99PU7")) ) { System.out.print(inter.getEvidenceXrefAC() + ": "); System.out.print (inter.getInteractants().get(0).getAccession()); if (inter.getInteractants().size()==2) System.out.print( " <==> " + inter.getInteractants().get(1)); } } } /* * This queries retrieves entries with their * - count of xeno interactions * - count of self interactions * - count of interactions with another protein entry defined in nextprot * - count of interactions whih another protein isoform defined in nextprot * - count of isoform specific interactions * * and can be used to find test examples * select entry_ac, sum(is_iso_spec) as iso_spec_interactions, sum(has_xeno) as with_xeno, sum(has_self) as with_self, sum(has_iso) as with_isos, sum(has_entry) as entries, sum(has_xeno)+ sum(has_self)+ sum(has_iso)+ sum(has_entry) as interaction_count from ( select xr1.accession, (regexp_split_to_array(xr1.accession,'-'))[1] as entry_ac, case when xr1.accession like '%-%' then 1 else 0 end as is_iso_spec, case when inter.is_xeno then 1 else 0 end as has_xeno, case when interactant1.is_self_interaction then 1 else 0 end as has_self, case when inter.is_xeno is false and interactant1.is_self_interaction is false and xr2.accession ilike '%-%' then 1 else 0 end as has_iso, case when inter.is_xeno is false and interactant1.is_self_interaction is false and xr2.accession not ilike '%-%' then 1 else 0 end as has_entry from partnerships inter inner join partnership_partner_assoc interactant1 on (inter.partnership_id=interactant1.partnership_id) inner join db_xrefs xr1 on (interactant1.db_xref_id=xr1.resource_id) left outer join partnership_partner_assoc interactant2 on (inter.partnership_id=interactant2.partnership_id and interactant1.assoc_id != interactant2.assoc_id or interactant2.assoc_id is null) left outer join db_xrefs xr2 on (interactant2.db_xref_id=xr2.resource_id) ) a group by entry_ac having sum(has_xeno)>0 and sum(has_self)>0 and sum(has_iso)>0 and sum(has_entry)>0 order by sum(has_xeno)+ sum(has_self)+ sum(has_iso)+ sum(has_entry) */ /* * NX_Q9UNQ0 should contain at least 1 interactions of each type: * - self interaction * - xeno interaction (interaction with a protein not defined in nextprot, see resourceinternalrefs * - interaction with another nextprot entry * - interaction with another nextprot specific isoform * and there should at least 1 interaction declared as isoform specific * * see query above to find other examples if necessary in future releases */ @Ignore @Test public void shouldDealWithAnyInteractionSpecialInteraction() { String entry_ac="NX_Q9UNQ0"; List<Annotation> annots = this.statementService.getAnnotations(entry_ac) .stream() .filter(a -> "BinaryInteraction".equals(a.getCategory())) .collect(Collectors.toList()); int numberOfExperiments = 0; int withNxEntries = 0; int withNxIsos = 0; int withSelf = 0; int withXrefs = 0; int isoSpecs = 0; for (Annotation annot: annots) { /* System.out.println("partner " + annot.getBioObject().getAccession() + " " + annot.getBioObject().getBioType() + " / " + annot.getBioObject().getResourceType()); */ // basic checks assertTrue(annot.getCategory().equals("BinaryInteraction")); assertTrue(annot.getAPICategory() == AnnotationCategory.BINARY_INTERACTION); // partners if (isAnnotationASelfInteraction(annot, entry_ac)) withSelf ++; if (isAnnotationAnInteractionWithAnExternalXrefAsPartner(annot)) withXrefs++; if (isAnnotationAnInteractionWithaNextprotEntryAsPartner(annot, entry_ac)) withNxEntries++; if (isAnnotationAnInteractionWithANextprotIsoformAsPartner(annot)) withNxIsos++; // specificity of annotation subject if (isAnnotationAnInteractionWithANextprotIsoformAsSubject(annot)) isoSpecs++; // evidences assertTrue(annot.getEvidences().size() >= 1); boolean hasPropertyNumberOfExperiments = false; for (AnnotationEvidence evi : annot.getEvidences()) { assertTrue(evi.getQualityQualifier().equals("GOLD") || evi.getQualityQualifier().equals("SILVER")); if ("database".equals(evi.getResourceType())) { assertEquals("IntAct", evi.getResourceDb()); } if (evi.getPropertyValue("numberOfExperiments") != null) { hasPropertyNumberOfExperiments = true; } } if (hasPropertyNumberOfExperiments) { numberOfExperiments++; } } /* System.out.println("numberOfExperiments:" + numberOfExperiments); System.out.println("withNxEntries:" + withNxEntries); System.out.println("withNxIsos:" + withNxIsos); System.out.println("withSelf:" + withSelf ); System.out.println("withXrefs:" + withXrefs ); System.out.println("isoSpecs:" + isoSpecs ); */ assertTrue(numberOfExperiments==annots.size()); // should exist for each interaction assertTrue(withNxEntries >= 1); // 21 cases assertTrue(withNxIsos >= 1); // 2 cases assertTrue(withXrefs >= 1); // 11 cases assertTrue(withSelf == 1); // 1 case assertTrue(isoSpecs > 1); // 17 cases } private boolean isAnnotationASelfInteraction(Annotation annot, String entry_ac) { return annot.getBioObject().getAccession().equals(entry_ac); } private boolean isAnnotationAnInteractionWithAnExternalXrefAsPartner(Annotation annot) { return annot.getBioObject().getResourceType().equals(BioObject.ResourceType.EXTERNAL); } private boolean isAnnotationAnInteractionWithaNextprotEntryAsPartner(Annotation annot, String entry_ac) { return annot.getBioObject().getResourceType().equals(BioObject.ResourceType.INTERNAL) && annot.getBioObject().getBioType().equals(BioObject.BioType.PROTEIN) && ! annot.getBioObject().getAccession().equals(entry_ac); } private boolean isAnnotationAnInteractionWithANextprotIsoformAsPartner(Annotation annot) { return annot.getBioObject().getBioType().equals(BioObject.BioType.PROTEIN_ISOFORM); } private boolean isAnnotationAnInteractionWithANextprotIsoformAsSubject(Annotation annot) { for (AnnotationIsoformSpecificity spec : annot.getTargetingIsoformsMap().values()) { if (spec.getSpecificity().equals("SPECIFIC")) return true; } return false; } /* * This query retrieves isoforms that are annotated as having as specific interaction with * another nextprot entry or isoform * isoformWithSpecificInteraction: use the entry of this isoform to get an example of isoform specific interaction * interactingEntity: the interaction partner of isoformWithSpecificInteraction * select xr1.accession as isoformWithSpecificInteraction, xr2.accession as interactingEntity from partnerships inter inner join partnership_partner_assoc interactant1 on (inter.partnership_id=interactant1.partnership_id) inner join db_xrefs xr1 on (interactant1.db_xref_id=xr1.resource_id) inner join partnership_partner_assoc interactant2 on (inter.partnership_id=interactant2.partnership_id and interactant1.assoc_id != interactant2.assoc_id or interactant2.assoc_id is null) inner join db_xrefs xr2 on (interactant2.db_xref_id=xr2.resource_id) where xr1.accession ilike '%-%' limit 10 * */ /* * NX_Q6ZMQ8 should contain an interaction with P61810 having the specificity SPECIFIC * Note that other isoform SPECIFIC interactions (as annotations) exist for this entry. */ }
calipho-sib/nextprot-api
core/src/test/java/org/nextprot/api/core/service/InteractionServiceIntegrationTest.java
Java
gpl-2.0
9,157
package runner import ( "fmt" //"error" //"log" //"os" //"io" "github.com/go-QA/logger" //"../logger" //"runtime" "time" ) const ( MAX_WAIT_MATCH_RETURN = 3000 // Maximum time in milliseconds to wait for build return message ) type RunId int func (ri RunId) String() string { return fmt.Sprintf("%d", ri) } type RunInfo struct { Id RunId Name string LaunchType string } type BuildInfo struct { Version string Project string Path string BuildComplete time.Time } type Matcher interface { FindMatches(buildInfo BuildInfo) []RunInfo } type BuildMockMatch struct { runNum RunId } func (mock *BuildMockMatch) FindMatches(buildInfo BuildInfo) []RunInfo { return []RunInfo{ {Id: mock.runNum, Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum, buildInfo.Version), LaunchType: "auto"}, {Id: mock.runNum + 1, Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum+1, buildInfo.Version), LaunchType: "manual"}, {Id: mock.runNum + 2, Name: fmt.Sprintf("Runplan_%d_%s", mock.runNum+2, buildInfo.Version), LaunchType: "auto"}, } } type InternalBuildMatcher struct { m_log *logger.GoQALog matcher Matcher chnBuilds chan InternalCommandInfo chnRunplans *CommandQueue chnExit chan int isStopRequested bool } func (ibm *InternalBuildMatcher) GetBuildInfo(info InternalCommandInfo) (BuildInfo, error) { var buildInfo BuildInfo var err error if info.Command == CMD_NEW_BUILD { buildInfo = BuildInfo{Version: info.Data[0].(string), Project: info.Data[1].(string), Path: info.Data[2].(string)} } else { buildInfo = BuildInfo{} err = &myError{mes: "No build info"} } return buildInfo, err } func (ibm *InternalBuildMatcher) CreatRunInfoMes(cmd *InternalCommandInfo, run RunInfo) { //cmd := new(InternalCommandInfo) cmd.Command = CMD_LAUNCH_RUN cmd.ChnReturn = make(chan CommandInfo) cmd.Data = []interface{}{run.Id, run.Name, run.LaunchType} return } func (ibm *InternalBuildMatcher) Init(iMatch Matcher, inChn chan InternalCommandInfo, outChn *CommandQueue, chnExit chan int, log *logger.GoQALog) { ibm.matcher = iMatch ibm.chnBuilds = inChn ibm.chnRunplans = outChn ibm.chnExit = chnExit ibm.m_log = log ibm.isStopRequested = false } func (ibm *InternalBuildMatcher) Stop(mes int) bool { return true } func (ibm *InternalBuildMatcher) OnMessageRecieved(nextMessage InternalCommandInfo) { var outMes *InternalCommandInfo nextBuild, err := ibm.GetBuildInfo(nextMessage) if err == nil { newRunplans := ibm.matcher.FindMatches(nextBuild) if newRunplans != nil { for _, run := range newRunplans { outMes = new(InternalCommandInfo) //ibm.m_log.LogMessage("BuildMatcher mesOut = %p", outMes) ibm.CreatRunInfoMes(outMes, run) *ibm.chnRunplans <- *outMes go func(mes *InternalCommandInfo) { select { case resv := <-(*mes).ChnReturn: ibm.m_log.LogMessage("BuildMatcher resv = %s %s %p", CmdName(resv.Command), resv.Data[0].(string), mes) case <-time.After(time.Millisecond * MAX_WAIT_MATCH_RETURN): ibm.m_log.LogMessage("BuildMatcher Timed out %v %p", mes, mes) } }(outMes) } nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, fmt.Sprintf("launched %d runs", len(newRunplans))) } else { nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, "no runs matched") } } else { ibm.m_log.LogError("GetBuildInfo::%s", err) nextMessage.ChnReturn <- GetMessageInfo(CMD_OK, "Build match err", err.Error()) } } func (ibm *InternalBuildMatcher) Run() { ibm.isStopRequested = false for ibm.isStopRequested == false { select { case nextMessage := <-ibm.chnBuilds: go ibm.OnMessageRecieved(nextMessage) case exitMessage := <-ibm.chnExit: ibm.isStopRequested = ibm.Stop(exitMessage) case <-time.After(time.Millisecond * LOOP_WAIT_TIMER): } ibm.onProcessEvents() } ibm.m_log.LogDebug("Out of Main loop") } func (ibm *InternalBuildMatcher) onProcessEvents() { ibm.m_log.LogDebug("Matcher Process Events") }
go-QA/runner
dispatcher.go
GO
gpl-2.0
4,192
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>SmartSorter: MoveCommand Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">SmartSorter &#160;<span id="projectnumber">1</span> </div> </td> </tr> </tbody> </table> </div> <!-- Generated by Doxygen 1.7.6.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <div class="title">MoveCommand Class Reference</div> </div> </div><!--header--> <div class="contents"> <!-- doxytag: class="MoveCommand" --><!-- doxytag: inherits="Command" --> <p>Move operation. <a href="classMoveCommand.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="command_8h_source.html">command.h</a>&gt;</code></p> <div class="dynheader"> Inheritance diagram for MoveCommand:</div> <div class="dyncontent"> <div class="center"> <img src="classMoveCommand.png" usemap="#MoveCommand_map" alt=""/> <map id="MoveCommand_map" name="MoveCommand_map"> <area href="classCommand.html" title="Virtual class." alt="Command" shape="rect" coords="0,0,99,24"/> </map> </div></div> <p><a href="classMoveCommand-members.html">List of all members.</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a096b524bf604c0104c2a765beb486228"></a><!-- doxytag: member="MoveCommand::Execute" ref="a096b524bf604c0104c2a765beb486228" args="()" --> void&#160;</td><td class="memItemRight" valign="bottom"><b>Execute</b> ()</td></tr> <tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a204f430f154d2826a36e5805a4e36b51"></a><!-- doxytag: member="MoveCommand::Undo" ref="a204f430f154d2826a36e5805a4e36b51" args="()" --> void&#160;</td><td class="memItemRight" valign="bottom"><b>Undo</b> ()</td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><p>Move operation. </p> <p>Move file to new destination </p> <p>Definition at line <a class="el" href="command_8h_source.html#l00042">42</a> of file <a class="el" href="command_8h_source.html">command.h</a>.</p> </div><hr/>The documentation for this class was generated from the following files:<ul> <li>Base/code/<a class="el" href="command_8h_source.html">command.h</a></li> <li>Base/code/<a class="el" href="command_8cpp_source.html">command.cpp</a></li> </ul> </div><!-- contents --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small> Generated on Fri May 15 2015 23:34:51 for SmartSorter by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.7.6.1 </small></address> </body> </html>
radimsvacek/SmartSorter
doc/classMoveCommand.html
HTML
gpl-2.0
6,098
package stagetime; public enum WorkingSpace { OPEN_SPACE, OFFICE, PRIVATE_OFFICE, TELE_COMMUTING; }
libreware/StageTime
src/java/stagetime/WorkingSpace.java
Java
gpl-2.0
105
/* Copyright 1991, 1998 The Open Group Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. 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 OPEN GROUP 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. Except as contained in this notice, the name of The Open Group shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from The Open Group. */ /* * Author: Keith Packard, MIT X Consortium */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "libxfontint.h" #include "src/util/replace.h" #include <X11/fonts/fntfilst.h> BitmapSourcesRec FontFileBitmapSources; Bool FontFileRegisterBitmapSource (FontPathElementPtr fpe) { FontPathElementPtr *new; int i; int newsize; for (i = 0; i < FontFileBitmapSources.count; i++) if (FontFileBitmapSources.fpe[i] == fpe) return TRUE; if (FontFileBitmapSources.count == FontFileBitmapSources.size) { newsize = FontFileBitmapSources.size + 4; new = reallocarray (FontFileBitmapSources.fpe, newsize, sizeof *new); if (!new) return FALSE; FontFileBitmapSources.size = newsize; FontFileBitmapSources.fpe = new; } FontFileBitmapSources.fpe[FontFileBitmapSources.count++] = fpe; return TRUE; } void FontFileUnregisterBitmapSource (FontPathElementPtr fpe) { int i; for (i = 0; i < FontFileBitmapSources.count; i++) if (FontFileBitmapSources.fpe[i] == fpe) { FontFileBitmapSources.count--; if (FontFileBitmapSources.count == 0) { FontFileBitmapSources.size = 0; free (FontFileBitmapSources.fpe); FontFileBitmapSources.fpe = 0; } else { for (; i < FontFileBitmapSources.count; i++) FontFileBitmapSources.fpe[i] = FontFileBitmapSources.fpe[i+1]; } break; } } /* * Our set_path_hook: unregister all bitmap sources. * This is necessary because already open fonts will keep their FPEs * allocated, but they may not be on the new font path. * The bitmap sources in the new path will be registered by the init_func. */ void FontFileEmptyBitmapSource(void) { if (FontFileBitmapSources.count == 0) return; FontFileBitmapSources.count = 0; FontFileBitmapSources.size = 0; free (FontFileBitmapSources.fpe); FontFileBitmapSources.fpe = 0; } int FontFileMatchBitmapSource (FontPathElementPtr fpe, FontPtr *pFont, int flags, FontEntryPtr entry, FontNamePtr zeroPat, FontScalablePtr vals, fsBitmapFormat format, fsBitmapFormatMask fmask, Bool noSpecificSize) { int source; FontEntryPtr zero; FontBitmapEntryPtr bitmap; int ret; FontDirectoryPtr dir; FontScaledPtr scaled; /* * Look through all the registered bitmap sources for * the same zero name as ours; entries along that one * can be scaled as desired. */ ret = BadFontName; for (source = 0; source < FontFileBitmapSources.count; source++) { if (FontFileBitmapSources.fpe[source] == fpe) continue; dir = (FontDirectoryPtr) FontFileBitmapSources.fpe[source]->private; zero = FontFileFindNameInDir (&dir->scalable, zeroPat); if (!zero) continue; scaled = FontFileFindScaledInstance (zero, vals, noSpecificSize); if (scaled) { if (scaled->pFont) { *pFont = scaled->pFont; (*pFont)->fpe = FontFileBitmapSources.fpe[source]; ret = Successful; } else if (scaled->bitmap) { entry = scaled->bitmap; bitmap = &entry->u.bitmap; if (bitmap->pFont) { *pFont = bitmap->pFont; (*pFont)->fpe = FontFileBitmapSources.fpe[source]; ret = Successful; } else { ret = FontFileOpenBitmap ( FontFileBitmapSources.fpe[source], pFont, flags, entry, format, fmask); if (ret == Successful && *pFont) (*pFont)->fpe = FontFileBitmapSources.fpe[source]; } } else /* "cannot" happen */ { ret = BadFontName; } break; } } return ret; }
TurboVNC/turbovnc
unix/Xvnc/lib/libXfont2/src/fontfile/bitsource.c
C
gpl-2.0
4,720
<?php /** * The Template for displaying all single posts. * * @package WordPress * @subpackage Twenty_Eleven * @since Twenty Eleven 1.0 */ ; ?> <?php include ('header-single-news.php'); ?> <div id="primary1"> <div id="content1" role="main"> <?php global $more; $more = 0; ?> <div class="ohu_sidebar1"> <div style="margin-bottom:5px;"><span class="redtext" stlye="line-height:2em;">NEWSFEED</span></div> <img src="http://onehopeunited.org/wp-content/themes/ohu/images/white.gif" style="vertical-align:middle;"> <a href="http://onehopeunited.org/news/">Show All News</a><br /> <img src="http://onehopeunited.org/wp-content/themes/ohu/images/in-the-news-white.gif" style="vertical-align:middle;"> <a href="http://onehopeunited.org/news/in-the-news/" style="color:gray;">In The News</a><br /> <img src="http://onehopeunited.org/wp-content/themes/ohu/images/stories-of-hope-white.gif" style="vertical-align:middle;" style="color:gray;"> <a href="http://onehopeunited.org/news/stories-of-hope/" style="color:gray;">Stories of Hope</a><br /> <img src="http://onehopeunited.org/wp-content/themes/ohu/images/press-releases-white.gif" style="vertical-align:middle;"> <a href="http://onehopeunited.org/news/press-releases/" style="color:gray;">Press Releases</a><br /> <img src="http://onehopeunited.org/wp-content/themes/ohu/images/everyday-heroes-white.gif" style="vertical-align:middle;"> <a href="http://onehopeunited.org/news/everyday-heroes/" style="color:gray;">Everyday Heroes</a> <div style="border-top:1px solid #ccc;padding-top:10px;margin-top:10px;"> <b>MEDIA CONTACT:</b><br /> Fotena Zirps, Executive Vice President<br /> <a href="mailto:FZirps@onehopeunited.org">FZirps@onehopeunited.org</a><br /> 850.212.6415</br></br> Cassie Monroe, Communications<br /> <a href="mailto:CMonroe@onehopeunited.org">CMonroe@onehopeunited.org</a><br /> 312.949.5651 </div> <div style="border-top:1px solid #ccc;padding-top:10px;margin-top:10px;"> <span class="redtext">FIND NEWS IN YOUR AREA</span> <br /><br /> <div style="margin-left:-20px;"> <img id="Image-Maps_8201208131652306" src="http://onehopeunited.org/wp-content/themes/ohu/images/small-map-new.gif" usemap="#Image-Maps_8201208131652306" border="0" width="250" height="324" alt="" /> <map id="_Image-Maps_8201208131652306" name="Image-Maps_8201208131652306"> <area shape="rect" coords="0,0,250,124" href="http://onehopeunited.org/news/northern-illinois-wisconsin/" alt="" title="" onMouseOver="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-red-new.gif';" onMouseOut="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-new.gif';" /> <area shape="rect" coords="0,125,250,230" href="http://onehopeunited.org/news/central-southern-illinois-missouri" alt="" title="" onMouseOver="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-yellow-new.gif';" onMouseOut="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-new.gif';" /> <area shape="rect" coords="0,231,250,324" href="http://onehopeunited.org/news/florida/" alt="" title="" onMouseOver="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-blue-new.gif';" onMouseOut="if(document.images) document.getElementById('Image-Maps_8201208131652306').src= 'http://onehopeunited.org/wp-content/themes/ohu/images/small-map-new.gif';" /> </map> </map> </div> </div> <div style="border-top:1px solid #ccc;padding-top:10px;margin-top:10px;"> <b>OHU TWITTER FEED:</b> <br /> <script charset="utf-8" src="http://widgets.twimg.com/j/2/widget.js"></script> <script> new TWTR.Widget({ version: 2, type: 'profile', rpp: 4, interval: 30000, width: 220, height: 300, theme: { shell: { background: '#ffffff', color: '#787878' }, tweets: { background: '#ffffff', color: '#a1a1a1', links: '#0775eb' } }, features: { scrollbar: false, loop: false, live: false, behavior: 'all' } }).render().setUser('1HopeUnited').start(); </script> </div> </div> <div class="entry-content1" style="margin-top:55px;"> <span class="redtext">ONE HOPE</span> <span class="bluetext">NEWSFEED</span> > <?php the_title();?> <div style="border-top:1px solid #ccc;padding-top:10px;margin-top:10px;margin-bottom:10px;"> <span class="graytext">SORT BY REGION:</span> </div> <table width="550"> <tr> <td> <a href="http://onehopeunited.org/news/northern-illinois-wisconsin/" style="text-decoration:none;"><div class="redbutton" style="border-radius:10px;padding:10px;color:white;font-size:0.8em;width:140px;margin-right:10px;"><center>NORTHERN IL / WISC</center> </div></a> </td><td> <a href="http://onehopeunited.org/news/central-southern-illinois-missouri/" style="text-decoration:none;"><div class="yellowbutton" style="border-radius:10px;padding:10px;color:black;font-size:0.8em;width:240px;margin-right:10px;"><center>CENTRAL & SOUTHERN IL / MISSOURI</center> </div></a> </td><td> <a href="http://onehopeunited.org/news/florida/" style="text-decoration:none;"><div class="bluebutton" style="border-radius:10px;padding:10px;color:white;font-size:0.8em;width:120px;"><center>FLORIDA</center> </div></a> </td> </tr> </table> <br /> <?php while (have_posts()) : the_post(); ?> <div style="border:1px solid #c8c9ca;background:#f1f2f3;margin-bottom:20px;border-radius:7px;padding:15px;line-height:1.4em;"> <span style="color:#757575;font-size:0.8em;text-transform:uppercase;font-weight:bold;"><?php if ( in_category('everyday-heroes') ) { echo '<img src="http://onehopeunited.org/wp-content/themes/ohu/images/everyday-heroes.gif" style="vertical-align:middle;"> Everyday Heroes'; } elseif ( in_category('in-the-news') ) { echo '<img src="http://onehopeunited.org/wp-content/themes/ohu/images/in-the-news.gif" style="vertical-align:middle;"> In The News'; } elseif ( in_category('press-releases') ) { echo '<img src="http://onehopeunited.org/wp-content/themes/ohu/images/press-releases.gif" style="vertical-align:middle;"> Press Releases'; } elseif ( in_category('stories-of-hope') ) { echo '<img src="http://onehopeunited.org/wp-content/themes/ohu/images/stories-of-hope.gif" style="vertical-align:middle;"> Stories of Hope'; } ?> | </span> <span style="color:#d03b3e;font-size:0.8em;font-weight:bold;"><?php if ( in_category('florida') ) { echo 'Florida'; } elseif ( in_category('hudelson') ) { echo 'Central & Southern IL / Missouri'; } elseif ( in_category('northern') ) { echo 'Northern Illinois / Wisconsin'; } ?></span> <br /> <a href="<?php the_permalink(); ?>" style="color:black;font-weight:bold;"><b><?php the_title(); ?></b></a><br /> Published <?php the_time('F j, Y'); ?><br /><br /> <?php the_content(''); ?> <?php comments_number( '0 comments', '1 comment', '% comments' ); ?> &nbsp;&nbsp; <a href="https://twitter.com/share?url=http://onehopeunited.org/?p=<?php the_ID(); ?>&text=<?php the_title(); ?> -" target="_blank"><img src="http://onehopeunited.org/wp-content/themes/ohu/images/twitter.png"></a> &nbsp;&nbsp; <a title="Share this on Facebook" target="_blank" href="http://www.facebook.com/sharer.php?s=100&p[url]=<?php the_permalink() ?>&p[images][0]=<?php $key="thumbnail"; echo get_post_meta($post->ID, $key, true); ?>&p[title]=<?php the_title(); ?>&p[summary]=<?php echo excerpt(30); ?>"><img src="http://onehopeunited.org/wp-content/themes/ohu/images/facebook.png"></a></div> <?php endwhile; ?> <?php twentyeleven_content_nav( 'nav-below' ); ?> <?php comments_template( '', true ); ?> </div><!-- #content --> </div><!-- #primary --> <?php get_footer(); ?>
onehopeunited/onehopeunited
wp-content/themes/ohu/single-news-post.php
PHP
gpl-2.0
7,965
/* STYLE FOR SHORTCODE TEAM MEMBERS INCLUDE 4 STYLES */ .wd_meet_team { line-height:0; text-align:center; width:100%; max-width:350px; margin:0 0 20px; } .wd_meet_team > div { padding:10px; line-height:14px; } .wd_meet_team .info h3 { font-size: 16px; line-height: 18px; margin: 0 0 5px; } .wd_meet_team .info h3 a { font-size: 16px; line-height: 18px; text-transform:uppercase; } .wd_meet_team .info p { margin: 0 0 5px; } .wd_meet_team .social a { position:relative; font-size: 0; line-height: 0; display: inline-block; width: 35px; height: 35px; margin: 0 0 2px 0; overflow: hidden; color: transparent; background: url(../images/social_team_member.png) no-repeat; } .wd_meet_team .social a:hover { top:-2px; } .wd_meet_team .social a.facebook_link { background-position: 0 0; } .wd_meet_team .social a.twitter_link { background-position: -35px 0; } .wd_meet_team .social a.google_link { background-position: -71px 0; } .wd_meet_team .social a.linkedlin_link { background-position: -105px 0; } .wd_meet_team .social a.rss_link { background-position: -176px 0; } .wd_meet_team .social a.dribble_link { background-position: -140px 0; } /* TEAM MEMBER STYLE O1 */ .wd_meet_team.style1 { overflow: hidden; position: relative; line-height: 0; } .wd_meet_team.style1 > a { display: inline-block; line-height: 0; width: 100%; } .wd_meet_team.style1 > a img { margin: 0; width: 100%; height: auto; transition: all 0.7s ease-in-out 0s; -moz-transition: all 0.7s ease-in-out 0s; -webkit-transition: all 0.7s ease-in-out 0s; } .wd_meet_team.style1:hover > a img { opacity: 0; filter: alpha(opacity=0)transform:scale(10); -moz-transform: scale(10); -webkit-transform: scale(10); -o-transform: scale(10); } .wd_meet_team.style1 > div { overflow: hidden; position: absolute; left: 0; top: 0; right: 0; bottom: 0; padding: 10px; opacity: 0; filter: alpha(opacity=0); background: #702c19; transition: all 1s ease-in-out 0s; -moz-transition: all 1s ease-in-out 0s; -webkit-transition: all 1s ease-in-out 0s; } .wd_meet_team.style1 > div:before { content:""; display:inline-block; height:100%; vertical-align:middle; } .wd_meet_team.style1:hover > div { opacity: 1; filter: alpha(opacity=1); } .wd_meet_team.style1 .info { display:inline-block; width:90%; overflow: hidden; line-height: 14px; vertical-align:middle; transform: scale(0,0); -moz-transform: scale(0,0); -webkit-transform: scale(0,0); } .wd_meet_team.style1:hover .info { transform: scale(1,1); -moz-transform: scale(1,1); -webkit-transform: scale(1,1); transition: all 0.7s ease-in-out 0s; -moz-transition: all 0.7s ease-in-out 0s; -webkit-transition: all 0.7s ease-in-out 0s; } .wd_meet_team.style1 .info h3 a { color:#fff; } .wd_meet_team.style1 .wd_des { display:none; } /* TEAM MEMBER STYLE 02 */ .wd_meet_team.style2 { background:#D6D6D6; border-bottom:5px solid #5C5C5C; } .wd_meet_team.style2 > a { display:inline-block; max-width:100%; line-height:0; overflow:hidden; position:relative; } .wd_meet_team.style2 > a:after { content:""; position:absolute; top:0; bottom:0; right:0; left:0; opacity:0; filter:alpha(opacity=0); background:#702C19 url(../images/icon_search.png) no-repeat 50% 50%; } .wd_meet_team.style2 > a:hover:after { opacity:1; filter:alpha(opacity:1); transition: all 1s ease-in-out 0s; -moz-transition: all 1s ease-in-out 0s; -webkit-transition: all 1s ease-in-out 0s; } .wd_meet_team.style2 > a > img { margin:0; transition: all 0.7s ease-in-out 0s; -moz-transition: all 0.7s ease-in-out 0s; -webkit-transition: all 0.7s ease-in-out 0s; } .wd_meet_team.style2 > a:hover > img { transform: scale(1.5,1.5); -moz-transform: scale(1.5,1.5); -webkit-transform: scale(1.5,1.5); } /* TEAM MEMBER STYLE 03 */ .wd_meet_team.style3 { position: relative; overflow: hidden; border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); } .wd_meet_team.style3 p, .wd_meet_team.style3 a { color: #fff; } .wd_meet_team.style3 > a { display: inline-block; max-width: 100%; overflow:hidden; } .wd_meet_team.style3 > a > img { margin: 0; border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; ransition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style3 > div { position: absolute; left: 0; top: 0; right: 0; bottom: 0; text-align: center; border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style3 > div:before { content:""; display:inline-block; height:100%; vertical-align:middle; } .wd_meet_team.style3 > div:hover { box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); } .wd_meet_team.style3 > div > div { display:inline-block; vertical-align:middle; transform: scale(0,0); -moz-transform: scale(0,0); -webkit-transform: scale(0,0); transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style3 > div:hover > div { transform: scale(1,1); -moz-transform: scale(1,1); -webkit-transform: scale(1,1); } .wd_meet_team.style3:hover > a img { transform:scale(1.2,1.2); -moz-transform:scale(1.2,1.2); -webkit-transform:scale(1.2,1.2); } .wd_meet_team.style3 .wd_des { display:none; } /* TEAM MEMBER STYLE 04 */ .wd_meet_team.style4 { background:#d6d6d6; border-bottom:5px solid #5c5c5c; border-radius:350px 350px 0 0; -moz-border-radius:350px 350px 0 0; -webkit-border-radius:350px 350px 0 0; } .wd_meet_team.style4 > a { z-index: 1; display: inline-block; position: relative; max-width: 100%; overflow:hidden; border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style4 > a:after { z-index: 2; content: ""; position: absolute; left: 0; right: 0; top: 0; bottom: 0; background:url(../images/icon_search.png) no-repeat 50% 50%; opacity:0; filter:alpha(opacity=0); border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 0 0 rgba(200, 95, 66, 0.4) inset, 0 0 0 16px rgba(255, 255, 255, 0.6) inset, 0 1px 2px rgba(0, 0, 0, 0.1); transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style4 > a:hover:after { opacity:1; filter:alpha(opacity=1); box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 0 0 0 180px rgba(119, 53, 21, 0.5) inset, 0 0 0 16px rgba(119, 53, 21, 0.8) inset, 0 1px 2px rgba(0, 0, 0, 0.1); } .wd_meet_team.style4 > a img { margin: 0; border-radius: 100%; -moz-border-radius: 100%; -webkit-border-radius: 100%; transition: all 0.4s ease-in-out 0s; -moz-transition: all 0.4s ease-in-out 0s; -webkit-transition: all 0.4s ease-in-out 0s; } .wd_meet_team.style4:hover > a img { transform:scale(1.2,1.2); -moz-transform:scale(1.2,1.2); -webkit-transform:scale(1.2,1.2); }
usualdesigner/usualdesigner-wp-1
wp-content/plugins/wd_shortcode/css/team.css
CSS
gpl-2.0
9,293